springboot+JWT

1、生成JWT验证字符串

/**
 * 生成token
 * @param admin Object
 * @return String
 */
public String getToken(Admin admin){
   String token = "";
   //JWT.create()创建token withAudience保存在token中的信息   Algorithm.HMAC256()使用HS256生成token,密钥是用户密码
   token = JWT.create().withAudience(admin.getId()).sign(Algorithm.HMAC256(admin.getPassword()));
   return token;
}

2、设置接口验证

/**
* 给需要验证的接口添加注解 不添加默认不验证
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
   boolean required() default true;
}

3、获取请求token并验证

package com.example.demo.unity;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.demo.dao.Admin;
import com.example.demo.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
* 获取token并验证
*/
public class AuthenticationInterceptor implements HandlerInterceptor {
   @Autowired
   AdminMapper adminMapper;

   @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 中的 user id
               String userId;
               try {
                   userId = JWT.decode(token).getAudience().get(0);
              } catch (JWTDecodeException j) {
                   throw new RuntimeException("401");
              }
               Admin admin = adminMapper.getAdminById(userId);
               if (admin == null) {
                   throw new RuntimeException("用户不存在,请重新登录");
              }
               // 验证 token
               JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
               try {
                   jwtVerifier.verify(token);
              } catch (JWTVerificationException e) {
                   throw new RuntimeException("401");
              }
               return true;
          }
      }
       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 {
  }
}

4、设置拦截器

package com.example.demo.unity;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
   @Override
   public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(authenticationInterceptor())
              .addPathPatterns("/**");//拦截所有请求
  }
   
   //token验证
   @Bean
   public AuthenticationInterceptor authenticationInterceptor() {
       return new AuthenticationInterceptor();
  }
}

5、响应封装+jwt验证使用

@UserLoginToken//开启验证
@RequestMapping("")
public ResponseEntity<Base> login(@RequestBody Map<String,String> person) {
   Base res = new Base(200,"登录成功");
   String name = person.get("name");
   String password = person.get("password");
   Admin admin = adminService.getAdminByName(name);
   if (admin != null){
       String adminPassword = admin.getPassword();
       if (password.equals(adminPassword)){
           Map<String ,String> map = new HashMap<>();
           map.put("name",admin.getName());
           map.put("admin_id",admin.getId());
           String token = res.getToken(admin);
           res.putData("token",token);
           res.putData("data",map);
      }else{
           res.setCode(500);
           res.setMsg("密码错误!");
      }
  }else{
       res.setCode(500);
       res.setMsg("用户不存在!");
  }
   return ResponseEntity.ok(res);
}

 

原文地址:https://www.cnblogs.com/ljkltt/p/14424246.html