本文整理汇总了Java中org.springframework.security.jwt.JwtHelper.decode方法的典型用法代码示例。如果您正苦于以下问题:Java JwtHelper.decode方法的具体用法?Java JwtHelper.decode怎么用?Java JwtHelper.decode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.security.jwt.JwtHelper
的用法示例。
在下文中一共展示了JwtHelper.decode方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getJwtTokenByClientCredentialForUser
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForUser() throws JsonParseException, JsonMappingException, IOException {
ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=user&password=password", null, String.class);
String responseText = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
assertEquals("bearer", jwtMap.get("token_type"));
assertEquals("read write", jwtMap.get("scope"));
assertTrue(jwtMap.containsKey("access_token"));
assertTrue(jwtMap.containsKey("expires_in"));
assertTrue(jwtMap.containsKey("jti"));
String accessToken = (String) jwtMap.get("access_token");
Jwt jwtToken = JwtHelper.decode(accessToken);
String claims = jwtToken.getClaims();
HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
assertEquals("trusted-app", claimsMap.get("client_id"));
assertEquals("user", claimsMap.get("user_name"));
assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
assertEquals("ROLE_USER", ((List<String>) claimsMap.get("authorities")).get(0));
}
开发者ID:leftso,项目名称:demo-spring-boot-security-oauth2,代码行数:26,代码来源:GrantByResourceOwnerPasswordCredentialTest.java
示例2: getJwtTokenByClientCredentialForAdmin
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByClientCredentialForAdmin() throws JsonParseException, JsonMappingException, IOException {
ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class);
String responseText = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
assertEquals("bearer", jwtMap.get("token_type"));
assertEquals("read write", jwtMap.get("scope"));
assertTrue(jwtMap.containsKey("access_token"));
assertTrue(jwtMap.containsKey("expires_in"));
assertTrue(jwtMap.containsKey("jti"));
String accessToken = (String) jwtMap.get("access_token");
Jwt jwtToken = JwtHelper.decode(accessToken);
String claims = jwtToken.getClaims();
HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
assertEquals("trusted-app", claimsMap.get("client_id"));
assertEquals("admin", claimsMap.get("user_name"));
assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
assertEquals("ROLE_ADMIN", ((List<String>) claimsMap.get("authorities")).get(0));
}
开发者ID:leftso,项目名称:demo-spring-boot-security-oauth2,代码行数:26,代码来源:GrantByResourceOwnerPasswordCredentialTest.java
示例3: verifiedToken
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
@NotNull
public static Map<String, Object> verifiedToken(String token, String publicKey) {
Jwt jwt = JwtHelper.decode(token);
// Currently not sure how we should handle this because we have multiple
// CF instances. We would need to have a central file for all UAA
// instances
// verifySignature(jwt, publicKey);
Map<String, Object> tokenObj = tryExtractToken(jwt);
if (tokenObj == null) {
throw new AuthenticationServiceException("Error parsing JWT token/extracting claims");
}
verifyExpiration(tokenObj);
return tokenObj;
}
示例4: checkJwtClaims
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
protected JsonNode checkJwtClaims(ResponseEntity<String> responseEntity, String expectedAuthority) throws IOException {
String responseBody = responseEntity.getBody();
assertThat(HttpStatus.OK, is(responseEntity.getStatusCode()));
JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody);
assertThat(responseBodyJsonNode.has("access_token"), is(true));
String accessToken = responseBodyJsonNode.get("access_token").asText();
Jwt jwt = JwtHelper.decode(accessToken);
String jwtClaims = jwt.getClaims();
JsonNode jwtClaimsJsonNode = new ObjectMapper().readTree(jwtClaims);
assertThat(jwtClaimsJsonNode.get("aud").get(0).asText(), is("sw360-REST-API"));
assertThat(jwtClaimsJsonNode.get("client_id").asText(), is("trusted-sw360-client"));
JsonNode scopeNode = jwtClaimsJsonNode.get("scope");
assertThat(scopeNode.get(0).asText(), is("sw360.read"));
assertThat(scopeNode.get(1).asText(), is("sw360.write"));
JsonNode authoritiesJsonNode = jwtClaimsJsonNode.get("authorities");
assertThat(authoritiesJsonNode.get(0).asText(), is(expectedAuthority));
assertThat(authoritiesJsonNode.size(), is(1));
return jwtClaimsJsonNode;
}
示例5: createFrom
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
public static Claims createFrom(ObjectMapper jsonMapper, OAuth2AccessToken accessToken) {
try {
String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
Jwt decodedToken = JwtHelper.decode(idToken);
return jsonMapper.readValue(decodedToken.getClaims(), Claims.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
示例6: getJwtTokenByTrustedClient
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void getJwtTokenByTrustedClient() throws JsonParseException, JsonMappingException, IOException {
ResponseEntity<String> response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?client_id=trusted-app&grant_type=client_credentials", null, String.class);
String responseText = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
assertEquals("bearer", jwtMap.get("token_type"));
assertEquals("read write", jwtMap.get("scope"));
assertTrue(jwtMap.containsKey("access_token"));
assertTrue(jwtMap.containsKey("expires_in"));
assertTrue(jwtMap.containsKey("jti"));
String accessToken = (String) jwtMap.get("access_token");
Jwt jwtToken = JwtHelper.decode(accessToken);
String claims = jwtToken.getClaims();
logJson(claims);
HashMap claimsMap = new ObjectMapper().readValue(claims, HashMap.class);
assertEquals("spring-boot-application", ((List<String>) claimsMap.get("aud")).get(0));
assertEquals("trusted-app", claimsMap.get("client_id"));
assertEquals("read", ((List<String>) claimsMap.get("scope")).get(0));
assertEquals("write", ((List<String>) claimsMap.get("scope")).get(1));
List<String> authorities = (List<String>) claimsMap.get("authorities");
assertEquals(1, authorities.size());
assertEquals("ROLE_TRUSTED_CLIENT", authorities.get(0));
}
示例7: getAccessTokenMap
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
private Map<String, Object> getAccessTokenMap() {
final Map<String, Object> accessTokenMap;
final OAuth2AccessToken accessToken = oauth2ClientContext.getAccessToken();
final Jwt decode = JwtHelper.decode(accessToken.getValue());
accessTokenMap = jsonParser.parseMap(decode.getClaims());
return accessTokenMap;
}
示例8: extractTokenInformation
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
private Map<String, Object> extractTokenInformation(String token) {
try {
final Jwt jwt = JwtHelper.decode(token);
final Map<String, Object> map = objectMapper.parseMap(jwt.getClaims());
if (map.containsKey(EXP) && map.get(EXP) instanceof Integer) {
Integer intValue = (Integer) map.get(EXP);
map.put(EXP, Long.valueOf(intValue));
}
return map;
} catch (RuntimeException mie) {
return null;
}
}
开发者ID:cloudfoundry-incubator,项目名称:credhub,代码行数:16,代码来源:AuditOAuth2AuthenticationExceptionHandler.java
示例9: JWTToken
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
public JWTToken(String token) throws IOException {
authorities = new ArrayList<>();
this.token = token;
this.jwt = JwtHelper.decode(token);
ObjectMapper mapper = new ObjectMapper();
this.claims = mapper.readValue(jwt.getClaims(), JwtPayload.class);
}
示例10: authenticate
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
@Override
public Authentication authenticate(final Authentication authRequest) throws AuthenticationException {
// Getting string token from authentication request object
String token = Preconditions.notNull(StringUtils.trimToNull((String) authRequest.getCredentials()), ExceptionCode.AUTHENTICATION, "No jwt token present.");
// Getting JWT object from string token
Jwt jwt = JwtHelper.decode(token);
// Getting payload of token
String claims = jwt.getClaims();
TokenPayload tokenPayload = this.gson.fromJson(claims, TokenPayload.class);
// Checking if token already expired and throwing an AuthenticationException in this case
checkIsExpired(tokenPayload.expirationTime);
// Getting user id from token
Long userId = Preconditions.notNull(tokenPayload.userId, ExceptionCode.AUTHENTICATION, "Token doesn't contains user id.");
// Getting user from database
HeapUser user = this.heapUserRepository.findOne(userId);
// Validate token signature (to be sure that token doesn't change on client side)
try {
jwt.verifySignature(new MacSigner(user.getSecret()));
} catch (Exception cause) {
HeapException.throwNew(ExceptionCode.AUTHENTICATION, "Token verification failed.", cause);
}
// Return authenticated Authentication
HeapUserDetails userDetails = new HeapUserDetails(user);
userDetails.eraseCredentials();
return new JwtAuthenticationToken(userDetails);
}
示例11: loadAuthentication
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
@Override
@Cacheable(cacheNames = "tokenCache", key = "#accessToken")
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
if (StringUtils.isBlank(jwtSignKey)) {
return getOAuth2Authentication(accessToken);
}
Jwt jwtToken = JwtHelper.decode(accessToken);
try {
Map<String, Object> claims = objectMapper.readValue(jwtToken.getClaims(), new MapTypeReference());
return claims.get("user") == null ? getOAuth2Authentication(accessToken) : getSSOAuthentication(accessToken);
} catch (IOException e) {
LOGGER.error("Token does not claim anything", e);
throw new InvalidTokenException("Invalid JWT token, does not claim anything", e);
}
}
示例12: getClaim
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
/**
* Retrieve the given claim from the given token.
*
* @param refreshToken the JWT token to examine.
* @param claimName name of the claim to get.
* @param clazz the Class we expect to find there.
* @return the desired claim.
* @throws InvalidTokenException if we cannot find the claim in the token or it is of wrong type.
*/
@SuppressWarnings("unchecked")
private <T> T getClaim(String refreshToken, String claimName, Class<T> clazz) {
Jwt jwt = JwtHelper.decode(refreshToken);
String claims = jwt.getClaims();
Map<String, Object> claimsMap = jsonParser.parseMap(claims);
Object claimValue = claimsMap.get(claimName);
if (claimValue == null) {
return null;
}
if (!clazz.isAssignableFrom(claimValue.getClass())) {
throw new InvalidTokenException("claim is not of expected type: " + claimName);
}
return (T) claimValue;
}
示例13: decodeAndVerify
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
@Nullable
@Override
public BlueWebToken decodeAndVerify(@Nonnull final String idToken){
final long now = System.currentTimeMillis();
if(log.isTraceEnabled()){
log.trace("Decoding token [" + idToken + "]");
}
try{
Jwt jwt = JwtHelper.decode(idToken);
// Get the key ID we need to use to verify the token
String keyId = getKeyId(idToken);
if("".equals(keyId.trim())){
log.warn("Failed to retrieve key ID for token");
return null;
}
BlueWebToken token = typeSecuredObjectMapper().readValue(
jwt.getClaims(),
BlueWebToken.class);
// Get the key and verify the JWT signature
RSAPublicKey key = rsaPublicKey(keyId, token.getAuthContextReference());
jwt.verifySignature(new RsaVerifier(key));
// Validate the nonce
if(!nonceService.isValid(token.getNonce())){
log.warn("Failed to validate nonce in token. This could be a replay attack.");
return null;
}
if(!claimValidationService.validateAudience(token)){
log.warn("Failed to validate audience in token. This could be a replay attack.");
return null;
}
if(!claimValidationService.validateIssuer(token)){
log.warn("Failed to validate issuer of token. This could be a replay attack.");
return null;
}
if(!claimValidationService.validateNotBefore(token, now)){
log.warn("Failed to validate notBefore time in token. This could be a replay attack. 'Now' milliseconds: " + now + "; 'NotBefore' milliseconds: " + token
.getNotBefore()
.toInstant()
.toEpochMilli());
return null;
}
if(!claimValidationService.validateExpiration(token, now)){
log.warn("Failed to validate expiration time in token. This could be a replay attack. 'Now' milliseconds: " + now + "; 'Expiration' milliseconds: " + token
.getExpiration()
.toInstant()
.toEpochMilli());
return null;
}
return token;
}catch(IOException | IllegalArgumentException | InvalidSignatureException x){
log.warn("Failed to extract data from JWT token: " + x.getMessage(), x);
}
return null;
}
示例14: parseJwtToken
import org.springframework.security.jwt.JwtHelper; //导入方法依赖的package包/类
private static OAuthToken parseJwtToken(String jwtToken) {
try {
Jwt jwt = JwtHelper.decode(jwtToken);
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jwt.getClaims().getBytes(), OAuthToken.class);
} catch (IOException e) {
throw new AuthenticationException("Invalid OAuth2 Token", e);
}
}