Search in sources :

Example 11 with JwtAuthenticationToken

use of org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken in project spring-security by spring-projects.

the class SecurityMockServerConfigurersJwtTests method mockJwtWhenUsingDefaultsTheCreatesJwtAuthentication.

@Test
public void mockJwtWhenUsingDefaultsTheCreatesJwtAuthentication() {
    this.client.mutateWith(SecurityMockServerConfigurers.mockJwt()).get().exchange().expectStatus().isOk();
    SecurityContext context = this.securityContextController.removeSecurityContext();
    assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
    JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication();
    assertThat(token.getAuthorities()).isNotEmpty();
    assertThat(token.getToken()).isNotNull();
    assertThat(token.getToken().getSubject()).isEqualTo("user");
    assertThat(token.getToken().getHeaders().get("alg")).isEqualTo("none");
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) SecurityContext(org.springframework.security.core.context.SecurityContext) Test(org.junit.jupiter.api.Test)

Example 12 with JwtAuthenticationToken

use of org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken in project spring-security by spring-projects.

the class OAuth2ResourceServerConfigurerTests method requestWhenJwtAuthenticationConverterConfiguredOnDslThenIsUsed.

@Test
public void requestWhenJwtAuthenticationConverterConfiguredOnDslThenIsUsed() throws Exception {
    this.spring.register(JwtDecoderConfig.class, JwtAuthenticationConverterConfiguredOnDsl.class, BasicController.class).autowire();
    Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter = this.spring.getContext().getBean(JwtAuthenticationConverterConfiguredOnDsl.class).getJwtAuthenticationConverter();
    given(jwtAuthenticationConverter.convert(JWT)).willReturn(JWT_AUTHENTICATION_TOKEN);
    JwtDecoder jwtDecoder = this.spring.getContext().getBean(JwtDecoder.class);
    given(jwtDecoder.decode(anyString())).willReturn(JWT);
    // @formatter:off
    this.mvc.perform(get("/").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk());
    // @formatter:on
    verify(jwtAuthenticationConverter).convert(JWT);
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) Test(org.junit.jupiter.api.Test)

Example 13 with JwtAuthenticationToken

use of org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken in project midpoint by Evolveum.

the class OidcResourceServerProvider method internalAuthentication.

@Override
protected Authentication internalAuthentication(Authentication authentication, List requireAssignment, AuthenticationChannel channel, Class focusType) throws AuthenticationException {
    Authentication token;
    if (authentication instanceof BearerTokenAuthenticationToken) {
        BearerTokenAuthenticationToken oidcAuthenticationToken = (BearerTokenAuthenticationToken) authentication;
        JwtAuthenticationToken jwtAuthentication;
        try {
            jwtAuthentication = (JwtAuthenticationToken) oidcProvider.authenticate(oidcAuthenticationToken);
        } catch (AuthenticationException e) {
            getAuditProvider().auditLoginFailure(null, null, createConnectEnvironment(getChannel()), e.getMessage());
            throw e;
        }
        HttpModuleAuthentication oidcModule = (HttpModuleAuthentication) AuthUtil.getProcessingModule();
        try {
            String username = jwtAuthentication.getName();
            if (StringUtils.isEmpty(username)) {
                LOGGER.error("Username from jwt token don't contains value");
                throw new AuthenticationServiceException("web.security.provider.invalid");
            }
            token = getPreAuthenticationToken(username, focusType, requireAssignment, channel);
        } catch (AuthenticationException e) {
            oidcModule.setAuthentication(oidcAuthenticationToken);
            LOGGER.info("Authentication with oidc module failed: {}", e.getMessage());
            throw e;
        }
    } else {
        LOGGER.error("Unsupported authentication {}", authentication);
        throw new AuthenticationServiceException("web.security.provider.unavailable");
    }
    MidPointPrincipal principal = (MidPointPrincipal) token.getPrincipal();
    LOGGER.debug("User '{}' authenticated ({}), authorities: {}", authentication.getPrincipal(), authentication.getClass().getSimpleName(), principal.getAuthorities());
    return token;
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) AuthenticationException(org.springframework.security.core.AuthenticationException) HttpModuleAuthentication(com.evolveum.midpoint.authentication.impl.module.authentication.HttpModuleAuthentication) Authentication(org.springframework.security.core.Authentication) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) HttpModuleAuthentication(com.evolveum.midpoint.authentication.impl.module.authentication.HttpModuleAuthentication) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 14 with JwtAuthenticationToken

use of org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken in project spring-security by spring-projects.

the class SecurityMockMvcRequestPostProcessorsJwtTests method jwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication.

@Test
public void jwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication() {
    String name = new String("user");
    jwt().jwt((jwt) -> jwt.subject(name)).postProcessRequest(this.request);
    verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request), any(HttpServletResponse.class));
    SecurityContext context = this.contextCaptor.getValue();
    assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
    JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication();
    assertThat(token.getToken().getSubject()).isSameAs(name);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) Mock(org.mockito.Mock) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) FilterChainProxy(org.springframework.security.web.FilterChainProxy) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DefaultSecurityFilterChain(org.springframework.security.web.DefaultSecurityFilterChain) SecurityContextPersistenceFilter(org.springframework.security.web.context.SecurityContextPersistenceFilter) Captor(org.mockito.Captor) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TestSecurityContextHolder(org.springframework.security.test.context.TestSecurityContextHolder) Jwt(org.springframework.security.oauth2.jwt.Jwt) MockServletContext(org.springframework.mock.web.MockServletContext) JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) SecurityMockMvcRequestPostProcessors.jwt(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) BeanIds(org.springframework.security.config.BeanIds) WebTestUtils(org.springframework.security.test.web.support.WebTestUtils) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) SecurityContext(org.springframework.security.core.context.SecurityContext) SecurityContextRepository(org.springframework.security.web.context.SecurityContextRepository) AnyRequestMatcher(org.springframework.security.web.util.matcher.AnyRequestMatcher) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) SecurityContext(org.springframework.security.core.context.SecurityContext) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 15 with JwtAuthenticationToken

use of org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken in project spring-security by spring-projects.

the class SecurityMockServerConfigurersJwtTests method mockJwtWhenProvidingPreparedJwtThenProducesJwtAuthentication.

@Test
public void mockJwtWhenProvidingPreparedJwtThenProducesJwtAuthentication() {
    Jwt originalToken = TestJwts.jwt().header("header1", "value1").subject("some_user").build();
    this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt(originalToken)).get().exchange().expectStatus().isOk();
    SecurityContext context = this.securityContextController.removeSecurityContext();
    assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
    JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication();
    assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user");
    assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token");
    assertThat(retrievedToken.getToken().getHeaders().get("header1")).isEqualTo("value1");
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) SecurityContext(org.springframework.security.core.context.SecurityContext) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.jupiter.api.Test)20 Jwt (org.springframework.security.oauth2.jwt.Jwt)16 JwtAuthenticationToken (org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken)11 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 SecurityContext (org.springframework.security.core.context.SecurityContext)6 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)3 BearerTokenAuthenticationToken (org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken)3 Arrays (java.util.Arrays)2 List (java.util.List)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2 Authentication (org.springframework.security.core.Authentication)2 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)2 JwtDecoder (org.springframework.security.oauth2.jwt.JwtDecoder)2 NimbusJwtDecoder (org.springframework.security.oauth2.jwt.NimbusJwtDecoder)2 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)2 HttpModuleAuthentication (com.evolveum.midpoint.authentication.impl.module.authentication.HttpModuleAuthentication)1 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 AfterEach (org.junit.jupiter.api.AfterEach)1 BeforeEach (org.junit.jupiter.api.BeforeEach)1