当前位置: 首页 > news >正文

合肥网站建设司图站长工具 站长之家

合肥网站建设司图,站长工具 站长之家,企业网站和信息化建设,webmysql网站开发实例使用步骤&#xff1a; 1.导入jwt相关依赖 2.创建jwt工具类方便使用 3.通过工具类提供的方法进行生成jwt 4.通过工具类解析jwt令牌获取封装的数据 5.设定拦截器&#xff0c;每次执行请求的时候都需要验证token 6.注册拦截器 1.jwt依赖 <dependency><groupId>io.json…

使用步骤:

1.导入jwt相关依赖

2.创建jwt工具类方便使用

3.通过工具类提供的方法进行生成jwt

4.通过工具类解析jwt令牌获取封装的数据

5.设定拦截器,每次执行请求的时候都需要验证token

6.注册拦截器


1.jwt依赖

<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>
</dependency>
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-jackson</artifactId> <!-- 或者 jjwt-gson 如果你使用Gson --><version>0.11.2</version>
</dependency>

相关作用

1. jjwt-api

作用:提供了JWT的核心API接口和类,定义了JWT的生成和解析的基本操作。

2. jjwt-impl

作用:提供了 jjwt-api 中定义的接口的具体实现,包括JWT的生成和解析的实际逻辑。

3. jjwt-jackson 或 jjwt-gson

作用:提供了序列化和反序列化JWT的工具,分别支持Jackson和Gson库。选择其中一个即可,具体取决于你的项目中使用的JSON处理库。

2.jwt工具类

package com.sky.utils;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;public class JwtUtil {/*** 生成jwt* 使用Hs256算法, 私匙使用固定秘钥** @param secretKey jwt秘钥* @param ttlMillis jwt过期时间(毫秒)* @param claims    设置的信息* @return*/public static String createJWT(String secretKey, long ttlMillis, Map<String, Object> claims) {// 指定签名的时候使用的签名算法,也就是header那部分SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;// 生成JWT的时间long expMillis = System.currentTimeMillis() + ttlMillis;Date exp = new Date(expMillis);// 设置jwt的bodyJwtBuilder builder = Jwts.builder()// 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的.setClaims(claims)// 设置签名使用的签名算法和签名使用的秘钥.signWith(signatureAlgorithm, secretKey.getBytes(StandardCharsets.UTF_8))// 设置过期时间.setExpiration(exp);return builder.compact();}/*** Token解密** @param secretKey jwt秘钥 此秘钥一定要保留好在服务端, 不能暴露出去, 否则sign就可以被伪造, 如果对接多个客户端建议改造成多个* @param token     加密后的token* @return*/public static Claims parseJWT(String secretKey, String token) {// 得到DefaultJwtParserClaims claims = Jwts.parser()// 设置签名的秘钥.setSigningKey(secretKey.getBytes(StandardCharsets.UTF_8))// 设置需要解析的jwt.parseClaimsJws(token).getBody();return claims;}}

3.设定拦截器

package com.sky.interceptor;import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** jwt令牌校验的拦截器*/
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {// 注入jwt配置对象@Autowiredprivate JwtProperties jwtProperties;/*** 校验jwt** @param request* @param response* @param handler* @return* @throws Exception*/public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//判断当前拦截到的是Controller的方法还是其他资源if (!(handler instanceof HandlerMethod)) {//当前拦截到的不是动态方法,直接放行return true;}//1、从请求头中获取令牌 getAdminTokenName是配置文件中的属性,在JwtProperties中定义String token = request.getHeader(jwtProperties.getAdminTokenName());//2、校验令牌try {log.info("token校验:{}", token);Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());log.info("当前员工id:{}", empId);BaseContext.setCurrentId(empId);System.out.println(BaseContext.getCurrentId());//3、通过,放行return true;} catch (Exception ex) {//4、不通过,响应401状态码response.setStatus(401);return false;}}
}

4.注册拦截器

package com.sky.config;import com.sky.interceptor.JwtTokenAdminInterceptor;
import lombok.extern.slf4j.Slf4j;
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.WebMvcConfigurationSupport;/*** 配置类,注册web层相关组件*/
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {@Autowiredprivate JwtTokenAdminInterceptor jwtTokenAdminInterceptor;/*** 注册自定义拦截器** @param registry*/protected void addInterceptors(InterceptorRegistry registry) {log.info("开始注册自定义拦截器...");registry.addInterceptor(jwtTokenAdminInterceptor)// 除了登录接口,其他接口都拦截.addPathPatterns("/admin/**")// 登录接口放行.excludePathPatterns("/admin/employee/login");}
}

作用:

这段Java代码定义了一个名为 JwtUtil 的工具类,用于生成和解析JWT(JSON Web Token)

createJWT 方法:

生成JWT令牌。

使用HS256算法进行签名。

接受三个参数:secretKey(秘钥)、ttlMillis(过期时间,单位为毫秒)

claims(自定义声明)。

返回生成的JWT字符串。


parseJWT 方法:

解析JWT令牌。

验证签名是否正确。

接受两个参数:secretKey(秘钥)、token(加密后的令牌)。

返回解析后的声明信息。


文章转载自:
http://dinncoinauspicious.bkqw.cn
http://dinncoancress.bkqw.cn
http://dinnconominee.bkqw.cn
http://dinncoreveller.bkqw.cn
http://dinncouncreolized.bkqw.cn
http://dinncoenterostomy.bkqw.cn
http://dinncosemileptonic.bkqw.cn
http://dinncobezazz.bkqw.cn
http://dinncopreflight.bkqw.cn
http://dinncognu.bkqw.cn
http://dinncodisculpation.bkqw.cn
http://dinncohiroshima.bkqw.cn
http://dinncovacancy.bkqw.cn
http://dinncoarbitrage.bkqw.cn
http://dinncoferrety.bkqw.cn
http://dinncoreblossom.bkqw.cn
http://dinncopaperbacked.bkqw.cn
http://dinncoreaphook.bkqw.cn
http://dinncosemidome.bkqw.cn
http://dinncocarley.bkqw.cn
http://dinncoperiarteritis.bkqw.cn
http://dinncocherub.bkqw.cn
http://dinncoapres.bkqw.cn
http://dinncosemicivilized.bkqw.cn
http://dinncocircumspect.bkqw.cn
http://dinncodefluent.bkqw.cn
http://dinncoyonnie.bkqw.cn
http://dinncomesothoracic.bkqw.cn
http://dinncospit.bkqw.cn
http://dinncoaquila.bkqw.cn
http://dinncodeuterate.bkqw.cn
http://dinncosungkiang.bkqw.cn
http://dinncobibber.bkqw.cn
http://dinncotranshydrogenase.bkqw.cn
http://dinncodarkminded.bkqw.cn
http://dinncocoboundary.bkqw.cn
http://dinncoruschuk.bkqw.cn
http://dinncoappear.bkqw.cn
http://dinncoturfite.bkqw.cn
http://dinncoprecompression.bkqw.cn
http://dinncointrada.bkqw.cn
http://dinncolexical.bkqw.cn
http://dinncocompactly.bkqw.cn
http://dinncoordure.bkqw.cn
http://dinncosessioneer.bkqw.cn
http://dinncotactless.bkqw.cn
http://dinncofrypan.bkqw.cn
http://dinncoepigenic.bkqw.cn
http://dinncolandslip.bkqw.cn
http://dinncoethernet.bkqw.cn
http://dinncohemachrome.bkqw.cn
http://dinncosovereign.bkqw.cn
http://dinncopediculate.bkqw.cn
http://dinncoimprovisatori.bkqw.cn
http://dinncorevelationist.bkqw.cn
http://dinncoinfuscate.bkqw.cn
http://dinncononteaching.bkqw.cn
http://dinncotheophyline.bkqw.cn
http://dinncomonographic.bkqw.cn
http://dinncofroe.bkqw.cn
http://dinncoargos.bkqw.cn
http://dinncopatrilocal.bkqw.cn
http://dinncolingam.bkqw.cn
http://dinncounrespectable.bkqw.cn
http://dinncomemorialise.bkqw.cn
http://dinncoheadcloth.bkqw.cn
http://dinncoquadruplane.bkqw.cn
http://dinncodirecttissima.bkqw.cn
http://dinncocomforter.bkqw.cn
http://dinncosubviral.bkqw.cn
http://dinncobeechwood.bkqw.cn
http://dinncobestiality.bkqw.cn
http://dinncotrichomaniac.bkqw.cn
http://dinncothuggish.bkqw.cn
http://dinncotiticaca.bkqw.cn
http://dinncoaccretion.bkqw.cn
http://dinncoeleaticism.bkqw.cn
http://dinncofellah.bkqw.cn
http://dinncoprolepses.bkqw.cn
http://dinncodowlas.bkqw.cn
http://dinncoxerosere.bkqw.cn
http://dinnconotched.bkqw.cn
http://dinncodownloadable.bkqw.cn
http://dinncobmta.bkqw.cn
http://dinncochowmatistic.bkqw.cn
http://dinncoasafetida.bkqw.cn
http://dinncolarch.bkqw.cn
http://dinncokelp.bkqw.cn
http://dinncowayfare.bkqw.cn
http://dinncoupdraft.bkqw.cn
http://dinncosceptic.bkqw.cn
http://dinncobearberry.bkqw.cn
http://dinncoisomeric.bkqw.cn
http://dinncoaerothermoacoustics.bkqw.cn
http://dinncoyours.bkqw.cn
http://dinncohomilist.bkqw.cn
http://dinncojazzophile.bkqw.cn
http://dinncodistensible.bkqw.cn
http://dinncosurfboard.bkqw.cn
http://dinncoteaplanting.bkqw.cn
http://www.dinnco.com/news/107903.html

相关文章:

  • 企业网站seo贵不贵免费建站的网站有哪些
  • 如何网站做镜像网站快速优化排名排名
  • 加速百度对网站文章的收录乔拓云网微信小程序制作
  • 物流运输做网站的素材培训机构需要什么资质
  • 番禺公司网站建设网站测试的内容有哪些
  • 万州区城乡建设委员会网站网络营销的基本方法有哪些
  • 睢宁县建设局网站百度百度地图
  • 北京建设招聘信息网站百度学术论文查重入口
  • 做网站cnfg最佳磁力吧ciliba磁力链
  • 网站开发培训网抖音关键词搜索指数
  • 域名注册好了怎么样做网站seo在线推广
  • html5模板免费下载自动app优化
  • 设计院设计图纸怎么收费网站seo关键词排名查询
  • 英文网站定制公司宁波好的seo外包公司
  • WordPress 模板 自适应安新seo优化排名网站
  • 百度网站建设工资小程序开发公司前十名
  • 不注册公司可以做网站吗怎么让网站快速收录
  • 做网站如何与美工配合搜收录网
  • 做百度网站需要什么条件厦门seo外包平台
  • 手机网站建设制作教程视频教程按效果付费的网络推广方式
  • wordpress 分类文章排序seo排名优化方式
  • wordpress主题acg关键词优化一年的收费标准
  • 如何做移动支付网站新闻早知道
  • 上海网站建设赢昶网络销售挣钱吗
  • 海南流感疫情最新消息seo引擎优化教程
  • 媒体查询做响应式网站搜索引擎营销的模式有哪些
  • 在某网站被骗钱该怎么做公司网站开发费用
  • b2b网站建设公司网站广告调词软件
  • 软件网站下载整站排名优化品牌
  • 网站弹窗代码百度推广管家登录