Search in sources :

Example 26 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project midpoint by Evolveum.

the class OidcClientProvider method internalAuthentication.

@Override
protected Authentication internalAuthentication(Authentication authentication, List requireAssignment, AuthenticationChannel channel, Class focusType) throws AuthenticationException {
    Authentication token;
    if (authentication instanceof OAuth2LoginAuthenticationToken) {
        OAuth2LoginAuthenticationToken oidcAuthenticationToken = (OAuth2LoginAuthenticationToken) authentication;
        OAuth2LoginAuthenticationToken oidcAuthentication;
        try {
            oidcAuthentication = (OAuth2LoginAuthenticationToken) oidcProvider.authenticate(oidcAuthenticationToken);
        } catch (AuthenticationException e) {
            getAuditProvider().auditLoginFailure(null, null, createConnectEnvironment(getChannel()), e.getMessage());
            throw e;
        }
        OidcClientModuleAuthenticationImpl oidcModule = (OidcClientModuleAuthenticationImpl) AuthUtil.getProcessingModule();
        try {
            String enteredUsername = oidcAuthentication.getName();
            if (StringUtils.isEmpty(enteredUsername)) {
                LOGGER.error("Oidc attribute, which define username don't contains value");
                throw new AuthenticationServiceException("web.security.provider.invalid");
            }
            token = getPreAuthenticationToken(enteredUsername, 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 : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) OidcClientModuleAuthenticationImpl(com.evolveum.midpoint.authentication.impl.module.authentication.OidcClientModuleAuthenticationImpl) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal)

Example 27 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project dhis2-core by dhis2.

the class AuthenticationListener method handleAuthenticationFailure.

@EventListener
public void handleAuthenticationFailure(AbstractAuthenticationFailureEvent event) {
    Authentication auth = event.getAuthentication();
    String username = event.getAuthentication().getName();
    Object details = auth.getDetails();
    if (details != null && TwoFactorWebAuthenticationDetails.class.isAssignableFrom(details.getClass())) {
        TwoFactorWebAuthenticationDetails authDetails = (TwoFactorWebAuthenticationDetails) details;
        log.debug(String.format("Login attempt failed for remote IP: %s", authDetails.getIp()));
    }
    if (OAuth2LoginAuthenticationToken.class.isAssignableFrom(auth.getClass())) {
        OAuth2LoginAuthenticationToken authenticationToken = (OAuth2LoginAuthenticationToken) auth;
        DhisOidcUser principal = (DhisOidcUser) authenticationToken.getPrincipal();
        if (principal != null) {
            username = principal.getUser().getUsername();
        }
        WebAuthenticationDetails tokenDetails = (WebAuthenticationDetails) authenticationToken.getDetails();
        String remoteAddress = tokenDetails.getRemoteAddress();
        log.debug(String.format("OIDC login attempt failed for remote IP: %s", remoteAddress));
    }
    securityService.registerFailedLogin(username);
}
Also used : TwoFactorWebAuthenticationDetails(org.hisp.dhis.security.spring2fa.TwoFactorWebAuthenticationDetails) DhisOidcUser(org.hisp.dhis.security.oidc.DhisOidcUser) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) TwoFactorWebAuthenticationDetails(org.hisp.dhis.security.spring2fa.TwoFactorWebAuthenticationDetails) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) EventListener(org.springframework.context.event.EventListener)

Example 28 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationProviderTests method authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest.

// gh-5368
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
    OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    OAuth2User principal = mock(OAuth2User.class);
    List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
    given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
    ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
    given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
    this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
    assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) HashMap(java.util.HashMap) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) LinkedHashSet(java.util.LinkedHashSet) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Set(java.util.Set) Instant(java.time.Instant) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) List(java.util.List) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2UserService(org.springframework.security.oauth2.client.userinfo.OAuth2UserService) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) Mockito.mock(org.mockito.Mockito.mock) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) List(java.util.List) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) Test(org.junit.jupiter.api.Test)

Example 29 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationProviderTests method authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthenticationException.

@Test
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthenticationException() {
    OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890").build();
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse);
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange))).withMessageContaining("invalid_state_parameter");
}
Also used : OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) Test(org.junit.jupiter.api.Test)

Example 30 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationFilterTests method doFilterWhenAuthorizationResponseHasDefaultPort443ThenRedirectUriMatchingExcludesPort.

// gh-5890
@Test
public void doFilterWhenAuthorizationResponseHasDefaultPort443ThenRedirectUriMatchingExcludesPort() throws Exception {
    String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
    String state = "state";
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setScheme("https");
    request.setServerName("example.com");
    request.setServerPort(443);
    request.setServletPath(requestUri);
    request.addParameter(OAuth2ParameterNames.CODE, "code");
    request.addParameter(OAuth2ParameterNames.STATE, "state");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.setUpAuthorizationRequest(request, response, this.registration2, state);
    this.setUpAuthenticationResult(this.registration2);
    this.filter.doFilter(request, response, filterChain);
    ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
    OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue();
    OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest();
    OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse();
    String expectedRedirectUri = "https://example.com/login/oauth2/code/registration-id-2";
    assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
    assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Authentication(org.springframework.security.core.Authentication) FilterChain(jakarta.servlet.FilterChain) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)29 Test (org.junit.jupiter.api.Test)25 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)23 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)21 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)20 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)16 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)15 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)15 Authentication (org.springframework.security.core.Authentication)13 HashMap (java.util.HashMap)12 Map (java.util.Map)12 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)11 BDDMockito.given (org.mockito.BDDMockito.given)11 Mockito.mock (org.mockito.Mockito.mock)11 Answer (org.mockito.stubbing.Answer)11 AuthorityUtils (org.springframework.security.core.authority.AuthorityUtils)11 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)11