public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60;是什么意思

时间: 2024-04-07 16:27:47 浏览: 8
这是一个常量,它表示 JWT 令牌的有效期。在这个例子中,常量值为 5 * 60 * 60,表示 JWT 令牌的有效期为 5 小时。具体来说,这个常量值是通过将 5 小时转换为秒数来计算得到的,因为 JWT 令牌通常使用秒数作为有效期的单位。在生成 JWT 令牌的过程中,可以将这个常量值作为参数传递给 JWT 库,以便让 JWT 库在生成令牌时自动设置有效期。在验证 JWT 令牌时,应该检查令牌是否已经过期,以确保令牌仍然有效。
相关问题

springboot生成token

Spring Boot可以使用JWT(JSON Web Token)生成Token,JWT是一种基于JSON的开放标准,用于在不同系统之间安全地传输信息。JWT由三部分组成:头部、载荷和签名。其中,头部包含算法和类型信息,载荷包含需要传输的信息,签名用于验证Token的真实性。 在Spring Boot中使用JWT生成Token,需要引入相关依赖,如jjwt和spring-security-jwt等。然后,可以通过编写Token生成和验证的代码来实现JWT的使用。 具体步骤如下: 1. 引入相关依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>.9.1</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>.9.1</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>.9.1</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>.9.1</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-spring-boot-starter</artifactId> <version>.9.1</version> </dependency> ``` 2. 编写Token生成和验证的代码 可以在Spring Boot的配置文件中配置JWT的相关信息,如密钥、过期时间等。然后,可以编写Token生成和验证的代码,如下所示: ``` import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.function.Function; @Component public class JwtTokenUtil { private static final long serialVersionUID = -2550185165626007488L; public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60; @Value("${jwt.secret}") private String secret; //retrieve username from jwt token public String getUsernameFromToken(String token) { return getClaimFromToken(token, Claims::getSubject); } //retrieve expiration date from jwt token public Date getExpirationDateFromToken(String token) { return getClaimFromToken(token, Claims::getExpiration); } public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { final Claims claims = getAllClaimsFromToken(token); return claimsResolver.apply(claims); } //for retrieving any information from token we will need the secret key private Claims getAllClaimsFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } //check if the token has expired private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } //generate token for user public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return doGenerateToken(claims, userDetails.getUsername()); } //while creating the token - //1. Define claims of the token, like Issuer, Expiration, Subject, and the ID //2. Sign the JWT using the HS512 algorithm and secret key. //3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1) compaction of the JWT to a URL-safe string private String doGenerateToken(Map<String, Object> claims, String subject) { return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 100)) .signWith(SignatureAlgorithm.HS512, secret).compact(); } //validate token public Boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } } ``` 3. 在Controller中使用Token 在Controller中可以使用Token,如下所示: ``` @RestController @RequestMapping("/api") public class UserController { @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UserDetailsService userDetailsService; @PostMapping("/login") public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception { authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword()); final UserDetails userDetails = userDetailsService .loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails); return ResponseEntity.ok(new JwtResponse(token)); } private void authenticate(String username, String password) throws Exception { try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); } catch (DisabledException e) { throw new Exception("USER_DISABLED", e); } catch (BadCredentialsException e) { throw new Exception("INVALID_CREDENTIALS", e); } } } ``` 以上就是使用Spring Boot生成JWT Token的步骤,可以根据实际需求进行调整和修改。

springboot 生成token

在Spring Boot中生成Token的一种常见方法是使用JSON Web Token(JWT)。JWT是一种轻量级的身份验证和授权协议,可以在网络应用程序中安全地传输信息。以下是在Spring Boot中使用JWT生成Token的步骤: 1. 添加依赖项:在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2. 创建一个JWT工具类:创建一个名为JwtTokenUtil的工具类,用于生成和验证JWT令牌。以下是一个简单的例子: ```java import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.function.Function; @Component public class JwtTokenUtil { private static final long serialVersionUID = -2550185165626007488L; public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60; @Value("${jwt.secret}") private String secret; // retrieve username from jwt token public String getUsernameFromToken(String token) { return getClaimFromToken(token, Claims::getSubject); } // retrieve expiration date from jwt token public Date getExpirationDateFromToken(String token) { return getClaimFromToken(token, Claims::getExpiration); } public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { final Claims claims = getAllClaimsFromToken(token); return claimsResolver.apply(claims); } // for retrieving any information from token we will need the secret key private Claims getAllClaimsFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } // check if the token has expired private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } // generate token for user public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return doGenerateToken(claims, userDetails.getUsername()); } // while creating the token - // 1. Define claims of the token, like Issuer, Expiration, Subject, and the ID // 2. Sign the JWT using the HS512 algorithm and secret key. // 3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1) compaction of the JWT to a URL-safe string private String doGenerateToken(Map<String, Object> claims, String subject) { return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000)) .signWith(SignatureAlgorithm.HS512, secret).compact(); } // validate token public Boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } } ``` 3. 创建一个Authentication Controller:创建一个名为AuthenticationController的控制器,用于处理用户身份验证和生成JWT令牌。以下是一个简单的例子: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/auth") public class AuthenticationController { @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UserDetailsService userDetailsService; @PostMapping("/login") public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest) throws Exception { try { authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())); } catch (AuthenticationException e) { throw new Exception("Incorrect username or password", e); } final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails); return ResponseEntity.ok(new AuthenticationResponse(token)); } } ``` 4. 在application.properties中设置JWT密钥: ```properties jwt.secret=mysecretkey ``` 现在,您可以通过向“/auth/login”端点发出POST请求来生成JWT令牌。请求主体应该是包含用户名和密码的JSON对象。如果成功验证用户凭据,控制器将返回一个包含JWT令牌的JSON对象。您可以将此令牌包含在后续请求的Authorization标头中,以进行身份验证和授权。

相关推荐

最新推荐

recommend-type

基于springboot+jwt实现刷新token过程解析

主要介绍了基于springboot+jwt实现刷新token过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
recommend-type

Java中使用JWT生成Token进行接口鉴权实现方法

主要介绍了Java中使用JWT生成Token进行接口鉴权实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

Django+JWT实现Token认证的实现方法

主要介绍了Django+JWT实现Token认证的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
recommend-type

基于Java验证jwt token代码实例

主要介绍了基于Java验证jwt token代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
recommend-type

SpringSecurity Jwt Token 自动刷新的实现

主要介绍了SpringSecurity Jwt Token 自动刷新的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【实战演练】增量式PID的simulink仿真实现

# 2.1 Simulink仿真环境简介 Simulink是MATLAB中用于建模、仿真和分析动态系统的图形化环境。它提供了一个直观的用户界面,允许用户使用块和连接线来创建系统模型。Simulink模型由以下元素组成: - **子系统:**将复杂系统分解成更小的、可管理的模块。 - **块:**代表系统中的组件,如传感器、执行器和控制器。 - **连接线:**表示信号在块之间的流动。 Simulink仿真环境提供了广泛的块库,涵盖了各种工程学科,包括控制系统、电子和机械工程。它还支持用户自定义块的创建,以满足特定仿真需求。 # 2. Simulink仿真环境的搭建和建模 ### 2.
recommend-type

训练集和测试集的准确率都99%,但是预测效果不好

即使训练集和测试集的准确率都很高,但是在实际的预测中表现不佳,可能会有以下几个原因: 1. 数据质量问题:模型训练和测试的数据可能存在问题,比如数据标签错误、数据集采样不均衡、数据集中存在异常值等问题,这些问题可能会导致模型在实际预测中表现不佳。 2. 特征工程问题:模型的特征工程可能存在问题,导致模型无法很好地捕捉数据的特征,从而影响预测效果。 3. 模型选择问题:模型的选择可能不合适,比如选择的模型太简单,无法很好地拟合数据,或者选择的模型太复杂,导致过拟合等问题。 4. 超参数调整问题:模型的超参数可能没有调整到最佳状态,需要进行调整。 针对以上可能的原因,可以采取相应的措施进
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。