|
@@ -1,5 +1,5 @@
|
|
|
/*
|
|
|
- * Copyright 2020 the original author or authors.
|
|
|
+ * Copyright 2020-2021 the original author or authors.
|
|
|
*
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
* you may not use this file except in compliance with the License.
|
|
@@ -16,20 +16,15 @@
|
|
|
|
|
|
package example.web;
|
|
|
|
|
|
-import java.security.interfaces.RSAPrivateKey;
|
|
|
import java.time.Instant;
|
|
|
-import java.util.Date;
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
-import com.nimbusds.jose.JWSAlgorithm;
|
|
|
-import com.nimbusds.jose.JWSHeader;
|
|
|
-import com.nimbusds.jose.crypto.RSASSASigner;
|
|
|
-import com.nimbusds.jwt.JWTClaimsSet;
|
|
|
-import com.nimbusds.jwt.SignedJWT;
|
|
|
-
|
|
|
-import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.security.core.Authentication;
|
|
|
import org.springframework.security.core.GrantedAuthority;
|
|
|
+import org.springframework.security.oauth2.jwt.JwtClaimsSet;
|
|
|
+import org.springframework.security.oauth2.jwt.JwtEncoder;
|
|
|
+import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
|
|
|
import org.springframework.web.bind.annotation.PostMapping;
|
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
|
|
@@ -41,8 +36,8 @@ import org.springframework.web.bind.annotation.RestController;
|
|
|
@RestController
|
|
|
public class TokenController {
|
|
|
|
|
|
- @Value("${jwt.private.key}")
|
|
|
- RSAPrivateKey key;
|
|
|
+ @Autowired
|
|
|
+ JwtEncoder encoder;
|
|
|
|
|
|
@PostMapping("/token")
|
|
|
public String token(Authentication authentication) {
|
|
@@ -52,27 +47,14 @@ public class TokenController {
|
|
|
String scope = authentication.getAuthorities().stream()
|
|
|
.map(GrantedAuthority::getAuthority)
|
|
|
.collect(Collectors.joining(" "));
|
|
|
- JWTClaimsSet claims = new JWTClaimsSet.Builder()
|
|
|
+ JwtClaimsSet claims = JwtClaimsSet.builder()
|
|
|
.issuer("self")
|
|
|
- .issueTime(new Date(now.toEpochMilli()))
|
|
|
- .expirationTime(new Date(now.plusSeconds(expiry).toEpochMilli()))
|
|
|
+ .issuedAt(now)
|
|
|
+ .expiresAt(now.plusSeconds(expiry))
|
|
|
.subject(authentication.getName())
|
|
|
.claim("scope", scope)
|
|
|
.build();
|
|
|
// @formatter:on
|
|
|
- JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
|
|
|
- SignedJWT jwt = new SignedJWT(header, claims);
|
|
|
- return sign(jwt).serialize();
|
|
|
- }
|
|
|
-
|
|
|
- SignedJWT sign(SignedJWT jwt) {
|
|
|
- try {
|
|
|
- jwt.sign(new RSASSASigner(this.key));
|
|
|
- return jwt;
|
|
|
- }
|
|
|
- catch (Exception ex) {
|
|
|
- throw new IllegalArgumentException(ex);
|
|
|
- }
|
|
|
+ return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
|
|
}
|
|
|
-
|
|
|
}
|