Spring Boot認證:整合Jwt


背景

Jwt全稱是:json web token。它將用戶信息加密到token里,服務器不保存任何用戶信息。服務器通過使用保存的密鑰驗證token的正確性,只要正確即通過驗證。

優點

  1. 簡潔: 可以通過URLPOST參數或者在HTTP header發送,因為數據量小,傳輸速度也很快;
  2. 自包含:負載中可以包含用戶所需要的信息,避免了多次查詢數據庫;
  3. 因為Token是以JSON加密的形式保存在客戶端的,所以JWT是跨語言的,原則上任何web形式都支持;
  4. 不需要在服務端保存會話信息,特別適用於分布式微服務。

缺點

  1. 無法作廢已頒布的令牌;
  2. 不易應對數據過期。

一、Jwt消息構成

1.1 組成

一個token分3部分,按順序為

  1. 頭部(header)
  2. 載荷(payload)
  3. 簽證(signature)

三部分之間用.號做分隔。例如:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxYzdiY2IzMS02ODFlLTRlZGYtYmU3Yy0wOTlkODAzM2VkY2UiLCJleHAiOjE1Njk3Mjc4OTF9.wweMzyB3tSQK34Jmez36MmC5xpUh15Ni3vOV_SGCzJ8

1.2 header

Jwt的頭部承載兩部分信息:

  1. 聲明類型,這里是Jwt
  2. 聲明加密的算法 通常直接使用 HMAC SHA256

Jwt里驗證和簽名使用的算法列表如下:

JWS 算法名稱
HS256 HMAC256
HS384 HMAC384
HS512 HMAC512
RS256 RSA256
RS384 RSA384
RS512 RSA512
ES256 ECDSA256
ES384 ECDSA384
ES512 ECDSA512

1.3 playload

載荷就是存放有效信息的地方。基本上填2種類型數據

  1. 標准中注冊的聲明的數據;
  2. 自定義數據。

由這2部分內部做base64加密。

  • 標准中注冊的聲明 (建議但不強制使用)
iss: jwt簽發者
sub: jwt所面向的用戶
aud: 接收jwt的一方
exp: jwt的過期時間,這個過期時間必須要大於簽發時間
nbf: 定義在什么時間之前,該jwt都是不可用的.
iat: jwt的簽發時間
jti: jwt的唯一身份標識,主要用來作為一次性token,從而回避重放攻擊。
  • 自定義數據:存放我們想放在token中存放的key-value

1.4 signature

Jwt的第三部分是一個簽證信息,這個簽證信息由三部分組成
base64加密后的headerbase64加密后的payload連接組成的字符串,然后通過header中聲明的加密方式進行加鹽secret組合加密,然后就構成了Jwt的第三部分。

二、Spring BootJwt集成示例

示例代碼采用:

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.8.1</version>
</dependency>

2.1 項目依賴

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.8.1</version>
    </dependency>
    <!-- redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>1.8.4</scope>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>
</dependencies>

2.2 自定義注解@JwtToken

加上該注解的接口需要登錄才能訪問

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface JwtToken {
    boolean required() default true;
}

2.3 Jwt 認證工具類JwtUtil.java

主要用來生成簽名、校驗簽名和通過簽名獲取信息

public class JwtUtil {

    /**
     * 過期時間5分鍾
     */
    private static final long EXPIRE_TIME = 5 * 60 * 1000;
    /**
     * jwt 密鑰
     */
    private static final String SECRET = "jwt_secret";

    /**
     * 生成簽名,五分鍾后過期
     * @param userId
     * @return
     */
    public static String sign(String userId) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    // 將 user id 保存到 token 里面
                    .withAudience(userId)
                    // 五分鍾后token過期
                    .withExpiresAt(date)
                    // token 的密鑰
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根據token獲取userId
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        try {
            String userId = JWT.decode(token).getAudience().get(0);
            return userId;
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 校驗token
     * @param token
     * @return
     */
    public static boolean checkSign(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    // .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception) {
            throw new RuntimeException("token 無效,請重新獲取");
        }
    }
}

2.4 攔截器攔截帶有注解的接口

  • JwtInterceptor.java
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        // 從 http 請求頭中取出 token
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通過
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //檢查有沒有需要用戶權限的注解
        if (method.isAnnotationPresent(JwtToken.class)) {
            JwtToken jwtToken = method.getAnnotation(JwtToken.class);
            if (jwtToken.required()) {
                // 執行認證
                if (token == null) {
                    throw new RuntimeException("無token,請重新登錄");
                }
                // 獲取 token 中的 userId
                String userId = JwtUtil.getUserId(token);
                System.out.println("用戶id:" + userId);

                // 驗證 token
                JwtUtil.checkSign(token);
            }
        }
        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 {

    }
}
  • 注冊攔截器:WebConfig.java
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 添加jwt攔截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())
                // 攔截所有請求,通過判斷是否有 @JwtToken 注解 決定是否需要登錄
                .addPathPatterns("/**");
    }

    /**
     * jwt攔截器
     * @return
     */
    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }
}

2.5 全局異常捕獲

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {
        String msg = e.getMessage();
        if (msg == null || msg.equals("")) {
            msg = "服務器出錯";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", msg);
        return jsonObject;
    }
}

2.6 接口

  • JwtController.java
@RestController
@RequestMapping("/jwt")
public class JwtController {

    /**
     * 登錄並獲取token
     * @param userName
     * @param passWord
     * @return
     */
    @PostMapping("/login")
    public Object login( String userName, String passWord){
        JSONObject jsonObject=new JSONObject();
        // 檢驗用戶是否存在(為了簡單,這里假設用戶存在,並制造一個uuid假設為用戶id)
        String userId = UUID.randomUUID().toString();
        // 生成簽名
        String token= JwtUtil.sign(userId);
        Map<String, String> userInfo = new HashMap<>();
        userInfo.put("userId", userId);
        userInfo.put("userName", userName);
        userInfo.put("passWord", passWord);
        jsonObject.put("token", token);
        jsonObject.put("user", userInfo);
        return jsonObject;
    }

    /**
     * 該接口需要帶簽名才能訪問
     * @return
     */
    @JwtToken
    @GetMapping("/getMessage")
    public String getMessage(){
        return "你已通過驗證";
    }
}

2.7 Postman測試接口

2.7.1 在沒token的情況下訪問jwt/getMessage接口

{
    "message": "無token,請重新登錄"
}

2.7.2 先登錄,在訪問jwt/getMessage接口

  • 登錄請求及結果,詳見下圖:

登錄后得到簽名如箭頭處

  • 在請求頭加上簽名,然后再請求jwt/getMessage接口

請求通過,測試成功!

2.7.3 過期后再次訪問

我們設置的簽名過期時間是五分鍾,五分鍾后再次訪問jwt/getMessage接口,結果如下:

通過結果,我們發現時間到了,簽名失效,說明該方案通過。

三、總結

3.1 示例源碼

Github 源碼

3.2 技術交流

  1. 風塵博客
  2. 風塵博客-CSDN
  3. 風塵博客-掘金


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM