首页 > 经验记录 > Spring Security集成以及配置

Spring Security集成以及配置

挺多的。。。就直接放上来吧,就不解释什么了。反正有注释。
为的是有一天要用、但是忘了相关的配置可以看这篇文章想起来。
 
 
由于使用security配置,故不需要Redis储存session了,将此相关的全部去掉
 
yml:

#数据库连接属性配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/hospital?serverTimezone=Asia/Shanghai
    username: root
    password: 614
#security配置
  jackson:
    serialization:
      indent_output: true
#mybatis实体类名
mybatis:
  type-aliases-package: top.yibobo.hospital.domain
  configuration:
  #到下划线的表字段自动映射成驼峰命名法
    map-underscore-to-camel-case: true
  mapper-locations: classpath:mybatis/mapper/*.xml
#设置服务器端口号/session保存时长
server:
  port: 8086
#定义日志文件路径
logging:
  file: logs/all.log
  level:
    org.springframework.security: info

 
pom.xml要加的:

<!--security配置-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

 
 
 

package top.yibobo.hospital.security.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import top.yibobo.hospital.domain.Authority;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/*
Spring Security框架服务的用户类
 */
public class JwtUser implements UserDetails {
    private final Integer id;//必须
    private final String username;//必须
    private final String password;//必须
    private final Integer state;
    private final String email;
    private final Date lastPasswordResetDate;
    private final boolean enabled;//必须
    private final Date loginTime;
    //授权的角色集合
    private final Collection<? extends GrantedAuthority> authorities;//必须
    public JwtUser(Integer id, String username, String password, Integer state, String email, Date lastPasswordResetDate, boolean enabled, Date loginTime, Collection<? extends GrantedAuthority> authorities) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.state = state;
        this.email = email;
        this.lastPasswordResetDate = lastPasswordResetDate;
        this.enabled = enabled;
        this.loginTime = loginTime;
        this.authorities = authorities;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }
    @JsonIgnore
    @Override
    public String getPassword() {
        return this.password;
    }
    @Override
    public String getUsername() {
        return this.username;
    }
    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
    @JsonIgnore
    public Integer getId() {
        return id;
    }
    public Integer getState() {
        return state;
    }
    public String getEmail() {
        return email;
    }
    @JsonIgnore
    public Date getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }
    public Date getLoginTime() {
        return loginTime;
    }
}

 

package top.yibobo.hospital.security.domain;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import top.yibobo.hospital.domain.Admins;
import top.yibobo.hospital.domain.Authority;
import java.util.List;
import java.util.stream.Collectors;
public final class JwtUserFactory {
    private JwtUserFactory(){}
    public static JwtUser create(Admins user){
        return new JwtUser(user.getAid(),
                user.getAname(),
                user.getPwd(),
                user.getState(),
                user.getEmail(),
                user.getLastPasswordResetDate(),
                user.getAexist()==1?true:false,
                user.getLoginTime(),
                mapToGrantedAuthorities(user.getAuthorities()));
    }
    /*
    将查询的用户角色集合转化为security框架授权的角色集合
     */
    private static List<GrantedAuthority> mapToGrantedAuthorities(List<Authority> authorities){
        return authorities.stream().map(authority ->
            new SimpleGrantedAuthority(authority.getName().name()))
                .collect(Collectors.toList());
    }
}

 
 

package top.yibobo.hospital.security.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.yibobo.hospital.domain.Admins;
import top.yibobo.hospital.mapper.AdminsMapper;
import top.yibobo.hospital.security.domain.JwtUserFactory;
@Service
public class JwtUserDetailsService implements UserDetailsService{
    @Autowired
    private AdminsMapper adminsMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Admins user = adminsMapper.findByName(s);
        if(user==null){
            throw new UsernameNotFoundException("找不到用户呀呀呀呀呀呀呀呀!!!!");
        }else {
            return JwtUserFactory.create(user);
        }
    }
}

 
 

package top.yibobo.hospital.security.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
 * 安全配置类
 * 配置哪些请求要经过安全检查
 *
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  @Qualifier("jwtUserDetailsService")
  private UserDetailsService userUserDetailsService;
  @Autowired
  public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder
            .userDetailsService(this.userUserDetailsService)
            .passwordEncoder(passwordEncoder());
  }
  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
  @Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
    //安全配置
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()
            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            //.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            // allow anonymous resource requests
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js"
            ).permitAll()
            // 不需要进行安全效验的请求
            .antMatchers(
                    "/auth/**",
                    "/api/users",
                    "/api/testError"
            ).permitAll()
            // 其他api请求都必须做安全效验
            .anyRequest().authenticated();
    // disable page caching
    httpSecurity
            .headers()
            .frameOptions().sameOrigin()  // required to set for H2 else H2 Console will be blank.
            .cacheControl();
  }
}

 

           


CAPTCHAis initialing...

1 COMMENT

EA PLAYER &

历史记录 [ 注意:部分数据仅限于当前浏览器 ]清空

      00:00/00:00