本文整理了Java中org.springframework.security.jwt.Jwt
类的一些代码示例,展示了Jwt
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Jwt
类的具体详情如下:
包路径:org.springframework.security.jwt.Jwt
类名称:Jwt
[英]An implementation of a SecurityToken representing a JSON Web Token (JWT).
JWTs represent a set of "Claims" as a JSON object that is encoded in a JSON Web Signature (JWS) and/or JSON Web Encryption (JWE) structure. The JSON object, also known as the JWT Claims Set, consists of one or more Claim Name/Claim Value pairs. The Claim Name is a String
and the Claim Value is an arbitrary JSON object.
[中]表示JSON Web令牌(JWT)的SecurityToken的实现。
JWT将一组“声明”表示为JSON对象,该对象以JSON Web签名(JWS)和/或JSON Web加密(JWE)结构编码。JSON对象,也称为JWT声明集,由一个或多个声明名称/声明值对组成。声明名称为String
,声明值为任意JSON对象。
代码示例来源:origin: cloudfoundry/uaa
private String getZoneIdFromToken(String token) {
Jwt tokenJwt;
try {
tokenJwt = JwtHelper.decode(token);
} catch (Throwable t) {
throw new IllegalStateException("Cannot decode token", t);
}
Map<String, Object> claims;
try {
claims = JsonUtils.readValue(tokenJwt.getClaims(), new TypeReference<Map<String, Object>>() {});
} catch (JsonUtils.JsonUtilException e) {
throw new IllegalStateException("Cannot read token claims", e);
}
return (String)claims.get(ClaimConstants.ZONE_ID);
}
}
代码示例来源:origin: spring-projects/spring-security-oauth
protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
String content;
try {
content = objectMapper.formatMap(tokenConverter.convertAccessToken(accessToken, authentication));
}
catch (Exception e) {
throw new IllegalStateException("Cannot convert access token to JSON", e);
}
String token = JwtHelper.encode(content, signer).getEncoded();
return token;
}
代码示例来源:origin: spring-projects/spring-security-oauth
jwt.verifySignature(verifier);
Map<String, Object> claims = this.jsonParser.parseMap(jwt.getClaims());
if (claims.containsKey(EXP) && claims.get(EXP) instanceof Integer) {
Integer expiryInt = (Integer) claims.get(EXP);
代码示例来源:origin: org.springframework.security/spring-security-jwt
public static Jwt decodeAndVerify(String token, SignatureVerifier verifier) {
Jwt jwt = decode(token);
jwt.verifySignature(verifier);
return jwt;
}
代码示例来源:origin: org.springframework.security/spring-security-jwt-jose
@Override
public Jwt decode(String token) throws JwtException {
Jwt jwt;
try {
JWT parsedJwt = JWTParser.parse(token);
// Verify the signature
JWTClaimsSet jwtClaimsSet = this.jwtProcessor.process(parsedJwt, null);
Instant expiresAt = jwtClaimsSet.getExpirationTime().toInstant();
Instant issuedAt;
if (jwtClaimsSet.getIssueTime() != null) {
issuedAt = jwtClaimsSet.getIssueTime().toInstant();
} else {
// issuedAt is required in SecurityToken so let's default to expiresAt - 1 second
issuedAt = Instant.from(expiresAt).minusSeconds(1);
}
Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
jwt = new Jwt(token, issuedAt, expiresAt, headers, jwtClaimsSet.getClaims());
} catch (Exception ex) {
throw new JwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex);
}
return jwt;
}
}
代码示例来源:origin: zhoutaoo/SpringCloud
@Override
public boolean invalidJwtAccessToken(String authentication) {
verifier = Optional.ofNullable(verifier).orElse(new MacSigner(signingKey));
//是否无效true表示无效
boolean invalid = Boolean.TRUE;
try {
Jwt jwt = getJwt(authentication);
jwt.verifySignature(verifier);
invalid = Boolean.FALSE;
} catch (InvalidSignatureException | IllegalArgumentException ex) {
log.warn("user token has expired or signature error ");
}
return invalid;
}
代码示例来源:origin: cloudfoundry/uaa
private String getPrincipalId() {
OAuth2AccessToken token = getSource();
Jwt jwt = JwtHelper.decode(token.getValue());
Map<String, Object> claims = JsonUtils.readValue(jwt.getClaims(), new TypeReference<Map<String, Object>>() {});
return (claims.get("user_id") != null ? claims.get("user_id") : claims.get("client_id")).toString();
}
}
代码示例来源:origin: org.springframework.security.oauth/spring-security-oauth2
jwt.verifySignature(verifier);
Map<String, Object> claims = this.jsonParser.parseMap(jwt.getClaims());
if (claims.containsKey(EXP) && claims.get(EXP) instanceof Integer) {
Integer expiryInt = (Integer) claims.get(EXP);
代码示例来源:origin: org.springframework.security.oauth/spring-security-oauth2
protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
String content;
try {
content = objectMapper.formatMap(tokenConverter.convertAccessToken(accessToken, authentication));
}
catch (Exception e) {
throw new IllegalStateException("Cannot convert access token to JSON", e);
}
String token = JwtHelper.encode(content, signer).getEncoded();
return token;
}
代码示例来源:origin: jorrellz/JetfireCloud
@Override
public boolean invalidJwtAccessToken(String authentication) {
verifier = Optional.ofNullable(verifier).orElse(new MacSigner(signingKey));
//是否无效true表示无效
boolean invalid = Boolean.TRUE;
try {
Jwt jwt = getJwt(authentication);
jwt.verifySignature(verifier);
invalid = Boolean.FALSE;
} catch (InvalidSignatureException | IllegalArgumentException ex) {
log.warn("user token has expired or signature error ");
}
return invalid;
}
代码示例来源:origin: spring-projects/spring-security-oauth
protected Map<String, Object> decode(String token) {
try {
Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
String claimsStr = jwt.getClaims();
Map<String, Object> claims = objectMapper.parseMap(claimsStr);
if (claims.containsKey(EXP) && claims.get(EXP) instanceof Integer) {
Integer intValue = (Integer) claims.get(EXP);
claims.put(EXP, new Long(intValue));
}
this.getJwtClaimsSetVerifier().verify(claims);
return claims;
}
catch (Exception e) {
throw new InvalidTokenException("Cannot convert access token to JSON", e);
}
}
代码示例来源:origin: io.choerodon/choerodon-starter-feign-replay
@Override
public void apply(RequestTemplate template) {
try {
String token = null;
if (SecurityContextHolder.getContext() != null
&& SecurityContextHolder.getContext().getAuthentication() != null
&& SecurityContextHolder.getContext().getAuthentication().getDetails() instanceof OAuth2AuthenticationDetails) {
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder
.getContext().getAuthentication().getDetails();
if (details.getTokenType() != null && details.getTokenValue() != null) {
token = details.getTokenType() + " " + details.getTokenValue();
} else if (details.getDecodedDetails() instanceof CustomUserDetails) {
token = OAUTH_TOKEN_PREFIX
+ JwtHelper.encode(OBJECT_MAPPER.writeValueAsString(details.getDecodedDetails()), signer).getEncoded();
}
}
if (token == null) {
token = OAUTH_TOKEN_PREFIX + JwtHelper.encode(OBJECT_MAPPER.writeValueAsString(defaultUserDetails), signer).getEncoded();
}
template.header(RequestVariableHolder.HEADER_JWT, token);
setLabel(template);
} catch (Exception e) {
LOGGER.error("generate jwt token failed {}", e);
}
}
代码示例来源:origin: cloudfoundry/uaa
private IntrospectionClaims getClaimsForToken(String token) {
org.springframework.security.jwt.Jwt tokenJwt;
tokenJwt = JwtHelper.decode(token);
IntrospectionClaims claims;
try {
// we assume token.getClaims is never null due to previously parsing token when verifying the token
claims = JsonUtils.readValue(tokenJwt.getClaims(), IntrospectionClaims.class);
} catch (JsonUtils.JsonUtilException e) {
logger.error("Can't parse introspection claims in token. Is it a valid JSON?");
throw new InvalidTokenException("Cannot read token claims", e);
}
return claims;
}
代码示例来源:origin: com.hand.hap.cloud/hap-feign-replay-starter
@Override
public void apply(RequestTemplate template) {
if (HystrixRequestContext.isCurrentThreadInitialized()) {
String token = HystrixHeaderInterceptor.token.get();
String label = HystrixHeaderInterceptor.label.get();
if (token != null) {
template.header(HystrixHeaderInterceptor.HEADER_TOKEN, token);
}else {
try {
String jwtToken = "Bearer " + JwtHelper.encode(OBJECT_MAPPER.writeValueAsString(DEFAULT_USER), SIGNER).getEncoded();
LOGGER.info("token {}",jwtToken);
template.header(HystrixHeaderInterceptor.HEADER_TOKEN, jwtToken);
} catch (IOException e) {
LOGGER.info("error {}",e);
}
}
if (label != null) {
template.header(HystrixHeaderInterceptor.HEADER_LABEL, label);
}
}else {
try {
String jwtToken = "Bearer " + JwtHelper.encode(OBJECT_MAPPER.writeValueAsString(DEFAULT_USER), SIGNER).getEncoded();
LOGGER.info("token {}",jwtToken);
template.header(HystrixHeaderInterceptor.HEADER_TOKEN, jwtToken);
} catch (IOException e) {
LOGGER.info("error {}",e);
}
}
}
代码示例来源:origin: cloudfoundry/uaa
protected void appendTokenDetails(Authentication caller, StringBuilder builder) {
String tokenValue = null;
if (caller instanceof UaaOauth2Authentication) {
tokenValue = ((UaaOauth2Authentication)caller).getTokenValue();
} else if (caller.getDetails() instanceof OAuth2AuthenticationDetails) {
tokenValue = ((OAuth2AuthenticationDetails)authentication.getDetails()).getTokenValue();
}
if (hasText(tokenValue)) {
if (isJwtToken(tokenValue)) {
try {
Jwt token = JwtHelper.decode(tokenValue);
Map<String, Object> claims = JsonUtils.readValue(token.getClaims(), new TypeReference<Map<String, Object>>() {
});
String issuer = claims.get(ClaimConstants.ISS).toString();
String subject = claims.get(ClaimConstants.SUB).toString();
builder.append(", sub=").append(subject).append(", ").append("iss=").append(issuer);
} catch (Exception e) {
builder.append(", <token extraction failed>");
}
} else {
builder.append(", opaque-token=present");
}
}
}
代码示例来源:origin: otto-de/edison-microservice
public String getBearerToken(final String scope) {
final ZonedDateTime soon = ZonedDateTime.now().plusDays(365);
final String jwtToken = "{\n" +
" \"aud\": [\n" +
" \"" + aud + "\"\n" +
" ],\n" +
" \"exp\": " + soon.toEpochSecond() + ",\n" +
" \"user_name\": \"3d44bbc24614e28edd094bc54ef0497809717af5\",\n" +
" \"jti\": \"3cee521d-96a7-4d82-b726-7e02355f3a55\",\n" +
" \"client_id\": \"fe0661e5a99e4d43bd3496cc6c58025f\",\n" +
" \"scope\": [\n" +
" \"" + scope + "\"\n" +
" ]\n" +
"}";
final RsaSigner rsaSigner = new RsaSigner((RSAPrivateKey) keyPair.getPrivate());
final Jwt encode = JwtHelper.encode(jwtToken, rsaSigner);
return "Bearer " + encode.getEncoded();
}
}
代码示例来源:origin: cloudfoundry/uaa
private void exchangeCodeForToken(String clientId, String redirectUri, String clientSecret, String value, MultiValueMap<String, String> formData) {
formData.clear();
formData.add("client_id", clientId);
formData.add("redirect_uri", redirectUri);
formData.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE);
formData.add("code", value);
HttpHeaders tokenHeaders = new HttpHeaders();
tokenHeaders.set("Authorization",
testAccounts.getAuthorizationHeader(clientId, clientSecret));
@SuppressWarnings("rawtypes")
ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders);
assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, String> body = tokenResponse.getBody();
Jwt token = JwtHelper.decode(body.get("access_token"));
assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}
代码示例来源:origin: cloudfoundry/uaa
private Claims getClaimsForToken(String token) {
Jwt tokenJwt;
try {
tokenJwt = JwtHelper.decode(token);
} catch (Throwable t) {
throw new InvalidTokenException("Invalid token (could not decode): " + token);
}
Claims claims;
try {
claims = JsonUtils.readValue(tokenJwt.getClaims(), Claims.class);
} catch (JsonUtils.JsonUtilException e) {
throw new InvalidTokenException("Cannot read token claims", e);
}
return claims;
}
代码示例来源:origin: cloudfoundry/uaa
public void testSuccessfulAuthorizationCodeFlow_Internal() throws Exception {
AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource();
Map<String, String> body = IntegrationTestUtils.getAuthorizationCodeTokenMap(serverRunning,
testAccounts,
resource.getClientId(),
resource.getClientSecret(),
testAccounts.getUserName(),
testAccounts.getPassword());
Jwt token = JwtHelper.decode(body.get("access_token"));
assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}
}
代码示例来源:origin: cloudfoundry/uaa
private void validateToken(String paramName, Map params, String[] scopes, String[] aud) throws java.io.IOException {
Jwt access_token = JwtHelper.decode((String)params.get(paramName));
Map<String, Object> claims = JsonUtils.readValue(access_token.getClaims(), new TypeReference<Map<String, Object>>() {
});
Assert.assertThat(claims.get("jti"), is(params.get("jti")));
Assert.assertThat(claims.get("client_id"), is("cf"));
Assert.assertThat(claims.get("cid"), is("cf"));
Assert.assertThat(claims.get("user_name"), is(user.getUserName()));
Assert.assertThat(((List<String>) claims.get(ClaimConstants.SCOPE)), containsInAnyOrder(scopes));
Assert.assertThat(((List<String>) claims.get(ClaimConstants.AUD)), containsInAnyOrder(aud));
}
内容来源于网络,如有侵权,请联系作者删除!