国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot整合Mybatis-Plus、Jwt實現(xiàn)登錄token設置

這篇具有很好參考價值的文章主要介紹了SpringBoot整合Mybatis-Plus、Jwt實現(xiàn)登錄token設置。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Spring Boot整合Mybatis-plus實現(xiàn)登錄常常需要使用JWT來生成用戶的token并設置用戶權限的攔截器。本文將為您介紹JWT的核心講解、示例代碼和使用規(guī)范,以及如何實現(xiàn)token的生成和攔截器的使用。
SpringBoot整合Mybatis-Plus、Jwt實現(xiàn)登錄token設置
一、JWT的核心講解

JWT(JSON Web Token)是一種基于JSON的,用于在網(wǎng)絡上安全傳輸信息的開放標準(RFC 7519)。JWT有三個部分組成,分別是Header(頭部)、Payload(載荷)和Signature(簽名)。

  1. Header

Header部分通常由兩部分組成:令牌的類型和使用的加密算法。例如:

{
  "alg": "HS256",
  "typ": "JWT"
}

其中,“alg” 參數(shù)表示簽名的算法(例如HS256),“typ” 參數(shù)表示令牌的類型(例如JWT)。

  1. Payload

Payload是JWT的核心部分,其中包含了需要傳輸?shù)男畔?。示例?/p>

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

其中,“sub” 參數(shù)表示主題(Subject),“name” 參數(shù)表示名稱,“iat” 參數(shù)表示令牌的簽發(fā)時間。

  1. Signature

Signature部分是JWT的第三部分,它由頭部和載荷組合后進行簽名而產(chǎn)生。

二、JWT 的使用規(guī)范

  1. 生成 JWT

使用 Java JWT 庫生成 JWT,示例代碼如下:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static final byte[] SECRET_KEY = "secretkeyhere".getBytes();
    private static final long EXPIRATION_TIME = 3600000L; // 1 hour

    public static String createJwt(String subject, String scopes) {
        SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY);
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION_TIME);
        String jwt = Jwts.builder()
                .setIssuer("demo")
                .setSubject(subject)
                .setExpiration(expiration)
                .claim("scopes", scopes)
                .setIssuedAt(now)
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
        return jwt;
    }

    public static Jws<Claims> parseJwt(String jwt) {
        SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY);
        Jws<Claims> jws = Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(jwt);
        return jws;
    }
}

其中,SECRET_KEY 是用于簽名的密鑰,建議使用足夠隨機的字符串或 byte 數(shù)組;EXPIRATION_TIME 是過期時間,設置為 1 小時;createJwt() 方法會創(chuàng)建 JWT,并將用戶標識(subject)和權限(scopes)作為載荷;parseJwt() 方法用于解析 JWT。

  1. 解析 JWT

解析 JWT 部分和生成 JWT 略有不同。示例代碼如下:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final List<String> ALLOWED_URIS = Arrays.asList("/login");

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String jwt = request.getHeader("Authorization");
        if (jwt != null) {
            jwt = jwt.replace("Bearer ", "");
            try {
                Jwts.parserBuilder().setSigningKey(jwtProperties.getSecret()).build().parseClaimsJws(jwt);
                String[] scopes = ((String)Jwts.parserBuilder().setSigningKey(jwtProperties.getSecret().parseClaimsJws(jwt).getBody().get("scopes")).split(",");
                Set<String> allowedScopes = Arrays.stream(scopes)
                        .map(String::trim)
                        .collect(Collectors.toSet());
                String uri = request.getRequestURI();
                if (!ALLOWED_URIS.contains(uri)) {
                    if (!allowedScopes.contains("all") && !allowedScopes.contains(uri)) {
                        response.sendError(HttpStatus.FORBIDDEN.value());
                        return;
                    }
                }
            } catch (Exception e) {
                response.sendError(HttpStatus.UNAUTHORIZED.value());
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}

這段代碼定義了一個JwtAuthenticationFilter,它會在每次請求進入 Controller 之前進行攔截,解析 JWT 并根據(jù)用戶權限進行攔截。ALLOWED_URIS 定義了不需要 JWT 驗證的 URL,比如登錄接口。jwtProperties 用于讀取一些 JWT 相關的配置,比如密鑰(secret)等。

三、Mybatis-plus 使用 JWT 實現(xiàn)登錄

在 Mybatis-plus 中使用 JWT 時,我們需要在登錄成功之后生成 JWT,并將其返回給客戶端??蛻舳嗽谝院蟮恼埱笾卸紩?JWT,我們需要在攔截器中解析 JWT 并進行權限校驗。

首先,在 pom.xml 中添加相關依賴:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.2</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.2</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.11.2</version>
    <scope>runtime</scope>
</dependency>

然后,我們需要創(chuàng)建一個 JwtUtil 工具類,用于生成和解析 JWT:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;

import java.util.Date;

public class JwtUtil {

    private static final String SECRET = "secretkey";

    public static String generateToken(String username, Long expiration) {
        Date now = new Date();
        Date expireTime = new Date(now.getTime() + expiration * 1000);
        JwtBuilder builder = Jwts.builder()
                .setId(username)
                .setIssuedAt(now)
                .setExpiration(expireTime)
                .signWith(SignatureAlgorithm.HS256, SECRET);
        return builder.compact();
    }

    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
}

在登錄成功之后,我們需要調用 JwtUtil.generateToken() 方法生成 JWT,并將其返回給客戶端??蛻舳嗽谝院蟮恼埱笾卸紩?JWT,我們需要在攔截器中解析 JWT 并進行權限校驗:

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtIntercepter implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            try {
                Claims claims = JwtUtil.parseToken(token);
                request.setAttribute("username", claims.getSubject());
                return true;
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
                return false;
            }
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No token provided in the request header");
            return false;
        }
    }
}

在攔截器中,我們通過 request.setAttribute() 方法將解析出來的用戶信息保存在 Request 中,后續(xù)可以通過 Request 獲取到用戶信息。在攔截器中,我們也可以實現(xiàn)權限校驗的邏輯。如果校驗失敗,我們可以通過 response.sendError() 方法返回403 或 401 狀態(tài)碼,告知客戶端請求被拒絕或未經(jīng)授權。

最后,定義一個 WebMvcConfigurerAdapter,將 JwtIntercepter 注冊為攔截器:

import org.springframework.beans.factory.annotation.Autowired;
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 WebConfig implements WebMvcConfigurer {

    @Autowired
    private JwtIntercepter jwtIntercepter;

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

在上述代碼中,我們通過 addPathPatterns() 方法設置需要攔截的 URL 路徑,并通過 excludePathPatterns() 方法排除不需要攔截的 URL 路徑。其中,“/login” 路徑為登錄接口,一般不需要攔截。

四、總結

本文介紹了在 Spring Boot 整合 Mybatis-plus 實現(xiàn)登錄時,使用 JWT 來生成用戶 Token 并設置用戶權限攔截器的方法。首先,我們需要了解 JWT 的核心框架和使用規(guī)范,并通過代碼實現(xiàn) JWT 的生成和解析。然后,我們在攔截器中實現(xiàn) JWT 的解析和權限校驗,最后通過 WebMvcConfigurerAdapter 將 JwtIntercepter 注冊為攔截器。文章來源地址http://www.zghlxwxcb.cn/news/detail-432479.html

到了這里,關于SpringBoot整合Mybatis-Plus、Jwt實現(xiàn)登錄token設置的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • SpringBoot整合MyBatis-Plus,趕緊整過來!

    提示:以下是本篇文章正文內(nèi)容 MyBatis-Plus官網(wǎng)介紹:MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發(fā)、提高效率而生。 MyBatis-Plus封裝了單表的crud操作,減少基礎代碼編寫,提高開發(fā)效率。 支持自

    2024年02月06日
    瀏覽(17)
  • springboot3.2 整合 mybatis-plus

    springboot3.2 整合 mybatis-plus

    springboot3.2 正式發(fā)布了 迫不及待地的感受了一下 結果在整個mybatis-plus 的時候遇到了如下報錯 主要是由于 mybatis-plus 中 mybatis 的整合包版本不夠導致的 排除 mybatis-plus 中自帶的 mybatis 整合包,單獨引入即可 修改依賴后正常

    2024年02月04日
    瀏覽(25)
  • Springboot 整合Mytbatis與Mybatis-Plus

    Springboot 整合Mytbatis與Mybatis-Plus

    目錄 1. springboot整合mybatis?? ?1.1 添加pom.xml依賴 ?1.2 新建jdbc.properties 文件添加以下內(nèi)容 ?1.3 新建generatorConfig.xml 文件添加以下內(nèi)容 (自動生成代碼類)? ?1.4 修改application.properties 文件 添加以下內(nèi)容 ?1.5 修改主類MapperScan ?1.6 編寫接口實現(xiàn)類進行測試? 2. springboot整合mybatis-p

    2024年02月06日
    瀏覽(23)
  • SpringBoot整合JUnit--MyBatis--MyBatis-Plus--Druid

    SpringBoot整合JUnit--MyBatis--MyBatis-Plus--Druid

    文章轉自黑馬程序員SpringBoot學習筆記,學習網(wǎng)址:黑馬程序員SpringBoot2教程 1.整合JUnit ? SpringBoot技術的定位用于簡化開發(fā),再具體點是簡化Spring程序的開發(fā)。所以在整合任意技術的時候,如果你想直觀感觸到簡化的效果,你必須先知道使用非SpringBoot技術時對應的整合是如何做

    2023年04月23日
    瀏覽(26)
  • SpringBoot(整合MyBatis + MyBatis-Plus + MyBatisX插件使用)

    SpringBoot(整合MyBatis + MyBatis-Plus + MyBatisX插件使用)

    1.需求分析 2.數(shù)據(jù)庫表設計 3.數(shù)據(jù)庫環(huán)境配置 1.新建maven項目 2.pom.xml 引入依賴 3.application.yml 配置數(shù)據(jù)源 數(shù)據(jù)庫名 用戶名 密碼 驅動是mysql8的(因為上面使用了版本仲裁) 4.Application.java 編寫啟動類 5.測試 6.配置類切換druid數(shù)據(jù)源 7.測試數(shù)據(jù)源是否成功切換 4.Mybatis基礎配置 1

    2024年03月20日
    瀏覽(30)
  • Springboot3整合Mybatis-plus3.5.3報錯

    Springboot3整合Mybatis-plus3.5.3報錯

    ?作者簡介:大家好,我是Leo,熱愛Java后端開發(fā)者,一個想要與大家共同進步的男人???? ??個人主頁:Leo的博客 ??當前專欄: 報錯以及Bug ?特色專欄: MySQL學習 ??本文內(nèi)容:記錄一次Docker與Redis沖突 ???個人小站 :個人博客,歡迎大家訪問 ??個人知識庫: 知識庫,

    2024年02月05日
    瀏覽(20)
  • SpringBoot整合Mybatis-Plus、Druid配置多數(shù)據(jù)源

    SpringBoot整合Mybatis-Plus、Druid配置多數(shù)據(jù)源

    目錄 1.初始化項目 1.1.初始化工程 1.2.添加依賴 1.3.配置yml文件 1.4.Spring Boot 啟動類中添加?@MapperScan?注解,掃描 Mapper 文件夾 1.5.配置使用數(shù)據(jù)源 1.5.1.注解方式 1.5.2.基于AOP手動實現(xiàn)多數(shù)據(jù)源原生的方式 2.結果展示 Mybatis-Plus:簡介 | MyBatis-Plus (baomidou.com) 在正式開始之前,先初始

    2024年02月11日
    瀏覽(24)
  • springboot整合mybatis-plus的sql輸出到日志文件上

    springboot整合mybatis-plus的sql輸出到日志文件上

    springboot整合mybatis-plus的sql輸出到日志文件上 在平時的日常開發(fā)中,我們希望sql打印在控制臺上,只要如下配置即可 但是在生產(chǎn)中如果希望sql輸出到日志文件上,有幾種方式可以實現(xiàn),下面我就用項目中常用的兩種方式(不引入第三方依賴) 一、修改yml文件配置即可 缺點:

    2024年02月01日
    瀏覽(26)
  • java springboot整合MyBatis-Plus 多用點Plus支持一下國人開發(fā)的東西吧

    java springboot整合MyBatis-Plus 多用點Plus支持一下國人開發(fā)的東西吧

    文章java springboot整合MyBatis做數(shù)據(jù)庫查詢操作講述了boot項目整合MyBatis的操作方法 但現(xiàn)在就還有一個 MyBatis-Plus Plus是國內(nèi)整合的一個技術 國內(nèi)的很多人會喜歡用 特別是一些中小型公司 他們用著會比較舒服 好 然后我們打開idea 創(chuàng)建一個項目 選擇 Spring Initializr 工程 調一下項目

    2024年02月09日
    瀏覽(19)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包