Spring Security 09 整合 JWT

导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
​
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
​
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
​
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.29</version>
</dependency>
​
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.7</version>
</dependency>
​
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>
​
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
​
<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>

JwtUtil

public class JwtUtil {
​
    public static final Long EXPIRE = 700L;
​
    public static final String HEAD = "Authentication";
​
    public static final String SECRET = "nice_try_secret";
​
​
    /**
     * 生成 Token
     *
     * @param username
     * @return
     */
    public static String createToken(String username) {
​
        Date nowDate = new Date();
​
        Date expireDate = new Date(nowDate.getTime() + EXPIRE * 1000);
​
        return Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }
​
​
    /**
     * 获取token中注册信息
     *
     * @param token
     * @return
     */
    public static Claims getTokenClaim(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }
​
​
    /**
     * 校验 Claims 是否 过期
     * @param claim
     * @return
     */
    public static Boolean checkClaimExpire(Claims claim) {
        if (Objects.isNull(claim)) {
            return false;
        }
        Date expiration = claim.getExpiration();
        return expiration.before(new Date());
    }
}

编写 filter

@Component
@Order(-1)
public class JwtFilter extends OncePerRequestFilter {
​
    @Autowired
    private UserService userService;
​
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jwtToken = request.getHeader(JwtUtil.HEAD);
        if (Objects.isNull(jwtToken)){
            filterChain.doFilter(request, response);
            return;
        }
        Claims claim = JwtUtil.getTokenClaim(jwtToken);
        if (Objects.isNull(claim)){
            throw new RuntimeException("token 解析失败");
        }
        Boolean expireFlag = JwtUtil.checkClaimExpire(claim);
        if (expireFlag){
            throw new RuntimeException("token 已失效");
        }
        String username = claim.getSubject();
        User user = userService.loadUserByUsername(username);
        if (Objects.isNull(user)){
            throw new RuntimeException("用户信息失效");
        }
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token);
        filterChain.doFilter(request, response);
    }
}
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
​
    public static final String FORM_CAPTCHA_KEY = "captcha";
​
    private String captchaParameter = FORM_CAPTCHA_KEY;
​
    public String getCaptchaParameter() {
        return captchaParameter;
    }
​
    public void setCaptchaParameter(String captchaParameter) {
        this.captchaParameter = captchaParameter;
    }
​
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        System.out.println("========================================");
​
        if (!request.getMethod().equals("POST")){
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
​
        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)){
            Map<String, String> userInfo = null;
            try {
                userInfo = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
​
            if (Objects.isNull(userInfo)){
                throw new NullPointerException("登入参数为空!登入失败");
            }
​
            String username = userInfo.get(getUsernameParameter());
            String password = userInfo.get(getPasswordParameter());
            String captcha = userInfo.get(getCaptchaParameter());
            String sessionVerifyCode = (String) request.getSession().getAttribute(FORM_CAPTCHA_KEY);
​
            if (ObjectUtils.isEmpty(captcha) || ObjectUtils.isEmpty(sessionVerifyCode)){
                throw new CaptchaNotMatchException("验证码不能为空!");
            }
​
            if (!captcha.equalsIgnoreCase(sessionVerifyCode)){
                throw new CaptchaNotMatchException("验证码不匹配!");
            }
​
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request, response);
    }
}

登入成功处理器

public class LoginSuccessHandler implements AuthenticationSuccessHandler {
​
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
​
        String token = JwtUtil.createToken(authentication.getName());
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "登入成功");
        map.put("status", 200);
        map.put("token", token);
        response.setContentType("application/json;charset=UTF-8");
        String json = new ObjectMapper().writeValueAsString(map);
​
        response.getWriter().println(json);
    }
}

配置

@Configuration
public class WebSecurityConfig {
​
    @Autowired
    private JwtFilter jwtFilter;
​
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }
​
    @Bean
    public LoginFilter loginFilter(AuthenticationManager authenticationManager) {
        LoginFilter filter = new LoginFilter();
​
        filter.setFilterProcessesUrl("/doLogin");
​
        filter.setUsernameParameter("username");
        filter.setPasswordParameter("password");
        filter.setCaptchaParameter("captcha");
​
        filter.setAuthenticationManager(authenticationManager);
​
        filter.setAuthenticationSuccessHandler(new LoginSuccessHandler());
        filter.setAuthenticationFailureHandler(new LoginFailureHandler());
​
        return filter;
    }
​
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .mvcMatchers("/index", "/captcha").permitAll()
                .anyRequest().authenticated()
                .and().formLogin();
​
        // 注销处理
        http.logout()
                .logoutSuccessHandler(new LogoutHandler());
​
        // session 管理 禁用 session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
​
        // 授权、认证异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(new UnAuthenticationHandler())
                .accessDeniedHandler(new UnAbleAccessHandler());
​
        // 不使用 session, csrf 禁用,
        http.csrf().disable();
​
        http.headers().frameOptions().disable();
​
        // 跨域处理方案
        http.cors().configurationSource(configurationSource());
​
        // 添加自定义过滤器
        http.addFilterAt(jwtFilter, LoginFilter.class);
        http.addFilterBefore(loginFilter(http.getSharedObject(AuthenticationManager.class)), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
​
​
    /**
     * 跨域资源配置
     *
     * @return
     */
    public CorsConfigurationSource configurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }
}

操作流程

登入获取 token

请求头携带 token 

不带 token 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值