SpringBoot 整合JWT

2021-03-05 08:27

阅读:563

标签:build   进入   handler   type   obj   void   配置   control   算法   

1、依赖

        com.auth0
            java-jwt
            3.4.0

2、JWT工具类生成

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtils {
   public static final String SING="asdasdadada";
   //生成token
   public  static  String getToken(Map map){
       Calendar instance=Calendar.getInstance();
       instance.add(Calendar.DATE,7);//默认过期时间
       //创建jet builder
       JWTCreator.Builder builder= JWT.create();
       //payload
       map.forEach((k,v)->{
           builder.withClaim(k,v);
       });
       String token = builder.withExpiresAt(instance.getTime())//指定国企时间
               .sign(Algorithm.HMAC256(SING));
       return token;
   }
   //验证token
    public static DecodedJWT verify(String token){
       return   JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
    //获取token信息方法
//    public static DecodedJWT getTokenInfo(String token){
//        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
//        return verify;
//    }
}

3、JWT拦截器

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.vuetest01.library.entity.Userregister;
import com.example.vuetest01.library.utils.Consts;
import com.example.vuetest01.library.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        JSONObject jsonObject=new JSONObject();
        try {
            DecodedJWT verify = JWTUtils.verify(token);//验证令牌
          return true;//-------直接放行
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            jsonObject.put(Consts.MSG,"无效签名");
        }catch (TokenExpiredException e){
            jsonObject.put(Consts.MSG,"tiken过期");
        }catch (AlgorithmMismatchException e){
            jsonObject.put(Consts.MSG,"token算法不一致");
        }catch (Exception e){
            jsonObject.put(Consts.MSG,"token无效");
        }
        jsonObject.put("state",false);//-----设置状态
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(jsonObject);
        return false;
    }
}

5、mvc配置

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(new JWTIntercepter())
                .addPathPatterns("/user/**")
                .excludePathPatterns("/**");//所有的用户都放行
    }
}

6、controller登录测试

    @GetMapping("/login")
    @ResponseBody
    //@CrossOrigin @RequestBody @Validated
   public Object login( Userregister userregister){
     //   session.setAttribute(Consts.NAME,userregister.getUsername());
        System.out.println("进入login...");
        JSONObject jsonObject=new JSONObject();
        Map map=new HashMap();
        try {
            Userregister userregister1 = (Userregister) userregisterService.userLogin(userregister);
            //------------token
            Map map1=new HashMap();
            map1.put("username",userregister1.getUsername());
            map1.put("password",userregister1.getPassword());
            String token = JWTUtils.getToken(map1);

            jsonObject.put(Consts.CODE,201);
            jsonObject.put(Consts.MSG,"认证成功");
            jsonObject.put("token",token);// --------------------
        } catch (Exception e) {
            jsonObject.put(Consts.CODE,500);
            jsonObject.put(Consts.MSG,"认证失败");
        }
        return jsonObject;
    }

    @PostMapping("/user/test")
    @ResponseBody
    public Object testq(){
       JSONObject jsonObject=new JSONObject();
       //处理自己的业务逻辑
        jsonObject.put(Consts.CODE,666);
        jsonObject.put(Consts.MSG,"啦啦啦!德玛西亚");
        return jsonObject;
    }

7、postman测试下即可,我这边token是在请求头里面!

 

SpringBoot 整合JWT

标签:build   进入   handler   type   obj   void   配置   control   算法   

原文地址:https://www.cnblogs.com/JunHello/p/14328197.html


评论


亲,登录后才可以留言!