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

在springBoot中使用JWT實(shí)現(xiàn)1.生成token,2.接收前端token進(jìn)行身份認(rèn)證,3.通過token獲取對(duì)象信息

這篇具有很好參考價(jià)值的文章主要介紹了在springBoot中使用JWT實(shí)現(xiàn)1.生成token,2.接收前端token進(jìn)行身份認(rèn)證,3.通過token獲取對(duì)象信息。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

1.使用JWT生成token

第一步:引入依賴

 <!-- JWT -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.10.3</version>
        </dependency>

第二步:創(chuàng)建工具類

在until包下創(chuàng)建TokenUntil類,用于生成token

利用id,和password作為參數(shù)生成token

JWt為這個(gè)包下的對(duì)象

import com.auth0.jwt.JWT;
package com.example.mybatis_plus_generator.untils;


import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * @author shkstart
 * @create 2023-08-06-13:51
 */
@Component
public class TokenUtils {

    //獲取token的靜態(tài)方法
    public static String getToken(String userId,String password){


        return JWT.create().withAudience(userId)// 將 user id 保存到 token 里面,作為載荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))// 2小時(shí)后token過期
                .sign(Algorithm.HMAC256(password));// 以 password 作為 token 的密鑰


    }
}

第三步:token使用

在向前端返回的數(shù)據(jù)對(duì)象中添加token屬性

springboot獲取token的用戶信息,spring boot,java,安全

?是serve層中調(diào)用工具類方法將生成的token放到返回的數(shù)據(jù)中

注意:這里獲取到的id是integer類型,需要用toString進(jìn)行類型轉(zhuǎn)換

springboot獲取token的用戶信息,spring boot,java,安全

?第四步:測(cè)試接口

springboot獲取token的用戶信息,spring boot,java,安全

?


2.通過驗(yàn)證token的攔截器

思路:建立一個(gè)統(tǒng)一的攔截器配置類,自己定義一個(gè)驗(yàn)證token的配置類。把它放到攔截器類中

知識(shí)儲(chǔ)備:

關(guān)于WebMvcConfigurationSupport類

是Spring MVC提供的一個(gè)配置類,用于擴(kuò)展和自定義Spring MVC的行為。通過繼承該類并重寫相應(yīng)的方法,我們可以實(shí)現(xiàn)定制化的配置,包括添加攔截器、配置視圖解析器、自定義消息轉(zhuǎn)換器等

關(guān)于HandlerInterceptor接口

用于攔截請(qǐng)求并對(duì)請(qǐng)求進(jìn)行預(yù)處理和后處理。它允許開發(fā)人員在請(qǐng)求到達(dá)處理器方法之前和之后執(zhí)行一些自定義的邏輯操作。

HandlerInterceptor接口定義了三個(gè)方法:

  1. preHandle:在處理器方法執(zhí)行之前被調(diào)用。可以在該方法中進(jìn)行一些預(yù)處理操作,如身份驗(yàn)證、權(quán)限檢查、日志記錄等。如果返回true,則繼續(xù)執(zhí)行后續(xù)的攔截器和處理器方法;如果返回false,則請(qǐng)求被攔截,后續(xù)的攔截器和處理器方法將不會(huì)被執(zhí)行。

  2. postHandle:在處理器方法執(zhí)行之后、視圖渲染之前被調(diào)用??梢栽谠摲椒ㄖ袑?duì)響應(yīng)進(jìn)行一些后處理操作,如修改視圖數(shù)據(jù)、添加公共模型屬性等。

  3. afterCompletion:在整個(gè)請(qǐng)求完成之后被調(diào)用,即視圖渲染完成后??梢栽谠摲椒ㄖ刑幚硪恍┽尫刨Y源的操作或執(zhí)行一些日志記錄等。

    我們可以創(chuàng)建自定義的HandlerInterceptor實(shí)現(xiàn)類來實(shí)現(xiàn)上述方法,并將其注冊(cè)到Spring MVC的配置中,以便攔截和處理請(qǐng)求。在Spring MVC的配置中,可以通過實(shí)現(xiàn)WebMvcConfigurer接口的addInterceptors方法來注冊(cè)自定義的HandlerInterceptor。

    通過使用HandlerInterceptor,我們可以實(shí)現(xiàn)一些與請(qǐng)求和響應(yīng)相關(guān)的公共邏輯和功能,如身份驗(yàn)證、日志記錄、參數(shù)解析、跨域處理等。攔截器提供了一種靈活的方式來對(duì)請(qǐng)求進(jìn)行攔截和處理,幫助開發(fā)人員實(shí)現(xiàn)系統(tǒng)層面的功能和邏輯。

第一步:創(chuàng)建統(tǒng)一的攔截器類

在config報(bào)下建立InterceptorConfig類

該類需要加上@Configuration注解并基礎(chǔ)WebMvcConfigurationSupport類

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {



}

第二步:建立驗(yàn)證token的類

在config.interceptor包寫建立JwtInterceptor類用于驗(yàn)證token,繼承接口HandlerInterceptor表示為攔截器類

重寫preHandler,設(shè)置規(guī)則

package com.example.mybatis_plus_generator.config.interceptor;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.mybatis_plus_generator.common.Constants;
import com.example.mybatis_plus_generator.entity.User;
import com.example.mybatis_plus_generator.exception.LoginException;
import com.example.mybatis_plus_generator.service.IUserService;
import org.apache.ibatis.logging.LogException;
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;

/**
 * @author shkstart
 * @create 2023-08-06-14:38
 */
//注入spring容器中,方便被調(diào)用
@Component
public class JwtInterceptor implements HandlerInterceptor {

    //注入service用于驗(yàn)證對(duì)象
    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //在請(qǐng)求頭中獲取token
        String token = request.getHeader("token");

        //若為空則拋出異常
        if(token == null){
            throw new  LoginException(Constants.CODE_401,"token為空");
        }

        //獲取token中的id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (Exception e){
            throw new LoginException(Constants.CODE_500,"該token不正確");
        }

        //判斷該id的用戶是否存在
        User user = userService.getById(userId);
        if(user == null){
            throw new LoginException(Constants.CODE_500,"該用戶已經(jīng)不存在");
        }
        //核心:進(jìn)行驗(yàn)證
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        }catch (Exception e){
            throw new LoginException(Constants.CODE_500,"驗(yàn)證token時(shí)出錯(cuò)");
        }

        //沒問題返回true
        return true;
    }

}

第三步:引入統(tǒng)一的攔截器類

@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {


    @Autowired
    JwtInterceptor jwtInterceptor;

    //增加攔截的規(guī)則
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)//將自己寫好的攔截類放進(jìn)來
                .addPathPatterns("/**")//攔截所有
                .excludePathPatterns("/user/login", "/user/register");//這兩個(gè)放行

    }

}

第四步:測(cè)試

有token時(shí)查出

springboot獲取token的用戶信息,spring boot,java,安全

?token值不正確時(shí)

springboot獲取token的用戶信息,spring boot,java,安全

?3.通過token獲取該用戶的信息

把這個(gè)功能放到包裝類中

思路:在until包下的TokenUntil寫創(chuàng)建靜態(tài)getCurrentUser方法,用于方便獲取user信息文章來源地址http://www.zghlxwxcb.cn/news/detail-763316.html

@Component
public class TokenUtils {

    private static IUserService staticUserService;

    @Resource
    private IUserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }



    /**
     * 獲取當(dāng)前登錄的用戶信息
     *
     * @return user對(duì)象
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserService.getById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}

到了這里,關(guān)于在springBoot中使用JWT實(shí)現(xiàn)1.生成token,2.接收前端token進(jìn)行身份認(rèn)證,3.通過token獲取對(duì)象信息的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

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

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包