Search in sources :

Example 86 with JWT

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());
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Jwt(org.springframework.security.oauth2.jwt.Jwt) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 87 with JWT

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());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Nullable(org.springframework.lang.Nullable)

Example 88 with JWT

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");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) MultiValueMap(org.springframework.util.MultiValueMap) Test(org.junit.jupiter.api.Test)

Example 89 with JWT

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));
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) InOrder(org.mockito.InOrder) Jwt(org.springframework.security.oauth2.jwt.Jwt) MultiValueMap(org.springframework.util.MultiValueMap) Test(org.junit.jupiter.api.Test)

Example 90 with JWT

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));
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) InOrder(org.mockito.InOrder) Jwt(org.springframework.security.oauth2.jwt.Jwt) Test(org.junit.jupiter.api.Test)

Aggregations

Jwt (org.springframework.security.oauth2.jwt.Jwt)99 Test (org.junit.jupiter.api.Test)80 GrantedAuthority (org.springframework.security.core.GrantedAuthority)51 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)23 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)19 Arrays (java.util.Arrays)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)18 List (java.util.List)17 Algorithm (com.auth0.jwt.algorithms.Algorithm)16 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)16 Authentication (org.springframework.security.core.Authentication)16 Test (org.junit.Test)14 HashMap (java.util.HashMap)13 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 Instant (java.time.Instant)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 JWTVerifier (com.auth0.jwt.JWTVerifier)10