当前位置:   article > 正文

Springboot集成Security和JWT_springboot security jwt

springboot security jwt

Springboot版本2.3.3

pom依赖

 <!--security+JWT-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
 </dependency>
 <dependency>
     <groupId>io.jsonwebtoken</groupId>
     <artifactId>jjwt</artifactId>
     <version>0.9.1</version>
 </dependency>
 <dependency>
     <groupId>javax.xml.bind</groupId>
     <artifactId>jaxb-api</artifactId>
     <version>2.3.1</version>
 </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Security配置类

/**
 * Security配置类,启用URL过滤,设置PasswordEncoder密码加密类
 * EnableWebSecurity            开启Security
 * EnableGlobalMethodSecurity   保证post之前的注解可以使用
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Config_Security extends WebSecurityConfigurerAdapter {

    @Resource
    private IUmsMemberService memberService;
    @Resource
    private SecurityAccessDeniedHandler restfulAccessDeniedHandler;
    @Resource
    private SecurityAuthenticationEntryPoint restAuthenticationEntryPoint;


    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)
     * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问
     * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
     * hasRole             |   如果有参数,参数表示角色,则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf()                 //由于使用的是JWT,我们这里不需要csrf
                .disable()
                .sessionManagement()        //基于token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, //允许对于网站静态资源的无授权访问
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger.**",
                        "/v3.**",
                        "**_notify_url"
                ).permitAll()
                .antMatchers("/LoginSecurity", "/Register").permitAll()         //对登录注册要允许匿名访问
                .antMatchers(HttpMethod.OPTIONS).permitAll()                    //跨域请求会先进行一次options请求
//                .antMatchers("/**").permitAll()                               //测试时全部运行访问
                .anyRequest()                                                   //除上面外的所有请求全部需要鉴权认证
                .authenticated();
        //禁用缓存
        httpSecurity.headers().cacheControl();
        //添加JWTFilter
        httpSecurity.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }


    /**
     * 重写身份认证接口configure
     * 其中userDetailsService为自定义用户认证逻辑接口
     * 其中bCryptPasswordEncoder()为加密接口
     * 使用authenticationManager.authenticate用户验证的时候,该方法会调用我们接口逻辑接口的实现类UserDetailsServiceImpl.loadUserByUsername
     * 就是下面的userDetailsService方法
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    /**
     * 认证过程中SpringSecurity会调用这个方法访问数据库进行对用户的搜索,逻辑什么都可以自定义,无论是从数据库中还是从缓存中
     * 我们需要将我们查询出来的用户信息和权限信息组装成一个UserDetails返回。
     * UserDetails也是一个定义了数据形式的接口,用于保存我们从数据库中查出来的数据,其功能主要是验证账号状态和获取权限
     */
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            //获取登录用户信息
            UmsMember u = memberService.GetByNameMember(username);
            if (u == null) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
            return new SecurityUserDetails(username,u.getPassword(),null);
        };
    }

    /**
     * 自定义加密器Bean
     * 强散列哈希加密实现,在Controller新增用户的时候用此bean生成密码,与及修改密码的时候用到此bean比较新旧密码是否匹配
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * JWT过滤器
     */
    @Bean
    public SecurityJwtFilter jwtFilter() {
        return new SecurityJwtFilter();
    }

    /**
     * 定义AuthenticationManager
     * 声明它的作用是用它帮我们进行认证操作,调用这个Bean的authenticate方法会由Spring Security自动帮我们做认证
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124

权限不足处理器

/**
 * 权限不足处理器
 */
@Component
public class SecurityAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        ResponseCon<?> responseCon = new ResponseCon<>(401, "没有权限", e.getMessage());
        response.getWriter().println(GsonUtil.getGson().toJson(responseCon));
        response.getWriter().flush();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

token认证失败处理器

/**
 * 认证失败处理器
 */
@Component
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        ResponseCon<?> responseCon = new ResponseCon<>(401,"身份认证失败", authException.getMessage());
        response.getWriter().println(GsonUtil.getGson().toJson(responseCon));
        response.getWriter().flush();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

JWT过滤器


/** 
 * JwtFilter过滤器
 */

@Slf4j
public class SecurityJwtFilter extends OncePerRequestFilter {

    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private SecurityJwtUtil securityJwtUtil;

    private final String Authorization = "Authorization";
    private final String tokenHead = "Bearer";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        //拿到Authorization请求头内的Header信息
        String authHeader = request.getHeader(Authorization);

        //判断一下内容是否为空且是否为(Bearer)开头
        if (authHeader != null && authHeader.startsWith(tokenHead)) {

            //去掉token前缀(Bearer),拿到真实token
            String authToken = authHeader.substring(tokenHead.length());

            //拿到token里面的username
            String username = securityJwtUtil.getUsername(authToken);

            //然后看看上下文中是否有我们以这个username为标识的主体,没有去new一个
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                //缓存里查询用户,不存在需要重新登陆
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                //拿到用户信息后验证用户信息与token
                if (securityJwtUtil.validateToken(authToken, userDetails)) {

                    //组装authentication对象,构造参数是Principal Credentials与Authorities
                    //后面的拦截器里面会用到grantedAuthorities 方法
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    //将authentication信息放入到上下文对象中, 这样后面的过滤器看到我们上下文对象中有authentication对象,就相当于我们认证过了
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    log.info("校验token-登录成功, user: {}", username);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

JWT工具类


/**
 * jwtToken工具类
 */
@Slf4j
@Component
public class SecurityJwtUtil {

    //一天过期
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    //解密jwt-token的密钥
    private static final String secret = "mySecret";

    /**
     * 生成token
     */
    public static String sign(String username, String loginType) {
        return Jwts.builder()
                .claim("username", username)
                .claim("loginType", loginType)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 根据token解密出用户名
     */
    public String getUsername(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return null;
    }

    /**
     * 根据token解密出登录类型
     */
    public String getLoginType(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return (String) claims.get("loginType");
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return null;
    }
    /**
     * 根据token解密出过期时间
     */
    public Date getExpiredDate(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
            return claims.getExpiration();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return null;
    }



    /**
     * 判断token是否已经过期
     */
    public boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDate(token);
        return expiredDate.before(new Date());
    }
    /**
     * 判断token是否可以被刷新
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }
    /**
     * 验证token与数据库中token是否一致
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUsername(token);
        assert username != null;
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87

UserDetails

/**
 * SpringSecurity包装的用户信息
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SecurityUserDetails extends UmsMember implements UserDetails {

    private Collection<? extends GrantedAuthority> authorities;

    //返回当前用户的权限
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    public SecurityUserDetails(String userName, String password, Collection<? extends GrantedAuthority> authorities){
        this.authorities = authorities;
        this.setUsername(userName);
        this.setPassword(new BCryptPasswordEncoder().encode(password));
        this.setAuthorities(authorities);
    }

    /**
     * 账户是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return false;
    }
    /**
     * 是否禁用
     */
    @Override
    public boolean isAccountNonLocked() {
        return false;
    }
    /**
     * 密码是否过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }
    /**
     * 是否启用
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

一共6个类

登录注册Controller

 @Resource
 private BCryptPasswordEncoder passwordEncoder;

    //登录:http://localhost:8080/LoginSecurity
    @RequestMapping(value = "/LoginSecurity", method = RequestMethod.POST)
    public ResponseCon<?> LoginSecurity(String username, String password) {
        UmsMember member = memberService.GetByNameMember(username);
        log.info("进入controller-member信息: {}", member);
        if (member != null) {
            if(passwordEncoder.matches(password,member.getPassword())){
                log.info("用户名正确, 密码正确");
                member.setToken(SecurityJwtUtil.sign(username, "user"));
                ...
                return new ResponseCon<>(200, "success", member);
            } else {
                log.info("用户名正确, 密码错误");
            }
        }
        return new ResponseCon<>(401, "error", "用户名或密码错误");
    }

    //注册:http://localhost:8080/Register
    @RequestMapping(value = "/Register", method = RequestMethod.POST)
    public boolean Register_OK(String username, String password, String phone) {
            password = passwordEncoder.encode(password);
            UmsMember mb = new UmsMember();
            mb.setPhone(phone);
            mb.setUsername(username);
            mb.setPassword(password);
            ...
            return true;
    }

    //测试:http://localhost:8080/TestTokenSecurity
    @RequestMapping(value = "/TestTokenSecurity", method = RequestMethod.POST)
    public ResponseCon<?> TestTokenSecurity() {
        return new ResponseCon<>(200, "success", "测试成功!");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

前端测试

第一次登录直接进controller验证用户名和密码,返回token
下次请求头都带上token,就会被security拦截去校验…

(不明白为啥非要加Bearer)
在这里插入图片描述
这篇写的很详细想深究去看看

https://blog.csdn.net/he_erduo/article/details/107178856
  • 1

刷新token下次补全…

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/388665
推荐阅读
相关标签
  

闽ICP备14008679号