JWT生成token,验证身份

JWT生成token,验证身份

1.添加依赖:

		<dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.10.3</version>
        </dependency>
        
         <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>

2.创建JWT工具类:用于生成token和解析token

package com.wecar.config;

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

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT 工具类,用来加密和解密用户名
 * @author
 * */
public class JWTUtils {
    /**issu :签发人*/
    String issu = "wecar";

    public String token(Map map){
        Algorithm algorithmHS = Algorithm.HMAC256("secret");
        long l = System.currentTimeMillis();
        l+=7*24*60*60*1000;
        Date date = new Date(l);
        Map headMap = new HashMap<>();
        /**签名算法*/
        headMap.put("alg","HS256");
        /**生成jwt*/
        headMap.put("typ","jwt");

        //签发人
        String sign = JWT.create()
                .withHeader(headMap).
                        withSubject("token")
                .withIssuer(issu)
                .withClaim("body", map)
                .withIssuedAt(new Date())
                .withExpiresAt(date)
                .sign(algorithmHS);
        return sign;
    }

    //解密
    public Map Verify(String token){
        Algorithm algorithm = Algorithm.HMAC256("secret");
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(issu).build();
        try{
            DecodedJWT verify = verifier.verify(token);
            Claim body = verify.getClaim("body");
            Map<String, Object> stringObjectMap = body.asMap();
            return stringObjectMap;
        }catch (Exception e){
            return null;
        }
    }
}

3.添加Interceptor拦截器:在preHandle方法中添加逻辑

package com.wecar.config.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.wecar.config.CookieUtils;
import com.wecar.config.JWTUtils;
import com.wecar.config.interceptor.BaseResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 登录状态验证以及拦截器
 * @author
 * */
@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
   
        BaseResp baseResp = new BaseResp();     	//自定义返回值
        Cookie[] cookies = request.getCookies();    //从浏览器中获取cookie
        if (cookies==null || cookies.length==0){
            baseResp.setMessage("nologin");       //浏览器cookie为空,不通过
            baseResp.setCode(2002);
            return false;							//返回false,已被拦截
        }
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(cookies);
        //解密
        JWTUtils jwtUtils = new JWTUtils();
        Map verify = jwtUtils.Verify(token);
        if (verify==null || verify.get("adminName")==null){
            baseResp.setMessage("登录失效");    
            baseResp.setCode(2001);
            return false;
        }else {
            return true;   //放行
        }
    }
}

4.添加拦截器的配置文件:

package com.wecar.config;

import com.wecar.config.interceptor.RequestInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Created by 54110 on 2020/12/24.
 * 拦截器配置类
 * addPathPatterns:表示所有的路径进行拦截
 * excludePathPatterns :排除哪些路径不被拦截
 */
@Configuration
public class RequestWebConfig implements WebMvcConfigurer{

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/admin/login");
    }
}

5.逻辑层核心代码:

附加:

1.cookieUtils工具类
package com.wecar.config;
import javax.servlet.http.Cookie;

/**
 * cookie工具类,生成token
 * @author
 * */
public class CookieUtils {

    public String getToken(Cookie[] cookies){
        String token ="";
        if (cookies==null||cookies.length==0){
            return null;
        }
        for (Cookie cook:cookies
        ) {
            String name = cook.getName();
            if(name.equals("token")){
                token=cook.getValue();
                return token;
            }
        }
        return null;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值