spring security怎么生成JWT返回前端,以及怎么自定义JWT认证过滤器

怎么生成JWT返回前端

1.先写一个类,里面含有jwt的生成解析验证过期时间的方法

package com.lzy.util;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Data
@ConfigurationProperties(prefix = "lzy.jwt")

public class JwtUtil {
    Date date = new Date();
    private Long expireDate;
    private String SECRET_KEY;

    //生成JWT
    public String generateToken(String userName) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT") // 设置头部参数
                .setSubject(userName) // 设置主题或用户 ID
                .setIssuedAt(date) // 设置发行时间
                .setExpiration(new Date(date.getTime() + expireDate * 1000)) // 设置过期时间
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY) // 使用 HMAC SHA-256 算法和秘钥签名
                .compact(); // 生成 JWT 字符串
    }


    //解析JWT
    public Claims parseJwt(String jwt) throws Exception {
        try {
            // 解析 JWT 并返回 Claims 对象
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY) // 设置秘钥
                    .parseClaimsJws(jwt)       // 解析 JWT 字符串
                    .getBody();                // 获取 Claims 对象
        } catch (Exception e) {
            return null;
        }
    }
    //JWT是否过期
    /**
     * 检测 JWT 是否过期
     *
     * @param claims JWT 的 Claims 对象
     * @return 是否已过期
     */
    public boolean isJwtExpired(Claims claims) {
        return claims.getExpiration().before(date);
    }

}

变量写在配置类

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/vueadmin?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: Qq702196
    driver-class-name: com.mysql.cj.jdbc.Driver
  redis:
    host: localhost
    port: 6379
    password: 123456
  security:
    user:
      name: lzy
      password: 123456
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
server:
  port: 9270
lzy:
  jwt:
    expireDate: 604800
    SECRET_KEY: fadboabdabodibnkjfbyervrtwqeqdfs


2.在成功执行器中引入

package com.lzy.security;

import cn.hutool.json.JSONUtil;
import com.lzy.common.lang.Result;
import com.lzy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component

public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    JwtUtil jwtUtil;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 将响应的内容类型设置为JSON
        response.setContentType("application/json;charset=utf-8");
        // 获取响应的输出流
        ServletOutputStream out = response.getOutputStream();
        //生成JWT,并且放置到请求头
        String jwt = jwtUtil.generateToken(authentication.getName());
        response.setHeader("Authorization", jwt);
        // 创建一个包含异常消息的Result对象
        Result result = Result.success("成功");
        // 将Result对象转换为JSON字符串,并写入输出流
        out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        // 刷新输出流
        out.flush();
        // 关闭输出流
        out.close();
    }

    }

因为我这里前端是放入的localstorage

成功

怎么自定义JWT认证过滤器

1.先写一个JWT认证过滤器

package com.lzy.security;

import cn.hutool.core.util.StrUtil;
import com.lzy.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    @Autowired
    JwtUtil jwtUtil;
    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }
    //重写父类方法
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //调用父类方法
        String jwt = request.getHeader("Authorization");
        //判断jwt是否为空
        if(StrUtil.isBlankOrUndefined(jwt)){
            chain.doFilter(request,response);
            return;
        }
        //解析jwt
        Claims claims = null;
        try {
            claims = jwtUtil.parseJwt(jwt);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(claims == null){
            throw new JwtException("token无效");
        }
        if (jwtUtil.isJwtExpired(claims)) {
            throw new JwtException("token已过期");
        }
        //获取用户名
        String username = claims.getSubject();
        //获取权限信息
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, null);
        //将用户名和权限信息放入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(token);
        //继续执行过滤器链
        chain.doFilter(request,response);


    }
}

2.再进行引用

package com.lzy.config;
 
import com.lzy.security.CaptchaFilter;
import com.lzy.security.JwtAuthenticationFilter;
import com.lzy.security.LoginFailureHandler;
import com.lzy.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别的权限注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    LoginFailureHandler loginFailureHandler;
    @Autowired
    LoginSuccessHandler loginSuccessHandler;
    @Autowired
    CaptchaFilter captchaFilter;
    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter(authenticationManager());
    }


    private static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/captcha",
            "/favicon.ico", // 防止 favicon 请求被拦截
    };

    protected void configure(HttpSecurity http) throws Exception {

        //跨域配置
        http.cors().and().csrf().disable()
                //登录配置
                .formLogin()
                .successHandler(loginSuccessHandler).failureHandler(loginFailureHandler)
                //禁用session
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //配置拦截规则
                .and().authorizeRequests()
                //白名单
                .antMatchers(URL_WHITELIST).permitAll()
                //其他请求都需要认证
                .anyRequest().authenticated()
                //异常处理器
                .and().addFilter(jwtAuthenticationFilter())
                //配置自定义的过滤器
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class);

    }
 
}

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值