SpringBoot集成JWT(极简版)(springboot集成jpa)

  本篇文章为你整理了SpringBoot集成JWT(极简版)(springboot集成jpa)的详细内容,包含有springboot集成jedis springboot集成jpa springboot集成jenkins springboot集成jdbctemplate SpringBoot集成JWT(极简版),希望能帮助你了解 SpringBoot集成JWT(极简版)。

  在WebConfig配置类中设置接口统一前缀

  

import org.springframework.context.annotation.Configuration;

 

  import org.springframework.web.bind.annotation.RestController;

  import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;

  import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

  @Configuration

  public class WebConfig implements WebMvcConfigurer {

   @Override

   public void configurePathMatch(PathMatchConfigurer configurer) {

   // 指定controller统一的接口前缀

   configurer.addPathPrefix("/api", clazz - clazz.isAnnotationPresent(RestController.class));

  

 

  导入JWT依赖

  

 dependency 

 

   groupId com.auth0 /groupId

   artifactId java-jwt /artifactId

   version 3.10.3 /version

   /dependency

  

 

  JWT工具类TokenUtils.java(生成token的工具类)

  

import cn.hutool.core.date.DateUtil;

 

  import cn.hutool.core.util.StrUtil;

  import com.auth0.jwt.JWT;

  import com.auth0.jwt.algorithms.Algorithm;

  import com.bai.entity.Admin;

  import com.bai.service.AdminService;

  import lombok.extern.slf4j.Slf4j;

  import org.springframework.stereotype.Component;

  import org.springframework.web.context.request.RequestContextHolder;

  import org.springframework.web.context.request.ServletRequestAttributes;

  import javax.annotation.PostConstruct;

  import javax.annotation.Resource;

  import javax.servlet.http.HttpServletRequest;

  import java.util.Date;

  @Component

  @Slf4j

  public class TokenUtils {

   private static AdminService staticAdminService;

   @Resource

   private AdminService adminService;

   @PostConstruct

   public void setUserService() {

   staticAdminService = adminService;

   * 生成token

   * @return

   public static String genToken(String adminId, String sign) {

   return JWT.create().withAudience(adminId) // 将 user id 保存到 token 里面,作为载荷

   .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期

   .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥

   * 获取当前登录的用户信息

   * @return user对象

   * /admin?token=xxxx

   public static Admin getCurrentAdmin() {

   String token = null;

   try {

   HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

   token = request.getHeader("token");

   if (StrUtil.isNotBlank(token)) {

   token = request.getParameter("token");

   if (StrUtil.isBlank(token)) {

   log.error("获取当前登录的token失败, token: {}", token);

   return null;

   String adminId = JWT.decode(token).getAudience().get(0);

   return staticAdminService.getById(Integer.valueOf(adminId));

   } catch (Exception e) {

   log.error("获取当前登录的管理员信息失败, token={}", token, e);

   return null;

  

 

  拦截器JwtInterceptor.java

  

 

 

  import cn.hutool.core.util.StrUtil;

  import com.auth0.jwt.JWT;

  import com.auth0.jwt.JWTVerifier;

  import com.auth0.jwt.algorithms.Algorithm;

  import com.auth0.jwt.exceptions.JWTVerificationException;

  import com.bai.entity.Admin;

  import com.bai.exception.ServiceException;

  import com.bai.service.AdminService;

  import lombok.extern.slf4j.Slf4j;

  import org.springframework.beans.factory.annotation.Autowired;

  import org.springframework.stereotype.Component;

  import org.springframework.web.servlet.HandlerInterceptor;

  import javax.servlet.http.HttpServletRequest;

  import javax.servlet.http.HttpServletResponse;

  import javax.servlet.http.HttpSession;

  @Component

  @Slf4j

  public class LoginJWTInterceptor implements HandlerInterceptor {

   private static final String ERROR_CODE_401 = "401";

   @Autowired

   private AdminService adminService;

   @Override

   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

   //这里是判断浏览器请求头里的token

   String token = request.getHeader("token");

   if (StrUtil.isBlank(token)) {

   token = request.getParameter("token");

   // 执行认证

   if (StrUtil.isBlank(token)) {

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

   // 获取 token 中的adminId

   String adminId;

   Admin admin;

   try {

   adminId = JWT.decode(token).getAudience().get(0);

   // 根据token中的userid查询数据库

   admin = adminService.getById(Integer.parseInt(adminId));

   } catch (Exception e) {

   String errMsg = "token验证失败,请重新登录";

   log.error(errMsg + ", token=" + token, e);

   throw new ServiceException(ERROR_CODE_401, errMsg);

   if (admin == null) {

   throw new ServiceException(ERROR_CODE_401, "用户不存在,请重新登录");

   try {

   // 用户密码加签验证 token

   JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();

   jwtVerifier.verify(token); // 验证token

   } catch (JWTVerificationException e) {

   throw new ServiceException(ERROR_CODE_401, "token验证失败,请重新登录");

   return true;

  

 

  在WebConfig配置类中添加自定义拦截器

  

 

 

  import org.springframework.beans.factory.annotation.Autowired;

  import org.springframework.context.annotation.Configuration;

  import org.springframework.web.bind.annotation.RestController;

  import org.springframework.web.servlet.config.annotation.CorsRegistry;

  import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

  import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;

  import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

  @Configuration

  public class WebConfig implements WebMvcConfigurer {

   @Autowired

   private LoginJWTInterceptor loginJWTInterceptor;

   @Override

   public void configurePathMatch(PathMatchConfigurer configurer) {

   // 指定controller统一的接口前缀

   configurer.addPathPrefix("/api", clazz - clazz.isAnnotationPresent(RestController.class));

   // 加自定义拦截器JwtInterceptor,设置拦截规则

   //.excludePathPatterns("/api/admin/login");放开登录接口,因为登录的时候还没有token

   @Override

   public void addInterceptors(InterceptorRegistry registry) {

   registry.addInterceptor(loginJWTInterceptor) // 添加所有路径需要校验

   .addPathPatterns("/api/**").excludePathPatterns("/api/admin/login", "/api/admin/register");//不需要拦截的接口

  

 

  设置自定义头配置(前端在request拦截器设置自定义头)

  

import org.springframework.context.annotation.Bean;

 

  import org.springframework.context.annotation.Configuration;

  import org.springframework.web.cors.CorsConfiguration;

  import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

  import org.springframework.web.filter.CorsFilter;

  
public CorsFilter corsFilter() {

   UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

   CorsConfiguration corsConfiguration = new CorsConfiguration();

   corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址

   corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头

   corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法

   source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置

   return new CorsFilter(source);

  

 

  以上就是SpringBoot集成JWT(极简版)(springboot集成jpa)的详细内容,想要了解更多 SpringBoot集成JWT(极简版)的内容,请持续关注盛行IT软件开发工作室。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: