-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use Spring security oauth2ResourceServer and spring oauth2-resource-s…
…erver for security
- Loading branch information
1 parent
286c1b4
commit 944de84
Showing
15 changed files
with
280 additions
and
278 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -21,7 +21,7 @@ | |
* GraphQL handler functions for Vet GraphQL type, Query and Mutation | ||
* | ||
* Note that the addVet mutation is secured in the domain layer, so that only | ||
* users with ROLE_MANAGER are allowed to create new vets | ||
* users with SCOPE_MANAGER are allowed to create new vets | ||
* | ||
* @author Nils Hartmann ([email protected]) | ||
*/ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
96 changes: 0 additions & 96 deletions
96
...src/main/java/org/springframework/samples/petclinic/security/JwtAuthenticationFilter.java
This file was deleted.
Oops, something went wrong.
108 changes: 30 additions & 78 deletions
108
backend/src/main/java/org/springframework/samples/petclinic/security/JwtTokenService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,97 +1,49 @@ | ||
package org.springframework.samples.petclinic.security; | ||
|
||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.security.Keys; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.samples.petclinic.auth.User; | ||
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.stereotype.Service; | ||
|
||
import jakarta.annotation.PostConstruct; | ||
import javax.crypto.SecretKey; | ||
import java.nio.charset.StandardCharsets; | ||
import java.text.SimpleDateFormat; | ||
import java.util.Date; | ||
import java.time.Instant; | ||
import java.time.temporal.ChronoUnit; | ||
import java.util.Collection; | ||
import java.util.stream.Collectors; | ||
|
||
/** | ||
* Note that this is an example only. DO NOT IMPLEMENT OWN SECURITY CODE IN REAL PRODUCTION APPS !!!!!!!!!! | ||
* | ||
* @author Nils Hartmann ([email protected]) | ||
* Based con code taken from Dan Vega https://github.com/danvega/jwt-username-password/blob/master/src/main/java/dev/danvega/jwt/service/TokenService.java | ||
*/ | ||
@Service | ||
public class JwtTokenService { | ||
private final Logger logger = LoggerFactory.getLogger(getClass()); | ||
|
||
@Value("${jwt.expirationInMs:7200000}") | ||
private int jwtExpirationInMs; | ||
private final JwtEncoder encoder; | ||
|
||
private final SecretKey secretKey; | ||
|
||
public JwtTokenService(@Value("${jwt.secretString:fasdfahsdufak4923674asbclbca73,f,a,dfw}") String secretString) { | ||
this.secretKey = Keys.hmacShaKeyFor(secretString.getBytes(StandardCharsets.UTF_8)); | ||
} | ||
|
||
/** Creates a token that will never expire and will be stable accross re-starts | ||
* as longs as jwt.secretString does not change. | ||
* | ||
* This token can be used for easier testing using command line tools etc. | ||
* YOU SHOULD NEVER DO THIS IN 'REAL' PRODUCTION APPS | ||
*/ | ||
@PostConstruct | ||
void createNeverExpiringToken() throws Exception { | ||
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy HH:mm"); | ||
String neverExpiringManagerToken = Jwts.builder() | ||
.setSubject("susi") | ||
.setIssuedAt(f.parse("25.12.2020 10:44")) | ||
.setExpiration(f.parse("25.12.2044 10:44")) | ||
.signWith(secretKey) | ||
.compact(); | ||
|
||
String neverExpiringUserToken = Jwts.builder() | ||
.setSubject("joe") | ||
.setIssuedAt(f.parse("25.12.2020 10:44")) | ||
.setExpiration(f.parse("25.12.2044 10:44")) | ||
.signWith(secretKey) | ||
.compact(); | ||
logger.info("\n\nNever Expiring JWT Token\n\n - ROLE_MANAGER: '{}'\n As HTTP Header: 'Authorization: Bearer {}'\n\n - ROLE_USER: '{}'\n As HTTP Header: 'Authorization: Bearer {}'\n", neverExpiringManagerToken, neverExpiringManagerToken, neverExpiringUserToken, neverExpiringUserToken); | ||
public JwtTokenService(JwtEncoder encoder) { | ||
this.encoder = encoder; | ||
} | ||
|
||
public String createTokenForUser(User user) { | ||
|
||
Date now = new Date(); | ||
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs); | ||
|
||
return Jwts.builder() | ||
.setSubject(user.getUsername()) | ||
.setIssuedAt(now) | ||
.setExpiration(expiryDate) | ||
.signWith(secretKey) | ||
.compact(); | ||
public String generateToken(Authentication authentication) { | ||
return generateToken(authentication.getName(), | ||
authentication.getAuthorities(), | ||
Instant.now().plus(1, ChronoUnit.HOURS) | ||
); | ||
} | ||
|
||
public String getUsernameFromToken(String token) { | ||
Claims claims = Jwts.parserBuilder() | ||
.setSigningKey(secretKey) | ||
.build() | ||
.parseClaimsJws(token) | ||
.getBody(); | ||
|
||
return claims.getSubject(); | ||
} | ||
public String generateToken(String name, Collection<? extends GrantedAuthority> authorities, Instant expiresAt) { | ||
String scope = authorities.stream() | ||
.map(GrantedAuthority::getAuthority) | ||
.collect(Collectors.joining(" ")); | ||
|
||
public boolean isValidToken(String authToken) { | ||
try { | ||
Jwts.parserBuilder() | ||
.setSigningKey(secretKey) | ||
.build() | ||
.parseClaimsJws(authToken); | ||
return true; | ||
} catch (Exception ex) { | ||
logger.info("Invalid JWT token: " + ex); | ||
} | ||
JwtClaimsSet claims = JwtClaimsSet.builder() | ||
.issuer("self") | ||
.issuedAt(Instant.now()) | ||
.expiresAt(expiresAt) | ||
.subject(name) | ||
.claim("scope", scope) | ||
.build(); | ||
|
||
return false; | ||
return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue(); | ||
} | ||
} |
Oops, something went wrong.