SpringBoot-Security-用户权限分配-配置验证规则

Spring Security配置

Spring Security配置是通过 @EnableWebSecurity注释和WebSecurityConfigurerAdapter共同提供基于网络的安全性。

WebSecurityConfigurerAdapter类的configure(HttpSecurity http)方法是设置 HTTP 验证规则,configure(AuthenticationManagerBuilder auth)方法是自定义身份验证组件

/**
 * @Author xiangjian
 * @Date 2019/2/24
 * @Description 实现WebSecurityConfigurerAdapter接口,
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}

/**
 * 设置 HTTP 验证规则
 * 复写这个方法来配置 {@link HttpSecurity}.
 * 通常,子类不能通过调用 super 来调用此方法,因为它可能会覆盖其配置。 默认配置为:
 * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
 * 匹配 "/" 路径,不需要权限即可访问
 * 匹配 "/user" 及其以下所有路径,都需要 "USER" 权限
 * 登录地址为 "/login",登录成功默认跳转到页面 "/user"
 * 退出登录的地址为 "/logout",退出成功后跳转到页面 "/login"
 * 默认启用 CSRF
 * 用于配置权限认证的方式
 * @param http
 * @throws Exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    //cors解决跨域问题
    http.cors().and()
            //关闭跨站请求伪造
            .csrf().disable()
            .authorizeRequests()
            //api要允许匿名访问
            .antMatchers(HttpMethod.OPTIONS).permitAll()
            .antMatchers("/api/**").permitAll()
            .antMatchers("/", "/*.html","/favicon.ico", "/css/**", "/js/**").permitAll().anyRequest().authenticated();
    // 基于token,所以不需要session
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    // 解决不允许显示在iframe的问题
    http.headers().frameOptions().disable();
    // 禁用缓存
    http.headers().cacheControl();
    http.addFilter(new JWTLoginFilter(authenticationManager()));
    http.addFilterBefore(new JWTAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
}
   /**
 * 使用自定义身份验证组件
 * 重写安全认证,加入密码加密方式
 * @param auth
 * @throws Exception
 */
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}

http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)方法说明:
Spring Security下的枚举SessionCreationPolicy,管理session的创建策略
ALWAYS:总是创建HttpSession
IF_REQUIRED:Spring Security只会在需要时创建一个HttpSession
NEVER:Spring Security不会创建HttpSession,但如果它已经存在,将可以使用HttpSession
STATELESS:Spring Security永远不会创建HttpSession,它不会使用HttpSession来获取SecurityContext

spring-security主要包含二部分:第一是用户验证,第二是鉴权。

用户验证:UsernamePasswordAuthenticationFilter去进行用户账号的验证
鉴权:BasicAuthenticationFilter去进行用户权限的验证

JWTLoginFilter继承于UsernamePasswordAuthenticationFilter
用于获取用户登录的信息,创建一个token并调用authenticationManager.authenticate()让spring-security去进行验证

JWTAuthenticationFilter继承于BasicAuthenticationFilte用于权限验证,,每一次请求都需要检查该用户是否有该权限去操作该资源

JWTLoginFilter类

核心功能是在验证用户名密码正确后,生成一个token,并将token返回给客户端
该类继承自UsernamePasswordAuthenticationFilter,重写了其中的2个方法:
attemptAuthentication :接收并解析用户凭证。
successfulAuthentication :用户成功登录后,这个方法会被调用,我们在这个方法里生成token。

/**
* 验证用户名密码正确后,生成一个token,并将token返回给客户端
* 该类继承自UsernamePasswordAuthenticationFilter,重写了其中的2个方法
* attemptAuthentication :接收并解析用户凭证。
* successfulAuthentication :用户成功登录后,这个方法会被调用,我们在这个方法里生成token。
*/
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

private AuthenticationManager authenticationManager;

  public JWTLoginFilter(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
}

// 接收并解析用户凭证
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
                                            HttpServletResponse response) throws AuthenticationException {
    try {
        SysUserDto user = GsonUtil.getInstance().fromJson(request.getReader(),SysUserDto.class);
        return authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        user.getUsername(),
                        user.getPassword(),
                        new ArrayList<>()));
    } catch (JsonSyntaxException | JsonIOException | IOException | NullPointerException e) {
        e.printStackTrace();
        ResultBean result = new ResultBean<>();
        result.setState(1);
        result.setErrorMsg("参数格式错误");
        ResponseUtil.responseJson(response, HttpStatus.BAD_REQUEST.value(), result);
    }
    return null;
}

@Override
protected void successfulAuthentication(HttpServletRequest request,
                                        HttpServletResponse response,
                                        FilterChain chain,
                                        Authentication auth) throws IOException, ServletException {
    LoginUserDetail loginUser = (LoginUserDetail) auth.getPrincipal();
    String tokenStr = Jwts.builder()
            .setSubject(loginUser.getUsername())
            // 使用Cache记录jwt的token过滤缓存
            // .setExpiration(new Date(System.currentTimeMillis() + 60 * 30 * 1 * 1000))
            .signWith(SignatureAlgorithm.HS512, "CrmJwtSecret")
            .compact();
    JWTCacheUtil.CACHE.add("Bearer " + tokenStr,loginUser);
    Token token = new Token(tokenStr,0L);
    response.addHeader("Authorization", "Bearer " + token);
    ResultBean result = new ResultBean<>();
    result.setState(0);
    ResponseUtil.responseJson(response, HttpStatus.OK.value(), token);
}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
    String msg;
    if (failed instanceof BadCredentialsException) {
        msg = "密码错误";
    } else {
        msg = failed.getMessage();
    }
    ResultBean result = new ResultBean<>();
    result.setState(1);
    result.setErrorMsg(msg);
    ResponseUtil.responseJson(response, HttpStatus.UNAUTHORIZED.value(), result);
    }
   }

JWTAuthenticationFilter类

这个类中实现token的校验功能该类继承自BasicAuthenticationFilter,在doFilterInternal方法中,从http头的Authorization 项读取token数据,然后用Jwts包提供的方法校验token的合法性。如果校验通过,就认为这是一个取得授权的合法请求

/**
* token的校验
* 该类继承自BasicAuthenticationFilter,在doFilterInternal方法中,
* 从http头的Authorization 项读取token数据,然后用Jwts包提供的方法校验token的合法性。
* 如果校验通过,就认为这是一个取得授权的合法请求
*/
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {

public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
    super(authenticationManager);
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    String header = request.getHeader("Authorization");

    if (header == null || !header.startsWith("Bearer ")) {
        chain.doFilter(request, response);
        return;
    }
    UsernamePasswordAuthenticationToken authentication = getAuthentication(request);

    SecurityContextHolder.getContext().setAuthentication(authentication);
    chain.doFilter(request, response);

}

private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
    String token = request.getHeader("Authorization");
    try {
        if (token != null) {
            // parse the token.
            if (JWTCacheUtil.CACHE.exist(token)){
                LoginUserDetail loginUser = (LoginUserDetail) JWTCacheUtil.CACHE.get(token);
                String user = Jwts.parser()
                        .setSigningKey("CrmJwtSecret")
                        .parseClaimsJws(token.replace("Bearer ", ""))
                        .getBody()
                        .getSubject();

                if (user != null) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser,
                            null,  loginUser.getAuthorities());
                    return authentication;
                }
            }
        }
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException
            | io.jsonwebtoken.SignatureException | IllegalArgumentException e) {
        return null;
    }
    return null;
   }
   }

JWT来处理用户名密码的认证。区别在于,认证通过后,服务器生成一个token,将token返回给客户端,客户端以后的所有请求都需要在http头中指定该token。服务器接收的请求后,会对token的合法性进行验证。验证的内容包括:JWT格式、检查签名、检查claims、检查权限

上一篇:排序算法汇总-C++版


下一篇:spring 拦截器 HandlerInterceptor