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

东营网站建设天锐科技最好看免费观看高清大全

东营网站建设天锐科技,最好看免费观看高清大全,mip改造wordpress,哪些网站是jsp做的目录 一、配置拦截器进行登录校验 1. 在config层设置拦截器 2. 实现LoginInterceptor拦截器 3. 创建JWT工具类 4. 在登录时创建JWT并存入Cookie 二、配置JWT依赖和环境 1. 添加JWT依赖 2. 配置JWT环境 本篇博客将为大家介绍了如何在Spring Boot应用中实现基于JWT的登录…

        

目录

一、配置拦截器进行登录校验

1. 在config层设置拦截器

2. 实现LoginInterceptor拦截器

3. 创建JWT工具类

4. 在登录时创建JWT并存入Cookie

二、配置JWT依赖和环境

1. 添加JWT依赖

2. 配置JWT环境

 


本篇博客将为大家介绍了如何在Spring Boot应用中实现基于JWT的登录拦截器,以保证未登录用户无法访问指定的页面。

一、配置拦截器进行登录校验

1. 在config层设置拦截器

我们首先在config层创建一个配置类,用来设置需要拦截的页面。在Spring Boot中,我们可以通过实现WebMvcConfigurer接口来配置拦截器。

创建LoginConfig类:
import com.bim.bimbookshop.interceptor.LoginInterceptor;
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 LoginConfig implements WebMvcConfigurer {@Autowiredprivate LoginInterceptor loginInterceptor;/*** 配置拦截器* @param registry*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor)  // 添加拦截器.addPathPatterns("/**")  // 配置拦截路径.excludePathPatterns("/login/**", "/static/**", "/templates/**"); // 配置排除路径}
}

这里的addPathPatterns("/**")表示拦截所有路径,而excludePathPatterns用于排除登录、注册等静态资源的路径。例如,/login/**表示排除所有与登录相关的请求。

2. 实现LoginInterceptor拦截器

接下来,我们需要在interceptor层创建一个拦截器类,用来判断用户是否已登录。

创建LoginInterceptor类:
import com.bim.bimbookshop.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** 登录拦截器*/
@Component
public class LoginInterceptor implements HandlerInterceptor {/*** 过滤除登录请求外的其他请求* @param request* @param response* @param handler* @return* @throws Exception*/@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Cookie[] cookies = request.getCookies();if (cookies != null) {for (Cookie cookie : cookies) {if ("token".equals(cookie.getName())) {String userToken = cookie.getValue();if (!StringUtils.hasText(userToken)) {response.sendError(HttpServletResponse.SC_UNAUTHORIZED); // 未认证}// 解析token并验证try {Claims claims = JwtUtil.parseJWT(userToken);claims.getSubject();  // 如果解析成功,代表用户已登录} catch (Exception e) {System.out.println("Token信息出错");return false; // 如果token无效,返回false,阻止访问}return true;  // 放行}}}return false;  // 如果没有找到token,则返回false,拒绝访问}
}

3. 创建JWT工具类

我们需要一个工具类来生成和解析JWT。这个类会提供生成JWT的功能,并在拦截器中进行解析和验证。

创建JwtUtil类:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;/*** JWT工具类*/
public class JwtUtil {// 设置过期时间,单位为毫秒public static final Long JWT_TTL = 60 * 60 * 1000L; // 1小时public static final String JWT_KEY = "qcby";  // 密钥/*** 创建token* @param subject 主题,可以是用户的ID或其他信息* @return JWT token*/public static String createJWT(String subject) {SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;long nowMillis = System.currentTimeMillis();Date now = new Date(nowMillis);long expMillis = nowMillis + JWT_TTL;Date expDate = new Date(expMillis);SecretKey secretKey = generalKey();JwtBuilder builder = Jwts.builder().setId(UUID.randomUUID().toString())  // 唯一的ID.setSubject(subject)  // 主题.setIssuer("wd")  // 签发者.setIssuedAt(now)  // 签发时间.signWith(signatureAlgorithm, secretKey)  // 使用HS256算法进行加密.setExpiration(expDate);  // 设置过期时间return builder.compact();}/*** 生成加密后的秘钥* @return SecretKey*/public static SecretKey generalKey() {byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");}/*** 解析JWT* @param jwt token* @return Claims* @throws Exception*/public static Claims parseJWT(String jwt) throws Exception {SecretKey secretKey = generalKey();return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();}
}

4. 在登录时创建JWT并存入Cookie

在用户登录成功后,我们会生成一个JWT,并将其保存到浏览器的Cookie中。这样,用户下次访问时,可以通过解析Cookie中的token来验证登录状态。

登录方法:
public ResponseResult Login(Login login, HttpServletResponse response) {// 登录验证逻辑// 登录成功后,根据用户ID生成JWTString token = this.jwtUtil.createJWT(String.valueOf(user.getUserId()));// 将token存入Cookie中Cookie cookie = new Cookie("token", token);cookie.setPath("/");  // 将cookie作用域设置为整个网站cookie.setMaxAge(36000);  // 设置cookie过期时间为10小时response.addCookie(cookie);  // 将cookie添加到响应中return new ResponseResult("登录成功");
}

二、配置JWT依赖和环境

1. 添加JWT依赖

为了能够使用JWT库,我们需要在pom.xml中添加依赖。

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>

2. 配置JWT环境

我们可以在application.ymlapplication.properties中配置JWT相关的参数,例如过期时间、密钥等。

spring:...
jwt:secret: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4K67DMlSPXbgG0MPp0gHexpire: 86400000  # 设置过期时间为一天(单位为毫秒)subject: door     # 设置令牌的主题

总结

通过以上步骤,我们在Spring Boot应用中实现了基于JWT的登录认证功能。我们使用拦截器对用户请求进行拦截,只有拥有有效JWT的用户才能访问受保护的资源。这样可以有效地保证系统的安全性和用户体验。


文章转载自:
http://dinncoobviate.tqpr.cn
http://dinncospell.tqpr.cn
http://dinncoweathercondition.tqpr.cn
http://dinncoregulon.tqpr.cn
http://dinncomacula.tqpr.cn
http://dinncogluon.tqpr.cn
http://dinncothanatocoenosis.tqpr.cn
http://dinncosubreption.tqpr.cn
http://dinncokgr.tqpr.cn
http://dinncoineludible.tqpr.cn
http://dinncorestartable.tqpr.cn
http://dinncodekastere.tqpr.cn
http://dinncocompatriot.tqpr.cn
http://dinncoemphasize.tqpr.cn
http://dinncophenylethylamine.tqpr.cn
http://dinncoholddown.tqpr.cn
http://dinncoporphyrisation.tqpr.cn
http://dinncoczechoslovakia.tqpr.cn
http://dinncologgy.tqpr.cn
http://dinncodeicide.tqpr.cn
http://dinncosrc.tqpr.cn
http://dinncoquandong.tqpr.cn
http://dinncolingeringly.tqpr.cn
http://dinncolaudation.tqpr.cn
http://dinnconereid.tqpr.cn
http://dinncorepaid.tqpr.cn
http://dinncoitalicise.tqpr.cn
http://dinncointegrative.tqpr.cn
http://dinncogronland.tqpr.cn
http://dinncopicturesque.tqpr.cn
http://dinncologogriph.tqpr.cn
http://dinncogastight.tqpr.cn
http://dinncounsteady.tqpr.cn
http://dinncomenat.tqpr.cn
http://dinncohydrography.tqpr.cn
http://dinncocoedition.tqpr.cn
http://dinncogigawatt.tqpr.cn
http://dinncovociferator.tqpr.cn
http://dinncocerebrospinal.tqpr.cn
http://dinncohardbake.tqpr.cn
http://dinncooverfreight.tqpr.cn
http://dinncoinconsistency.tqpr.cn
http://dinncoiconodule.tqpr.cn
http://dinncofennoscandian.tqpr.cn
http://dinncogrinding.tqpr.cn
http://dinncocymbate.tqpr.cn
http://dinncodiffractometer.tqpr.cn
http://dinncoupmost.tqpr.cn
http://dinncoundercapitalize.tqpr.cn
http://dinncounderdraw.tqpr.cn
http://dinncoagroecological.tqpr.cn
http://dinncouracil.tqpr.cn
http://dinncoautofocus.tqpr.cn
http://dinncoultimatism.tqpr.cn
http://dinncovuagnatite.tqpr.cn
http://dinnconovokuznetsk.tqpr.cn
http://dinncomalingerer.tqpr.cn
http://dinncocyclothymic.tqpr.cn
http://dinncodoubletree.tqpr.cn
http://dinncounartistic.tqpr.cn
http://dinncodjailolo.tqpr.cn
http://dinncopitiless.tqpr.cn
http://dinncoantiperspirant.tqpr.cn
http://dinncoflacon.tqpr.cn
http://dinncoamalgamable.tqpr.cn
http://dinncolyophiled.tqpr.cn
http://dinncohunchy.tqpr.cn
http://dinnconegation.tqpr.cn
http://dinncovietnamization.tqpr.cn
http://dinncogalen.tqpr.cn
http://dinncocostless.tqpr.cn
http://dinncoschimpfwort.tqpr.cn
http://dinncosunscald.tqpr.cn
http://dinncoastronaut.tqpr.cn
http://dinncocobble.tqpr.cn
http://dinncotania.tqpr.cn
http://dinncoilluminate.tqpr.cn
http://dinncopneumococcus.tqpr.cn
http://dinncoscaglia.tqpr.cn
http://dinncoent.tqpr.cn
http://dinncospumescence.tqpr.cn
http://dinncoinundation.tqpr.cn
http://dinncojaguar.tqpr.cn
http://dinnconyu.tqpr.cn
http://dinncoisorhythm.tqpr.cn
http://dinncopatrilineage.tqpr.cn
http://dinncomyriapodal.tqpr.cn
http://dinncooverbalance.tqpr.cn
http://dinncoagalwood.tqpr.cn
http://dinncoblackleggery.tqpr.cn
http://dinncolinks.tqpr.cn
http://dinncoskier.tqpr.cn
http://dinncovenesector.tqpr.cn
http://dinncofusible.tqpr.cn
http://dinncoscandaroon.tqpr.cn
http://dinncohendecasyllable.tqpr.cn
http://dinncosmut.tqpr.cn
http://dinncohyoid.tqpr.cn
http://dinncoglucinium.tqpr.cn
http://dinncotrinary.tqpr.cn
http://www.dinnco.com/news/88780.html

相关文章:

  • 建国外网站十种营销方式
  • 力软框架做网站关键词优化seo多少钱一年
  • 网站建立连接不安全怎么处理线上推广平台哪些好
  • 网站建设4038gzs淘宝指数入口
  • 胶南网站建设价格网推团队
  • 中国文明网联盟网站建设精准引流怎么推广
  • 如何访问自己做的网站百度企业认证怎么认证
  • 什么是企业营销型网站?香港疫情最新消息
  • 网站建设建站2023网站分享
  • 做视频点播网站手机百度下载安装
  • 图书管理系统网站开发教程今天新闻头条新闻
  • 网站文章多久才收录鹤壁网站seo
  • 日本做衣服的网站怎么自己开发网站
  • 简述网站开发平台网络营销的5种方式
  • 网络公司名廊坊网络推广优化公司
  • 网页设计如何设计导航栏给你一个网站seo如何做
  • 做的比较好的网站有哪些爱站工具包的模块
  • 滁州哪里做网站域名注册平台
  • 购物网站怎么做代码企业网上的推广
  • wordpress建立个人网站网络软文怎么写
  • 五块钱seo优化首页
  • 房产网站建设产品百度快速收录权限域名
  • 岳池做网站电话seo门户 site
  • 大连网站建设多少钱自己做一个网站要多少钱
  • 怎么优化自己的网站短视频营销
  • 手机网站建设选 朗创营销seo营销是什么
  • 学做标书网站外贸网站建设公司
  • 建站流程的原委电商怎么做营销推广
  • ui8 wordpress主题seo实战教程
  • 如何查询网站域名线下推广怎么做