Search in sources :

Example 31 with OAuth2AuthenticationException

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

the class CrudControllerAdvice method handleOAuth2AuthenticationException.

@ExceptionHandler(OAuth2AuthenticationException.class)
@ResponseBody
public WebMessage handleOAuth2AuthenticationException(OAuth2AuthenticationException ex) {
    OAuth2Error error = ex.getError();
    if (error instanceof BearerTokenError) {
        BearerTokenError bearerTokenError = (BearerTokenError) error;
        HttpStatus status = ((BearerTokenError) error).getHttpStatus();
        return createWebMessage(bearerTokenError.getErrorCode(), bearerTokenError.getDescription(), Status.ERROR, status);
    }
    return unauthorized(ex.getMessage());
}
Also used : HttpStatus(org.springframework.http.HttpStatus) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) BearerTokenError(org.springframework.security.oauth2.server.resource.BearerTokenError) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 32 with OAuth2AuthenticationException

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

the class Dhis2ApiTokenFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String tokenKey;
    try {
        tokenKey = this.apiTokenResolver.resolve(request);
    } catch (OAuth2AuthenticationException invalid) {
        this.logger.debug("Sending to authentication entry point since failed to resolve API token", invalid);
        this.authenticationEntryPoint.commence(request, response, invalid);
        return;
    }
    if (tokenKey == null) {
        this.logger.debug("Did not process request since did not find API token in header or body");
        filterChain.doFilter(request, response);
        return;
    }
    final String hashedKey = apiTokenService.hashKey(tokenKey);
    tokenKey = null;
    try {
        ApiTokenAuthenticationToken authenticationToken = (ApiTokenAuthenticationToken) apiTokenAuthManager.authenticate(new ApiTokenAuthenticationToken(hashedKey));
        // Set values unique to each request
        authenticationToken.setDetails(this.authenticationDetailsSource.buildDetails(request));
        validateRequestRules(request, authenticationToken.getToken());
        authenticationToken.setAuthenticated(true);
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authenticationToken);
        SecurityContextHolder.setContext(context);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authenticationToken));
        }
        filterChain.doFilter(request, response);
    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();
        this.logger.debug("Failed to process authentication request", failed);
        this.authenticationFailureHandler.onAuthenticationFailure(request, response, failed);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) SecurityContext(org.springframework.security.core.context.SecurityContext) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 33 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationFilterTests method doFilterWhenAuthorizationResponseClientRegistrationNotFoundThenClientRegistrationNotFoundError.

// gh-5251
@Test
public void doFilterWhenAuthorizationResponseClientRegistrationNotFoundThenClientRegistrationNotFoundError() throws Exception {
    String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
    String state = "state";
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setServletPath(requestUri);
    request.addParameter(OAuth2ParameterNames.CODE, "code");
    request.addParameter(OAuth2ParameterNames.STATE, "state");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    // @formatter:off
    ClientRegistration registrationNotFound = ClientRegistration.withRegistrationId("registration-not-found").clientId("client-1").clientSecret("secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE).redirectUri("{baseUrl}/login/oauth2/code/{registrationId}").scope("user").authorizationUri("https://provider.com/oauth2/authorize").tokenUri("https://provider.com/oauth2/token").userInfoUri("https://provider.com/oauth2/user").userNameAttributeName("id").clientName("client-1").build();
    // @formatter:on
    this.setUpAuthorizationRequest(request, response, registrationNotFound, state);
    this.filter.doFilter(request, response, filterChain);
    ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
    verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
    assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
    OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue();
    assertThat(authenticationException.getError().getErrorCode()).isEqualTo("client_registration_not_found");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 34 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationFilterTests method doFilterWhenAuthorizationResponseInvalidThenInvalidRequestError.

@Test
public void doFilterWhenAuthorizationResponseInvalidThenInvalidRequestError() throws Exception {
    String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setServletPath(requestUri);
    // NOTE:
    // A valid Authorization Response contains either a 'code' or 'error' parameter.
    // Don't set it to force an invalid Authorization Response.
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.filter.doFilter(request, response, filterChain);
    ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
    verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
    assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
    OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue();
    assertThat(authenticationException.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 35 with OAuth2AuthenticationException

use of org.springframework.security.oauth2.core.OAuth2AuthenticationException in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationFilterTests method doFilterWhenAuthorizationResponseAuthorizationRequestNotFoundThenAuthorizationRequestNotFoundError.

@Test
public void doFilterWhenAuthorizationResponseAuthorizationRequestNotFoundThenAuthorizationRequestNotFoundError() throws Exception {
    String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
    MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
    request.setServletPath(requestUri);
    request.addParameter(OAuth2ParameterNames.CODE, "code");
    request.addParameter(OAuth2ParameterNames.STATE, "state");
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.filter.doFilter(request, response, filterChain);
    ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor.forClass(AuthenticationException.class);
    verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
    assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
    OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor.getValue();
    assertThat(authenticationException.getError().getErrorCode()).isEqualTo("authorization_request_not_found");
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FilterChain(jakarta.servlet.FilterChain) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)54 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)31 Test (org.junit.jupiter.api.Test)27 BearerTokenError (org.springframework.security.oauth2.server.resource.BearerTokenError)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)9 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)8 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)7 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)7 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)7 Map (java.util.Map)6 Authentication (org.springframework.security.core.Authentication)6 AuthenticationException (org.springframework.security.core.AuthenticationException)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)6 Mono (reactor.core.publisher.Mono)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Base64 (java.util.Base64)5