Search in sources :

Example 21 with JwtDecoder

use of org.springframework.security.oauth2.jwt.JwtDecoder in project dhis2-core by dhis2.

the class Dhis2JwtAuthenticationManagerResolver method getAuthenticationManager.

/**
 * Looks for a DhisOidcClientRegistration in the DhisOidcProviderRepository
 * that matches the input JWT "issuer". It creates a new
 * DhisJwtAuthenticationProvider if it finds a matching config.
 * <p>
 * The DhisJwtAuthenticationProvider is configured with a custom
 * {@link Converter} that "converts" the incoming JWT token into a
 * {@link DhisJwtAuthenticationToken}.
 * <p>
 * It also configures a JWT decoder that "decodes" incoming JSON string into
 * a JWT token ({@link Jwt}
 *
 * @param issuer JWT issuer to look up
 *
 * @return a DhisJwtAuthenticationProvider
 */
private AuthenticationManager getAuthenticationManager(String issuer) {
    return this.authenticationManagers.computeIfAbsent(issuer, s -> {
        DhisOidcClientRegistration clientRegistration = clientRegistrationRepository.findByIssuerUri(issuer);
        if (clientRegistration == null) {
            throw new InvalidBearerTokenException("Invalid issuer");
        }
        Converter<Jwt, DhisJwtAuthenticationToken> authConverter = getConverter(clientRegistration);
        JwtDecoder decoder = getDecoder(issuer);
        return new DhisJwtAuthenticationProvider(decoder, authConverter)::authenticate;
    });
}
Also used : DhisOidcClientRegistration(org.hisp.dhis.security.oidc.DhisOidcClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) InvalidBearerTokenException(org.springframework.security.oauth2.server.resource.InvalidBearerTokenException)

Example 22 with JwtDecoder

use of org.springframework.security.oauth2.jwt.JwtDecoder in project spring-security by spring-projects.

the class OAuth2ResourceServerConfigurerTests method requestWhenBearerTokenResolverAllowsQueryParameterAndRequestContainsTwoTokensThenInvalidRequest.

@Test
public void requestWhenBearerTokenResolverAllowsQueryParameterAndRequestContainsTwoTokensThenInvalidRequest() throws Exception {
    this.spring.register(AllowBearerTokenAsQueryParameterConfig.class, JwtDecoderConfig.class, BasicController.class).autowire();
    JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
    given(decoder.decode(anyString())).willReturn(JWT);
    // @formatter:off
    MockHttpServletRequestBuilder request = get("/authenticated").with(bearerToken(JWT_TOKEN)).param("access_token", JWT_TOKEN);
    this.mvc.perform(request).andExpect(status().isBadRequest()).andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("invalid_request")));
// @formatter:on
}
Also used : NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) Test(org.junit.jupiter.api.Test)

Example 23 with JwtDecoder

use of org.springframework.security.oauth2.jwt.JwtDecoder in project spring-security by spring-projects.

the class OAuth2ResourceServerConfigurerTests method requestWhenFormLoginAndResourceServerEntryPointsThenSessionCreatedByRequest.

@Test
public void requestWhenFormLoginAndResourceServerEntryPointsThenSessionCreatedByRequest() throws Exception {
    this.spring.register(FormAndResourceServerConfig.class, JwtDecoderConfig.class).autowire();
    JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
    given(decoder.decode(anyString())).willThrow(BadJwtException.class);
    // @formatter:off
    MvcResult result = this.mvc.perform(get("/authenticated").header("Accept", "text/html")).andExpect(status().isFound()).andExpect(redirectedUrl("http://localhost/login")).andReturn();
    // @formatter:on
    assertThat(result.getRequest().getSession(false)).isNotNull();
    // @formatter:off
    result = this.mvc.perform(get("/authenticated").with(bearerToken("token"))).andExpect(status().isUnauthorized()).andReturn();
    // @formatter:on
    assertThat(result.getRequest().getSession(false)).isNull();
}
Also used : NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) MvcResult(org.springframework.test.web.servlet.MvcResult) Test(org.junit.jupiter.api.Test)

Example 24 with JwtDecoder

use of org.springframework.security.oauth2.jwt.JwtDecoder in project spring-security by spring-projects.

the class OAuth2ResourceServerConfigurerTests method requestWhenDefaultAndResourceServerAccessDeniedHandlersThenMatchedByRequest.

@Test
public void requestWhenDefaultAndResourceServerAccessDeniedHandlersThenMatchedByRequest() throws Exception {
    this.spring.register(ExceptionHandlingAndResourceServerWithAccessDeniedHandlerConfig.class, JwtDecoderConfig.class).autowire();
    JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
    given(decoder.decode(anyString())).willReturn(JWT);
    // @formatter:off
    this.mvc.perform(get("/authenticated").with(httpBasic("basic-user", "basic-password"))).andExpect(status().isForbidden()).andExpect(header().doesNotExist(HttpHeaders.WWW_AUTHENTICATE));
    this.mvc.perform(get("/authenticated").with(bearerToken("insufficiently_scoped"))).andExpect(status().isForbidden()).andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer")));
// @formatter:on
}
Also used : NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) Test(org.junit.jupiter.api.Test)

Example 25 with JwtDecoder

use of org.springframework.security.oauth2.jwt.JwtDecoder in project spring-security by spring-projects.

the class OAuth2ResourceServerConfigurerTests method requestWhenCustomAuthenticationDetailsSourceThenUsed.

@Test
public void requestWhenCustomAuthenticationDetailsSourceThenUsed() throws Exception {
    this.spring.register(CustomAuthenticationDetailsSource.class, JwtDecoderConfig.class, BasicController.class).autowire();
    JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
    given(decoder.decode(anyString())).willReturn(JWT);
    this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk()).andExpect(content().string(JWT_SUBJECT));
    verifyBean(AuthenticationDetailsSource.class).buildDetails(any());
}
Also used : AuthenticationDetailsSource(org.springframework.security.authentication.AuthenticationDetailsSource) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)37 NimbusJwtDecoder (org.springframework.security.oauth2.jwt.NimbusJwtDecoder)34 JwtDecoder (org.springframework.security.oauth2.jwt.JwtDecoder)33 Jwt (org.springframework.security.oauth2.jwt.Jwt)9 GenericWebApplicationContext (org.springframework.web.context.support.GenericWebApplicationContext)6 Map (java.util.Map)4 ApplicationContext (org.springframework.context.ApplicationContext)4 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)4 RSAKey (com.nimbusds.jose.jwk.RSAKey)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 Base64 (java.util.Base64)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)3 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)3 BDDMockito.given (org.mockito.BDDMockito.given)3 Mockito.mock (org.mockito.Mockito.mock)3 GenericApplicationContext (org.springframework.context.support.GenericApplicationContext)3 Converter (org.springframework.core.convert.converter.Converter)3 HttpStatus (org.springframework.http.HttpStatus)3 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)2