Spring Security JWT

huangapple go评论85阅读模式
英文:

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.
&lt;dependency&gt;
&lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;
&lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;
&lt;version&gt;0.10.7&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;
&lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;
&lt;version&gt;0.10.7&lt;/version&gt;
&lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
&lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;
&lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;
&lt;version&gt;0.10.7&lt;/version&gt;
&lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;
**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(&quot;${springbootwebfluxjjwt.jjwt.secret}&quot;)
private String secret;
@Value(&quot;${springbootwebfluxjjwt.jjwt.expiration}&quot;)
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&lt;String, Object&gt; claims = new HashMap&lt;&gt;();
claims.put(&quot;role&quot;, user.getRoles());
return doGenerateToken(claims, user.getUsername());
}
private String doGenerateToken(Map&lt;String, Object&gt; 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.
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-jwt&lt;/artifactId&gt;
&lt;version&gt;1.1.0.RELEASE&lt;/version&gt;
&lt;/dependency&gt;
Is there any example to convert the current JWTUtil with the spring-security-jwt API&#39;s?
</details>
# 答案1
**得分**: 4
您可以使用以下代码:
```xml
&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-jwt&lt;/artifactId&gt;
&lt;version&gt;1.0.11.RELEASE&lt;/version&gt;
&lt;/dependency&gt;

对应的Java代码如下:

// 使用token字符串解码
Jwt decodedJwt = JwtHelper.decode(jwtToken);
// 获取声明
JSONObject claims = new JSONObject(decodedJwt.getClaims());
// 获取过期时间
Date exp = new Date(claims.getLong(&quot;exp&quot;));
// 获取主题
claims.getString(&quot;sub&quot;);

此外,您可以在这里查看关于 org.springframework.security.jwt.JwtHelper 的一些示例。

编辑:
在版本 1.1.0.RELEASE 中,JwtHelper 已被标记为 deprecated,您可以参考迁移指南

英文:

You can use

&lt;dependency&gt;
&lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
&lt;artifactId&gt;spring-security-jwt&lt;/artifactId&gt;
&lt;version&gt;1.0.11.RELEASE&lt;/version&gt;
&lt;/dependency&gt;

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(&quot;exp&quot;));
//get subject
claims.getString(&quot;sub&quot;);

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 :

&lt;dependency&gt;
&lt;groupId&gt;com.auth0&lt;/groupId&gt;
&lt;artifactId&gt;java-jwt&lt;/artifactId&gt;
&lt;version&gt;3.10.0&lt;/version&gt;
&lt;/dependency&gt;

huangapple
  • 本文由 发表于 2020年4月7日 06:51:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/61070170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定