use of com.auth0.jwt.JWT in project dhis2-core by dhis2.
the class JwtUtils method encode.
public Jwt encode(JoseHeader headers, JwtClaimsSet claims) throws JwtEncodingException {
Assert.notNull(headers, "headers cannot be null");
Assert.notNull(claims, "claims cannot be null");
JWK jwk = selectJwk(headers);
if (jwk == null) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
} else if (!StringUtils.hasText(jwk.getKeyID())) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "The \"kid\" (key ID) from the selected JWK cannot be empty"));
}
headers = JoseHeader.from(headers).type(JOSEObjectType.JWT.getType()).keyId(jwk.getKeyID()).build();
claims = JwtClaimsSet.from(claims).id(UUID.randomUUID().toString()).build();
JWSHeader jwsHeader = JWS_HEADER_CONVERTER.convert(headers);
JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims);
JWSSigner jwsSigner = this.jwsSigners.computeIfAbsent(jwk, (key) -> {
try {
return JWS_SIGNER_FACTORY.createJWSSigner(key);
} catch (JOSEException ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to create a JWS Signer -> " + ex.getMessage()), ex);
}
});
SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet);
try {
signedJwt.sign(jwsSigner);
} catch (JOSEException ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex);
}
String jws = signedJwt.serialize();
return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims());
}
use of com.auth0.jwt.JWT in project spring-security by spring-projects.
the class JwtBearerOAuth2AuthorizedClientProvider method authorize.
/**
* Attempt to authorize (or re-authorize) the
* {@link OAuth2AuthorizationContext#getClientRegistration() client} in the provided
* {@code context}. Returns {@code null} if authorization (or re-authorization) is not
* supported, e.g. the client's {@link ClientRegistration#getAuthorizationGrantType()
* authorization grant type} is not {@link AuthorizationGrantType#JWT_BEARER
* jwt-bearer} OR the {@link OAuth2AuthorizedClient#getAccessToken() access token} is
* not expired.
* @param context the context that holds authorization-specific state for the client
* @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not
* supported
*/
@Override
@Nullable
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) {
Assert.notNull(context, "context cannot be null");
ClientRegistration clientRegistration = context.getClientRegistration();
if (!AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType())) {
return null;
}
OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient();
if (authorizedClient != null && !hasTokenExpired(authorizedClient.getAccessToken())) {
// need for re-authorization
return null;
}
Jwt jwt = this.jwtAssertionResolver.apply(context);
if (jwt == null) {
return null;
}
// As per spec, in section 4.1 Using Assertions as Authorization Grants
// https://tools.ietf.org/html/rfc7521#section-4.1
//
// An assertion used in this context is generally a short-lived
// representation of the authorization grant, and authorization servers
// SHOULD NOT issue access tokens with a lifetime that exceeds the
// validity period of the assertion by a significant period. In
// practice, that will usually mean that refresh tokens are not issued
// in response to assertion grant requests, and access tokens will be
// issued with a reasonably short lifetime. Clients can refresh an
// expired access token by requesting a new one using the same
// assertion, if it is still valid, or with a new assertion.
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwt);
OAuth2AccessTokenResponse tokenResponse = getTokenResponse(clientRegistration, jwtBearerGrantRequest);
return new OAuth2AuthorizedClient(clientRegistration, context.getPrincipal().getName(), tokenResponse.getAccessToken());
}
use of com.auth0.jwt.JWT in project spring-security by spring-projects.
the class JwtBearerGrantRequestEntityConverterTests method convertWhenGrantRequestValidThenConverts.
@SuppressWarnings("unchecked")
@Test
public void convertWhenGrantRequestValidThenConverts() {
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().authorizationGrantType(AuthorizationGrantType.JWT_BEARER).scope("read", "write").build();
// @formatter:on
Jwt jwtAssertion = TestJwts.jwt().build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwtAssertion);
RequestEntity<?> requestEntity = this.converter.convert(jwtBearerGrantRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString()).isEqualTo(clientRegistration.getProviderDetails().getTokenUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
assertThat(headers.getContentType()).isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.GRANT_TYPE)).isEqualTo(AuthorizationGrantType.JWT_BEARER.getValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.ASSERTION)).isEqualTo(jwtAssertion.getTokenValue());
assertThat(formParameters.getFirst(OAuth2ParameterNames.SCOPE)).isEqualTo("read write");
}
use of com.auth0.jwt.JWT in project spring-security by spring-projects.
the class JwtBearerGrantRequestEntityConverterTests method convertWhenParametersConverterSetThenCalled.
@Test
public void convertWhenParametersConverterSetThenCalled() {
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter1 = mock(Converter.class);
this.converter.setParametersConverter(parametersConverter1);
Converter<JwtBearerGrantRequest, MultiValueMap<String, String>> parametersConverter2 = mock(Converter.class);
this.converter.addParametersConverter(parametersConverter2);
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().authorizationGrantType(AuthorizationGrantType.JWT_BEARER).scope("read", "write").build();
// @formatter:on
Jwt jwtAssertion = TestJwts.jwt().build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwtAssertion);
this.converter.convert(jwtBearerGrantRequest);
InOrder inOrder = inOrder(parametersConverter1, parametersConverter2);
inOrder.verify(parametersConverter1).convert(any(JwtBearerGrantRequest.class));
inOrder.verify(parametersConverter2).convert(any(JwtBearerGrantRequest.class));
}
use of com.auth0.jwt.JWT in project spring-security by spring-projects.
the class JwtBearerGrantRequestEntityConverterTests method convertWhenHeadersConverterSetThenCalled.
@Test
public void convertWhenHeadersConverterSetThenCalled() {
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter1 = mock(Converter.class);
this.converter.setHeadersConverter(headersConverter1);
Converter<JwtBearerGrantRequest, HttpHeaders> headersConverter2 = mock(Converter.class);
this.converter.addHeadersConverter(headersConverter2);
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().authorizationGrantType(AuthorizationGrantType.JWT_BEARER).scope("read", "write").build();
// @formatter:on
Jwt jwtAssertion = TestJwts.jwt().build();
JwtBearerGrantRequest jwtBearerGrantRequest = new JwtBearerGrantRequest(clientRegistration, jwtAssertion);
this.converter.convert(jwtBearerGrantRequest);
InOrder inOrder = inOrder(headersConverter1, headersConverter2);
inOrder.verify(headersConverter1).convert(any(JwtBearerGrantRequest.class));
inOrder.verify(headersConverter2).convert(any(JwtBearerGrantRequest.class));
}
Aggregations