英文:
Spring security JWT
问题
我正在尝试使用Spring Security实现基于JWT的身份验证。
目前,使用以下依赖项。
**JWtUtil类**
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Component
public class JWTUtil implements Serializable {
private static final long serialVersionUID = 1L;
@Value("${springbootwebfluxjjwt.jjwt.secret}")
private String secret;
@Value("${springbootwebfluxjjwt.jjwt.expiration}")
private String expirationTime;
public Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(Base64.getEncoder().encodeToString(secret.getBytes())).parseClaimsJws(token)
.getBody();
}
public String getUsernameFromToken(String token) {
return getAllClaimsFromToken(token).getSubject();
}
public Date getExpirationDateFromToken(String token) {
return getAllClaimsFromToken(token).getExpiration();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String generateToken(User user) {
Map<String, Object> claims = new HashMap<>();
claims.put("role", user.getRoles());
return doGenerateToken(claims, user.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String username) {
Long expirationTimeLong = Long.parseLong(expirationTime); // in second
final Date createdDate = new Date();
final Date expirationDate = new Date(createdDate.getTime() + expirationTimeLong * 1000);
return Jwts.builder().setClaims(claims).setSubject(username).setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, Base64.getEncoder().encodeToString(secret.getBytes())).compact();
}
public Boolean validateToken(String token) {
return !isTokenExpired(token);
}
}
遇到了用于JWT的Spring依赖项。但是找不到相应的API。
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.0.RELEASE</version>
</dependency>
是否有示例将当前的JWTUtil转换为使用spring-security-jwt API的方式?
<details>
<summary>英文:</summary>
I am trying to implement JWT based auth with Spring security.
Currently, using the below dependencies.
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.10.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.10.7</version>
<scope>runtime</scope>
</dependency>
**JWtUtil class**
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
@Component
public class JWTUtil implements Serializable {
private static final long serialVersionUID = 1L;
@Value("${springbootwebfluxjjwt.jjwt.secret}")
private String secret;
@Value("${springbootwebfluxjjwt.jjwt.expiration}")
private String expirationTime;
public Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(Base64.getEncoder().encodeToString(secret.getBytes())).parseClaimsJws(token)
.getBody();
}
public String getUsernameFromToken(String token) {
return getAllClaimsFromToken(token).getSubject();
}
public Date getExpirationDateFromToken(String token) {
return getAllClaimsFromToken(token).getExpiration();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
public String generateToken(User user) {
Map<String, Object> claims = new HashMap<>();
claims.put("role", user.getRoles());
return doGenerateToken(claims, user.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String username) {
Long expirationTimeLong = Long.parseLong(expirationTime); // in second
final Date createdDate = new Date();
final Date expirationDate = new Date(createdDate.getTime() + expirationTimeLong * 1000);
return Jwts.builder().setClaims(claims).setSubject(username).setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS512, Base64.getEncoder().encodeToString(secret.getBytes())).compact();
}
public Boolean validateToken(String token) {
return !isTokenExpired(token);
}
}
Came across spring dependency for JWT. But unable to find the correponding API.
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.0.RELEASE</version>
</dependency>
Is there any example to convert the current JWTUtil with the spring-security-jwt API's?
</details>
# 答案1
**得分**: 4
您可以使用以下代码:
```xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.11.RELEASE</version>
</dependency>
对应的Java代码如下:
// 使用token字符串解码
Jwt decodedJwt = JwtHelper.decode(jwtToken);
// 获取声明
JSONObject claims = new JSONObject(decodedJwt.getClaims());
// 获取过期时间
Date exp = new Date(claims.getLong("exp"));
// 获取主题
claims.getString("sub");
此外,您可以在这里查看关于 org.springframework.security.jwt.JwtHelper
的一些示例。
编辑:
在版本 1.1.0.RELEASE
中,JwtHelper
已被标记为 deprecated
,您可以参考迁移指南。
英文:
You can use
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.0.11.RELEASE</version>
</dependency>
Java code for this:
//decode using token as String
Jwt decodedJwt = JwtHelper.decode(jwtToken);
//get Claims
JSONObject claims = new JSONObject(decodedJwt.getClaims());
//get expiration date
Date exp = new Date(claims.getLong("exp"));
//get subject
claims.getString("sub");
Additional you can check here some examples for org.springframework.security.jwt.JwtHelper
EDIT:
in version 1.1.0.RELEASE
JwtHelper
is deprecated
and you can use migration guide
答案2
得分: 0
我正在使用带有JWT的Spring Security,我所依赖的库如下:
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.0</version>
</dependency>
英文:
I'm using spring security with jwt and the dependecy I have is this one :
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.0</version>
</dependency>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论