use of org.springframework.security.oauth2.jwt.JoseHeader in project spring-authorization-server by spring-projects.
the class JwtGeneratorTests method assertGeneratedTokenType.
private void assertGeneratedTokenType(OAuth2TokenContext tokenContext) {
this.jwtGenerator.generate(tokenContext);
ArgumentCaptor<JwtEncodingContext> jwtEncodingContextCaptor = ArgumentCaptor.forClass(JwtEncodingContext.class);
verify(this.jwtCustomizer).customize(jwtEncodingContextCaptor.capture());
JwtEncodingContext jwtEncodingContext = jwtEncodingContextCaptor.getValue();
assertThat(jwtEncodingContext.getHeaders()).isNotNull();
assertThat(jwtEncodingContext.getClaims()).isNotNull();
assertThat(jwtEncodingContext.getRegisteredClient()).isEqualTo(tokenContext.getRegisteredClient());
assertThat(jwtEncodingContext.<Authentication>getPrincipal()).isEqualTo(tokenContext.getPrincipal());
assertThat(jwtEncodingContext.getAuthorization()).isEqualTo(tokenContext.getAuthorization());
assertThat(jwtEncodingContext.getAuthorizedScopes()).isEqualTo(tokenContext.getAuthorizedScopes());
assertThat(jwtEncodingContext.getTokenType()).isEqualTo(tokenContext.getTokenType());
assertThat(jwtEncodingContext.getAuthorizationGrantType()).isEqualTo(tokenContext.getAuthorizationGrantType());
assertThat(jwtEncodingContext.<Authentication>getAuthorizationGrant()).isEqualTo(tokenContext.getAuthorizationGrant());
ArgumentCaptor<JoseHeader> joseHeaderCaptor = ArgumentCaptor.forClass(JoseHeader.class);
ArgumentCaptor<JwtClaimsSet> jwtClaimsSetCaptor = ArgumentCaptor.forClass(JwtClaimsSet.class);
verify(this.jwtEncoder).encode(joseHeaderCaptor.capture(), jwtClaimsSetCaptor.capture());
JoseHeader joseHeader = joseHeaderCaptor.getValue();
assertThat(joseHeader.<JwsAlgorithm>getAlgorithm()).isEqualTo(SignatureAlgorithm.RS256);
JwtClaimsSet jwtClaimsSet = jwtClaimsSetCaptor.getValue();
assertThat(jwtClaimsSet.getIssuer().toExternalForm()).isEqualTo(tokenContext.getProviderContext().getIssuer());
assertThat(jwtClaimsSet.getSubject()).isEqualTo(tokenContext.getAuthorization().getPrincipalName());
assertThat(jwtClaimsSet.getAudience()).containsExactly(tokenContext.getRegisteredClient().getClientId());
Instant issuedAt = Instant.now();
Instant expiresAt;
if (tokenContext.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
expiresAt = issuedAt.plus(tokenContext.getRegisteredClient().getTokenSettings().getAccessTokenTimeToLive());
} else {
expiresAt = issuedAt.plus(30, ChronoUnit.MINUTES);
}
assertThat(jwtClaimsSet.getIssuedAt()).isBetween(issuedAt.minusSeconds(1), issuedAt.plusSeconds(1));
assertThat(jwtClaimsSet.getExpiresAt()).isBetween(expiresAt.minusSeconds(1), expiresAt.plusSeconds(1));
if (tokenContext.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
assertThat(jwtClaimsSet.getNotBefore()).isBetween(issuedAt.minusSeconds(1), issuedAt.plusSeconds(1));
Set<String> scopes = jwtClaimsSet.getClaim(OAuth2ParameterNames.SCOPE);
assertThat(scopes).isEqualTo(tokenContext.getAuthorizedScopes());
} else {
assertThat(jwtClaimsSet.<String>getClaim(IdTokenClaimNames.AZP)).isEqualTo(tokenContext.getRegisteredClient().getClientId());
OAuth2AuthorizationRequest authorizationRequest = tokenContext.getAuthorization().getAttribute(OAuth2AuthorizationRequest.class.getName());
String nonce = (String) authorizationRequest.getAdditionalParameters().get(OidcParameterNames.NONCE);
assertThat(jwtClaimsSet.<String>getClaim(IdTokenClaimNames.NONCE)).isEqualTo(nonce);
}
}
use of org.springframework.security.oauth2.jwt.JoseHeader in project spring-authorization-server by spring-projects.
the class JwtGenerator method generate.
@Nullable
@Override
public Jwt generate(OAuth2TokenContext context) {
if (context.getTokenType() == null || (!OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType()) && !OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue()))) {
return null;
}
if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType()) && !OAuth2TokenFormat.SELF_CONTAINED.equals(context.getRegisteredClient().getTokenSettings().getAccessTokenFormat())) {
return null;
}
String issuer = null;
if (context.getProviderContext() != null) {
issuer = context.getProviderContext().getIssuer();
}
RegisteredClient registeredClient = context.getRegisteredClient();
Instant issuedAt = Instant.now();
Instant expiresAt;
if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
// TODO Allow configuration for ID Token time-to-live
expiresAt = issuedAt.plus(30, ChronoUnit.MINUTES);
} else {
expiresAt = issuedAt.plus(registeredClient.getTokenSettings().getAccessTokenTimeToLive());
}
// @formatter:off
JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder();
if (StringUtils.hasText(issuer)) {
claimsBuilder.issuer(issuer);
}
claimsBuilder.subject(context.getPrincipal().getName()).audience(Collections.singletonList(registeredClient.getClientId())).issuedAt(issuedAt).expiresAt(expiresAt);
if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
claimsBuilder.notBefore(issuedAt);
if (!CollectionUtils.isEmpty(context.getAuthorizedScopes())) {
claimsBuilder.claim(OAuth2ParameterNames.SCOPE, context.getAuthorizedScopes());
}
} else if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
claimsBuilder.claim(IdTokenClaimNames.AZP, registeredClient.getClientId());
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType())) {
OAuth2AuthorizationRequest authorizationRequest = context.getAuthorization().getAttribute(OAuth2AuthorizationRequest.class.getName());
String nonce = (String) authorizationRequest.getAdditionalParameters().get(OidcParameterNames.NONCE);
if (StringUtils.hasText(nonce)) {
claimsBuilder.claim(IdTokenClaimNames.NONCE, nonce);
}
}
// TODO Add 'auth_time' claim
}
// @formatter:on
JoseHeader.Builder headersBuilder = JoseHeader.withAlgorithm(SignatureAlgorithm.RS256);
if (this.jwtCustomizer != null) {
// @formatter:off
JwtEncodingContext.Builder jwtContextBuilder = JwtEncodingContext.with(headersBuilder, claimsBuilder).registeredClient(context.getRegisteredClient()).principal(context.getPrincipal()).providerContext(context.getProviderContext()).authorizedScopes(context.getAuthorizedScopes()).tokenType(context.getTokenType()).authorizationGrantType(context.getAuthorizationGrantType());
if (context.getAuthorization() != null) {
jwtContextBuilder.authorization(context.getAuthorization());
}
if (context.getAuthorizationGrant() != null) {
jwtContextBuilder.authorizationGrant(context.getAuthorizationGrant());
}
// @formatter:on
JwtEncodingContext jwtContext = jwtContextBuilder.build();
this.jwtCustomizer.customize(jwtContext);
}
JoseHeader headers = headersBuilder.build();
JwtClaimsSet claims = claimsBuilder.build();
Jwt jwt = this.jwtEncoder.encode(headers, claims);
return jwt;
}
use of org.springframework.security.oauth2.jwt.JoseHeader in project spring-authorization-server by spring-projects.
the class OidcClientRegistrationEndpointFilterTests method createJwt.
private static Jwt createJwt(String scope) {
// @formatter:off
JoseHeader joseHeader = TestJoseHeaders.joseHeader().build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().claim(OAuth2ParameterNames.SCOPE, Collections.singleton(scope)).build();
Jwt jwt = Jwt.withTokenValue("jwt-access-token").headers(headers -> headers.putAll(joseHeader.getHeaders())).claims(claims -> claims.putAll(jwtClaimsSet.getClaims())).build();
// @formatter:on
return jwt;
}
use of org.springframework.security.oauth2.jwt.JoseHeader in project spring-authorization-server by spring-projects.
the class OidcClientRegistrationTests method registerClient.
private OidcClientRegistration registerClient(OidcClientRegistration clientRegistration) throws Exception {
// ***** (1) Obtain the "initial" access token used for registering the client
String clientRegistrationScope = "client.create";
// @formatter:off
RegisteredClient clientRegistrar = RegisteredClient.withId("client-registrar-1").clientId("client-registrar-1").clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT).authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).scope(clientRegistrationScope).clientSettings(ClientSettings.builder().jwkSetUrl(this.clientJwkSetUrl).tokenEndpointAuthenticationSigningAlgorithm(SignatureAlgorithm.RS256).build()).build();
// @formatter:on
this.registeredClientRepository.save(clientRegistrar);
// @formatter:off
JoseHeader joseHeader = JoseHeader.withAlgorithm(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = jwtClientAssertionClaims(clientRegistrar).build();
// @formatter:on
Jwt jwtAssertion = jwtClientAssertionEncoder.encode(joseHeader, jwtClaimsSet);
MvcResult mvcResult = this.mvc.perform(post(DEFAULT_TOKEN_ENDPOINT_URI).param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()).param(OAuth2ParameterNames.SCOPE, clientRegistrationScope).param(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, "urn:ietf:params:oauth:client-assertion-type:jwt-bearer").param(OAuth2ParameterNames.CLIENT_ASSERTION, jwtAssertion.getTokenValue()).param(OAuth2ParameterNames.CLIENT_ID, clientRegistrar.getClientId())).andExpect(status().isOk()).andExpect(jsonPath("$.access_token").isNotEmpty()).andExpect(jsonPath("$.scope").value(clientRegistrationScope)).andReturn();
OAuth2AccessToken accessToken = readAccessTokenResponse(mvcResult.getResponse()).getAccessToken();
// ***** (2) Register the client
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setBearerAuth(accessToken.getTokenValue());
// Register the client
mvcResult = this.mvc.perform(post(DEFAULT_OIDC_CLIENT_REGISTRATION_ENDPOINT_URI).headers(httpHeaders).contentType(MediaType.APPLICATION_JSON).content(getClientRegistrationRequestContent(clientRegistration))).andExpect(status().isCreated()).andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))).andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))).andReturn();
return readClientRegistrationResponse(mvcResult.getResponse());
}
use of org.springframework.security.oauth2.jwt.JoseHeader in project spring-authorization-server by spring-projects.
the class OidcUserInfoTests method createAuthorization.
private OAuth2Authorization createAuthorization() {
JoseHeader headers = JoseHeader.withAlgorithm(SignatureAlgorithm.RS256).build();
// @formatter:off
JwtClaimsSet claimSet = JwtClaimsSet.builder().claims(claims -> claims.putAll(createUserInfo().getClaims())).build();
// @formatter:on
Jwt jwt = this.jwtEncoder.encode(headers, claimSet);
Instant now = Instant.now();
Set<String> scopes = new HashSet<>(Arrays.asList(OidcScopes.OPENID, OidcScopes.ADDRESS, OidcScopes.EMAIL, OidcScopes.PHONE, OidcScopes.PROFILE));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), now, now.plusSeconds(300), scopes);
OidcIdToken idToken = OidcIdToken.withTokenValue("id-token").claims(claims -> claims.putAll(createUserInfo().getClaims())).build();
return TestOAuth2Authorizations.authorization().accessToken(accessToken).token(idToken).build();
}
Aggregations