個人博客開發(fā)之blog-api 項目整合JWT實(shí)現(xiàn)token登錄認(rèn)證

前言

現(xiàn)在前后端分離,基于session設(shè)計到跨越問題,而且session在多臺服器之前同步問題,肯能會丟失,所以傾向于使用jwt作為token認(rèn)證 json web token

  1. 導(dǎo)入java-jwt工具包
 <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.15.0</version>
        </dependency>
  1. 通過jwt生成token

編寫通用TokenService

package cn.soboys.core.authentication;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author kenx
 * @version 1.0
 * @date 2021/6/22 10:23
 * token 操作
 */
@Service("TokenService")
public class TokenService {

    //過期時間單位 毫秒 7*24*60*60*1000
    private final Long tokenExpirationTime = 604800000l;

    /**
     * @param uuid   用戶唯一標(biāo)示
     * @param secret 用戶密碼等
     * @return token生成
     */
    public String generateToken(String uuid, String secret) {
        //每次登錄充當(dāng)前時間重新計算
        Date expiresDate = new Date(System.currentTimeMillis() + tokenExpirationTime);
        String token = "";
        token = JWT.create()
                //設(shè)置過期時間
                .withExpiresAt(expiresDate)
                //設(shè)置接受方信息,一般時登錄用戶
                .withAudience(uuid)// 將 user id 保存到 token 里面
                //使用HMAC算法
                .sign(Algorithm.HMAC256(secret));// 以 password 作為 token 的密鑰
        return token;
    }
}

  1. 編寫注解過濾攔截需要登錄驗(yàn)證的controller

PassToken用于跳過登錄驗(yàn)證UserLoginToken表示需要登錄驗(yàn)證

package cn.soboys.core.authentication;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author kenx
 * @version 1.0
 * @date 2021/6/21 17:21
 * 跳過登錄驗(yàn)證
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
    boolean required() default true;
}

package cn.soboys.core.authentication;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author kenx
 * @version 1.0
 * @date 2021/6/21 17:22
 * 需要登錄驗(yàn)證
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
    boolean required() default true;
}

  1. 編寫業(yè)務(wù)異常AuthenticationException

認(rèn)證失敗拋出認(rèn)證異常AuthenticationException

package cn.soboys.core.authentication;

import lombok.Data;

/**
 * @author kenx
 * @version 1.0
 * @date 2021/6/22 13:58
 * 認(rèn)證異常
 */
@Data
public class AuthenticationException extends RuntimeException {

    public AuthenticationException(String message) {
        super(message);
    }

}

  1. 編寫認(rèn)證攔截器AuthenticationInterceptor,攔截需要認(rèn)證請求
package cn.soboys.core.authentication;

import cn.hutool.extra.spring.SpringUtil;
import cn.soboys.core.ret.ResultCode;
import cn.soboys.mallapi.entity.User;
import cn.soboys.mallapi.service.IUserService;
import cn.soboys.mallapi.service.impl.UserServiceImpl;
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 lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

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

/**
 * @author kenx
 * @version 1.0
 * @date 2021/6/21 17:24
 * 用戶驗(yàn)證登錄攔截
 */

public class AuthenticationInterceptor implements HandlerInterceptor {
    //從header中獲取token
    public static final String AUTHORIZATION_TOKEN = "authorizationToken";


    private  IUserService userService= SpringUtil.getBean(UserServiceImpl.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader(AUTHORIZATION_TOKEN);// 從 http 請求頭中取出 token
        httpServletRequest.setAttribute("token", token);
        // 如果不是映射到Controller mapping方法直接通過
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;

        Method method = handlerMethod.getMethod();
        //檢查是否有passtoken注釋,有則跳過認(rèn)證
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //檢查有沒有需要用戶權(quán)限的注解
        //Annotation classLoginAnnotation = handlerMethod.getBeanType().getAnnotation(UserLoginToken.class);// 類級別的要求登錄標(biāo)記
        if (method.isAnnotationPresent(UserLoginToken.class) || handlerMethod.getBeanType().isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken =
                    method.getAnnotation(UserLoginToken.class) == null ?
                            handlerMethod.getBeanType().getAnnotation(UserLoginToken.class) : method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 執(zhí)行認(rèn)證
                if (token == null) {
                    throw new AuthenticationException("無token,請重新登錄");
                }
                // 獲取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new AuthenticationException("非法用戶");
                }
                User user = userService.getUserInfoById(userId);
                if (user == null) {
                    throw new AuthenticationException("用戶過期,請重新登錄");
                }
                // 驗(yàn)證 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserMobile())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new AuthenticationException("非法用戶");
                }
                return true;
            }
        }
        return true;
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容