java token生成和验证_SpringBoot集成JWT生成token及校验方法过程解析

本文详细介绍了如何在SpringBoot应用中使用JWT进行token的生成与验证。通过创建`JwtTokenUtil`工具类,设置密钥并提供生成与验证token的方法,结合自定义注解`@UserLoginToken`以及拦截器`AuthenticationInterceptor`实现权限控制。登录成功后,后续请求需携带有效token,否则将返回401错误。
摘要由CSDN通过智能技术生成

GitHub源码地址:https://github.com/zeng-xian-guo/springboot_jwt_token.git

封装JTW生成token和校验方法

public class JwtTokenUtil {

//公用密钥-保存在服务端,客户端是不会知道密钥的,以防被攻击

public static String SECRET = "ThisIsASecret";

//生成Troke

public static String createToken(String username) {

//签发时间

//Date iatDate = new Date();

//过地时间 1分钟后过期

//Calendar nowTime = Calendar.getInstance();

//nowTime.add(Calendar.MINUTE, 1);

//Date expiresDate = nowTime.getTime();

Map map = new HashMap();

map.put("alg", "HS256");

map.put("typ", "JWT");

String token = JWT.create()

.withHeader(map)

//.withClaim( "name","Free码生") //设置 载荷 Payload

//.withClaim("age","12")

//.withClaim( "org","测试")

//.withExpiresAt(expiresDate)//设置过期时间,过期时间要大于签发时间

//.withIssuedAt(iatDate)//设置签发时间

.withAudience(username) //设置 载荷 签名的观众

.sign(Algorithm.HMAC256(SECRET));//加密

System.out.println("后台生成token:" + token);

return token;

}

//校验TOKEN

public static boolean verifyToken(String token) throws UnsupportedEncodingException{

JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();

try {

verifier.verify(token);

return true;

} catch (Exception e){

return false;

}

}

//获取Token信息

public static DecodedJWT getTokenInfo(String token) throws UnsupportedEncodingException{

JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();

try{

return verifier.verify(token);

} catch(Exception e){

throw new RuntimeException(e);

}

}

}

新建自定义注解:@UserLoginToken

@Target({ElementType.METHOD, ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

public @interface UserLoginToken {

boolean required() default true;

}

关于拦截器配置:

@Configuration

public class InterceptorConfig implements WebMvcConfigurer {

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(authenticationInterceptor())

.addPathPatterns("/**"); // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录

}

@Bean

public AuthenticationInterceptor authenticationInterceptor() {

return new AuthenticationInterceptor();

}

}

public class AuthenticationInterceptor implements HandlerInterceptor {

@Autowired

UserService userService;

@Override

public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {

String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token

// 如果不是映射到方法直接通过

if(!(object instanceof HandlerMethod)){

return true;

}

HandlerMethod handlerMethod=(HandlerMethod)object;

Method method=handlerMethod.getMethod();

//检查是否有passtoken注释,有则跳过认证

if (method.isAnnotationPresent(PassToken.class)) {

PassToken passToken = method.getAnnotation(PassToken.class);

if (passToken.required()) {

return true;

}

}

//检查有没有需要用户权限的注解

if (method.isAnnotationPresent(UserLoginToken.class)) {

UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);

if (userLoginToken.required()) {

// 执行认证

if (token == null) {

throw new RuntimeException("无token,请重新登录");

}

// 验证 token

if(JwtTokenUtil.verifyToken(token)){

return true;

}else {

throw new RuntimeException("401");

}

}

}

return true;

}

@Override

public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

}

@Override

public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

}

}

登录:

在Controller上登录方法不用添加@UserLoginToken自定义注解,其余获取后台数据方法加上@UserLoginToken自定义注解,目的验证token是否有效,是则返回数据,否则提示401无权限。

测试:

@Controller

@RequestMapping(path = "/api")

public class IndexController {

private String prefix = "index/";

@GetMapping("/index")

public String index()

{

return prefix + "index";

}

@UserLoginToken

@PostMapping("/test")

@ResponseBody

public Object test(){

Map map = new HashMap<>();

map.put("code","200");

map.put("message","你已通过验证了");

return map;

}

}

HTTP请求带上登陆成功后生成token,返回成功:

2bf8ef9ef361c16e18a64b6aed1e8863.png

HTTP请求带上无效token或不带token,返回失败:

1513d01facf3576bbc81b50cc384277e.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

好的,下面我将为您提供前端和SpringBoot使用JWT进行token校验的代码实现。 前端代码实现: 1. 安装jsonwebtoken库 ``` npm install jsonwebtoken ``` 2. 在登录成功后,生成token并存储在本地: ``` import jwt from 'jsonwebtoken'; const token = jwt.sign({ userId: '123456' }, 'secretKey', { expiresIn: '1h' }); localStorage.setItem('token', token); ``` 3. 在发送请求时,将token添加到请求头中: ``` import axios from 'axios'; const token = localStorage.getItem('token'); axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; ``` SpringBoot代码实现: 1. 安装jsonwebtoken库 ``` <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2. 在接收请求时,从请求头中获取token,进行校验: ``` import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import org.springframework.web.filter.OncePerRequestFilter; public class JwtTokenFilter extends OncePerRequestFilter { private final String secretKey = "secretKey"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String authorizationHeader = request.getHeader("Authorization"); if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) { filterChain.doFilter(request, response); return; } String token = authorizationHeader.replace("Bearer ", ""); try { Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody(); int userId = Integer.parseInt(claims.getSubject()); // 根据userId进行相应的权限校验和业务逻辑处理 } catch (Exception e) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token"); } filterChain.doFilter(request, response); } } ``` 3. 在SpringBoot的配置类中,将JwtTokenFilter加入到过滤器链中: ``` import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JwtConfig { @Bean public FilterRegistrationBean<JwtTokenFilter> jwtTokenFilter() { FilterRegistrationBean<JwtTokenFilter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new JwtTokenFilter()); registrationBean.addUrlPatterns("/api/*"); // 需要进行token校验的接口路径 return registrationBean; } } ``` 以上是使用JWT进行token校验的一般步骤和代码实现,需要根据具体的业务场景进行相应的调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值