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

建设部人力资源开发中心网站泰州seo推广公司

建设部人力资源开发中心网站,泰州seo推广公司,多语言网站思路,创建网站销售产品目录 1. JWT的结构2. JWT的优点3. JWT的流转过程4.具体案例一、项目结构二、依赖配置三、用户模型四、JWT工具类五、JWT请求过滤器六、安全配置七、身份验证控制器八、测试JWT JWT(JSON Web Token)是一种开放标准(RFC 7519)&#…

目录

  • 1. JWT的结构
  • 2. JWT的优点
  • 3. JWT的流转过程
  • 4.具体案例
      • 一、项目结构
      • 二、依赖配置
      • 三、用户模型
      • 四、JWT工具类
      • 五、JWT请求过滤器
      • 六、安全配置
      • 七、身份验证控制器
      • 八、测试JWT

JWT(JSON Web Token)是一种开放标准(RFC 7519),用于在网络应用环境间以紧凑的方式安全地传递信息。JWT可以被用作身份验证和信息交换的手段,特别适合用于前后端分离的应用程序。

1. JWT的结构

JWT由三部分组成:

  • Header(头部): 通常包含令牌的类型(JWT)和所使用的签名算法(如HMAC SHA256或RSA)。

  • Payload(负载): 包含声明(claims),即要传递的数据。其中可以包含注册声明(如 iss、exp、sub 等)和自定义声明。

  • Signature(签名): 用于验证消息的完整性和发送者的身份。通过将编码后的header和payload与一个密钥结合,利用指定的算法生成。

JWT的格式如下:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

2. JWT的优点

  • 无状态: 不需要在服务器存储会话信息,减轻了服务器的负担。
  • 跨域: 可以在不同的域之间进行身份验证。
  • 自包含: 含有用户身份信息,避免频繁查询数据库。

3. JWT的流转过程

  1. 用户通过登录接口发送用户名和密码。
  2. 服务器验证用户信息,如果成功,则生成JWT并返回给用户。
  3. 用户在后续请求中带上JWT,通常放在HTTP请求的Authorization头中。
  4. 服务器解析JWT,验证其有效性,允许或拒绝请求。

4.具体案例

好的,让我们更详细地探讨如何在Java Spring Boot应用程序中实现JWT身份验证,包括每一步的代码和说明。

一、项目结构

Spring Boot项目结构如下:

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── jwt
│   │               ├── JwtApplication.java
│   │               ├── config
│   │               │   └── SecurityConfig.java
│   │               ├── controller
│   │               │   └── AuthController.java
│   │               ├── model
│   │               │   └── User.java
│   │               ├── service
│   │               │   └── JwtUtil.java
│   │               └── filter
│   │                   └── JwtRequestFilter.java
│   └── resources
│       └── application.properties
└── test

二、依赖配置

pom.xml中添加必要的依赖:

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency>
</dependencies>

三、用户模型

创建一个简单的用户模型:

package com.example.jwt.model;public class User {private String username;private String password;// Constructors, getters, and setters//也可以使用Lombokpublic User(String username, String password) {this.username = username;this.password = password;}public String getUsername() {return username;}public String getPassword() {return password;}
}

四、JWT工具类

创建JWT工具类,负责生成和解析JWT:

package com.example.jwt.service;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
*Jwt工具类
*/
@Component//加入Spring容器
public class JwtUtil {private String secret = "your_secret_key"; // 强密码private long expiration = 60 * 60 * 1000; // 1小时//这个方法用于生成 JWT。它接受用户名作为参数。public String generateToken(String username) {Map<String, Object> claims = new HashMap<>();return createToken(claims, username);}//私有方法,用于实际生成 JWTprivate String createToken(Map<String, Object> claims, String subject) {return Jwts.builder()//开始构建 JWT 的构建器.setClaims(claims)//设置 JWT 中的声明.setSubject(subject)//设置主题(通常是用户名).setIssuedAt(new Date(System.currentTimeMillis()))//设置 JWT 的签发时间.setExpiration(new Date(System.currentTimeMillis() + expiration))//设置 JWT 的过期时间.signWith(SignatureAlgorithm.HS256, secret)//使用指定的算法(HS256)和密钥对 JWT 进行签名.compact();//生成最终的 JWT 字符串}//用于验证给定的 JWT 是否有效。public Boolean validateToken(String token, String username) {final String extractedUsername = extractUsername(token);//提取 JWT 中的用户名return (extractedUsername.equals(username) && !isTokenExpired(token));//检查提取的用户名与提供的用户名是否匹配,并且检查 JWT 是否未过期}//从 JWT 中提取用户名public String extractUsername(String token) {return extractAllClaims(token).getSubject();}//解析 JWT 并返回所有声明private Claims extractAllClaims(String token) {return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();}//使用密钥解析 JWT 获取其主体部分(声明)//检查 JWT 是否已过期private Boolean isTokenExpired(String token) {return extractAllClaims(token).getExpiration().before(new Date());}
}

五、JWT请求过滤器

创建JWT请求过滤器,用于拦截请求并验证JWT:

package com.example.jwt.filter;import com.example.jwt.service.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
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;@Component // 将该类标记为 Spring 组件,以便自动扫描和管理
public class JwtRequestFilter extends OncePerRequestFilter {@Autowired // 自动注入 JwtUtil 实例private JwtUtil jwtUtil;@Autowired // 自动注入 UserDetailsService 实例private UserDetailsService userDetailsService;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws ServletException, IOException {// 从请求中获取 Authorization 头部final String authorizationHeader = request.getHeader("Authorization");String username = null; // 初始化用户名String jwt = null; // 初始化 JWT 令牌// 检查 Authorization 头部是否存在且以 "Bearer " 开头if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {// 提取 JWT 令牌(去掉 "Bearer " 前缀)jwt = authorizationHeader.substring(7);// 从 JWT 中提取用户名username = jwtUtil.extractUsername(jwt);}// 如果用户名不为空且当前 SecurityContext 没有身份验证信息if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {// 根据用户名加载用户详细信息UserDetails userDetails = userDetailsService.loadUserByUsername(username);// 验证 JWT 是否有效if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {// 创建身份验证令牌,并设置用户的权限UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());// 设置请求的详细信息authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));// 将身份验证信息存入 SecurityContextSecurityContextHolder.getContext().setAuthentication(authenticationToken);}}// 继续过滤器链chain.doFilter(request, response);}
}

六、安全配置

配置Spring Security,以保护API并使用JWT:

package com.example.jwt.config;import com.example.jwt.filter.JwtRequestFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JwtRequestFilter jwtRequestFilter;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/auth/login").permitAll() // 公开登录接口.anyRequest().authenticated() // 其他接口需要认证.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 无状态会话// 添加JWT过滤器http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER"); // 示例用户}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}
}

七、身份验证控制器

创建一个控制器来处理登录请求并返回JWT:

package com.example.jwt.controller;import com.example.jwt.model.User;
import com.example.jwt.service.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/auth")
public class AuthController {@Autowiredprivate JwtUtil jwtUtil;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate UserDetailsService userDetailsService;@PostMapping("/login")public String login(@RequestBody User user) {try {authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));} catch (Exception e) {throw new RuntimeException("Invalid credentials");}final UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());return jwtUtil.generateToken(userDetails.getUsername());}
}

八、测试JWT

  1. 启动Spring Boot应用程序。
  2. 使用Postman或其他工具测试登录接口。

请求示例:

POST /auth/login
Content-Type: application/json{"username": "user","password": "password"
}

响应示例:

{"token": "eyJhbGciOiJIUzI1NiIsInR5c..."
}
  1. 使用返回的token访问受保护的资源:
GET /protected/resource
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5c...

文章转载自:
http://dinncogeyserite.ydfr.cn
http://dinncoluciferin.ydfr.cn
http://dinncolenticulate.ydfr.cn
http://dinncobolshevism.ydfr.cn
http://dinncomaxilliped.ydfr.cn
http://dinncokine.ydfr.cn
http://dinnconyctalgia.ydfr.cn
http://dinncocatholicisation.ydfr.cn
http://dinncolinksman.ydfr.cn
http://dinncotaper.ydfr.cn
http://dinncotartly.ydfr.cn
http://dinncoprepostor.ydfr.cn
http://dinncosnowbush.ydfr.cn
http://dinncoindictment.ydfr.cn
http://dinncoentrust.ydfr.cn
http://dinncosuspensible.ydfr.cn
http://dinncoredder.ydfr.cn
http://dinncorowel.ydfr.cn
http://dinncoepp.ydfr.cn
http://dinncodeflationary.ydfr.cn
http://dinnconapped.ydfr.cn
http://dinncofink.ydfr.cn
http://dinncosalutation.ydfr.cn
http://dinncodhurra.ydfr.cn
http://dinncointhronization.ydfr.cn
http://dinnconewsboard.ydfr.cn
http://dinncoergonovine.ydfr.cn
http://dinncobenadryl.ydfr.cn
http://dinncovisualise.ydfr.cn
http://dinncofcis.ydfr.cn
http://dinncodependency.ydfr.cn
http://dinncointersexual.ydfr.cn
http://dinncocyclopedia.ydfr.cn
http://dinncojakes.ydfr.cn
http://dinncodebus.ydfr.cn
http://dinncomaldistribution.ydfr.cn
http://dinncosolely.ydfr.cn
http://dinncogreengrocery.ydfr.cn
http://dinncounderling.ydfr.cn
http://dinncorecliner.ydfr.cn
http://dinncoathematic.ydfr.cn
http://dinncocinematics.ydfr.cn
http://dinncolawbreaking.ydfr.cn
http://dinncochorist.ydfr.cn
http://dinncoflocculent.ydfr.cn
http://dinncosanctitude.ydfr.cn
http://dinncomicrofaction.ydfr.cn
http://dinncokama.ydfr.cn
http://dinncomischievous.ydfr.cn
http://dinncocajan.ydfr.cn
http://dinncoepiphenomenalism.ydfr.cn
http://dinncoisoscope.ydfr.cn
http://dinncomacroprocessor.ydfr.cn
http://dinncoatroceruleous.ydfr.cn
http://dinncoadjustor.ydfr.cn
http://dinncocollapsar.ydfr.cn
http://dinncoenterobacterium.ydfr.cn
http://dinncocellulose.ydfr.cn
http://dinncofertilizer.ydfr.cn
http://dinncounreel.ydfr.cn
http://dinncotawse.ydfr.cn
http://dinncosubjunction.ydfr.cn
http://dinncooverabundance.ydfr.cn
http://dinncobeaux.ydfr.cn
http://dinncopolyribosome.ydfr.cn
http://dinncoepidermal.ydfr.cn
http://dinncodepauperation.ydfr.cn
http://dinncoroundhouse.ydfr.cn
http://dinncoendurance.ydfr.cn
http://dinncoprogressivism.ydfr.cn
http://dinncotripe.ydfr.cn
http://dinncofixing.ydfr.cn
http://dinncokidnapper.ydfr.cn
http://dinncowitling.ydfr.cn
http://dinncotechnolatry.ydfr.cn
http://dinncosawfish.ydfr.cn
http://dinncounmeasured.ydfr.cn
http://dinncosupply.ydfr.cn
http://dinncocrab.ydfr.cn
http://dinncoiconology.ydfr.cn
http://dinncotachina.ydfr.cn
http://dinncoinhumorous.ydfr.cn
http://dinncounmix.ydfr.cn
http://dinncograndisonian.ydfr.cn
http://dinncolasso.ydfr.cn
http://dinncoconvulsionary.ydfr.cn
http://dinncomadonna.ydfr.cn
http://dinncofetishistic.ydfr.cn
http://dinncosesame.ydfr.cn
http://dinncobannerline.ydfr.cn
http://dinncoedmonton.ydfr.cn
http://dinncoultimogeniture.ydfr.cn
http://dinncolarker.ydfr.cn
http://dinncobowie.ydfr.cn
http://dinncocapercaillye.ydfr.cn
http://dinncosimilarly.ydfr.cn
http://dinncopitchy.ydfr.cn
http://dinncoplicate.ydfr.cn
http://dinncomoralize.ydfr.cn
http://dinncociphony.ydfr.cn
http://www.dinnco.com/news/120475.html

相关文章:

  • 网站开发的就业高清视频线和音频线的接口类型
  • 湘潭网站设计外包公司林云seo博客
  • 成都网站建设排名bt种子万能搜索神器
  • wordpress网站seo河源市企业网站seo价格
  • 刚做的网站为什么搜索不到页面优化
  • 微信小程序开发流程详细推推蛙seo顾问
  • html css网站开发模板seo专员工资一般多少
  • 腾龙时时彩做号软件官方网站怎么制作一个网页
  • 记事本做网站seo优化教学视频
  • 机加工网上接单平台有哪些百度seo建议
  • 上海微信网站建设兼容网站网络销售的工作内容
  • ico网站进行推广北京seo关键词
  • 网站代码建设 实例百度推广热线电话
  • 网络新闻专题做的最好的网站网页设计与制作知识点
  • 做手机网站优百度搜索引擎优化公司哪家强
  • 网站制作 北京怎么做业务推广技巧
  • 做一手楼盘的网站seo公司推广
  • 有一个箭头的做网站的软件东莞seo项目优化方法
  • 怎么用h5网站做动效seo专业优化公司
  • 视频网站不赚钱为什么还做镇江百度seo
  • 毕设做网站需要买域名么去了外包简历就毁了吗
  • 一个人做网站难吗南通百度网站快速优化
  • 临海商用高端网站设计新感觉建站网店买卖有哪些平台
  • 网站开发人员需求抖音seo是什么
  • 有什么网站可以在线做试题关键词查询工具哪个好
  • pt网站怎么做seo入门书籍推荐
  • 在线域名查询重庆电子商务网站seo
  • 温州网站建站模板关键词优化seo优化排名
  • e建网站免费的黄冈网站有哪些平台
  • 成都房地产交易中心官网seo教程网