Search in sources :

Example 26 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ORCID-Source by ORCID.

the class RevokeTokenEndpointFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws AuthenticationException, IOException, ServletException {
    String clientId = request.getParameter("client_id");
    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        throw new ServletException("RevokeTokenEndpointFilter just supports HTTP requests");
    }
    if (clientId != null && (OrcidStringUtils.isValidOrcid(clientId) || OrcidStringUtils.isClientId(clientId))) {
        String clientSecret = request.getParameter("client_secret");
        if (clientSecret == null) {
            clientSecret = "";
        }
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
        try {
            Authentication auth = clientAuthenticationProvider.authenticate(authRequest);
            SecurityContextHolder.getContext().setAuthentication(auth);
        } catch (AuthenticationException failed) {
            oauthAuthenticationEntryPoint.commence((HttpServletRequest) request, (HttpServletResponse) response, failed);
            return;
        }
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 27 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project summerb by skarpushin.

the class RestExceptionTranslator method determineFailureResult.

private DtoBase determineFailureResult(Exception ex, HttpServletRequest request, HttpServletResponse response) {
    // first see if it is FVE
    FieldValidationException fve = ExceptionUtils.findExceptionOfType(ex, FieldValidationException.class);
    if (fve != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return fve.getErrorDescriptionObject();
    }
    boolean translateAuthErrors = Boolean.TRUE.equals(Boolean.valueOf(request.getHeader(X_TRANSLATE_AUTHORIZATION_ERRORS)));
    GenericServerErrorResult ret = null;
    if (translateAuthErrors) {
        ret = new GenericServerErrorResult(exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale()), new ExceptionInfo(ex));
    }
    NotAuthorizedException naex = ExceptionUtils.findExceptionOfType(ex, NotAuthorizedException.class);
    if (naex != null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return ret != null ? ret : naex.getResult();
    }
    AuthenticationException ae = ExceptionUtils.findExceptionOfType(ex, AuthenticationException.class);
    if (ae != null) {
        // NOTE: See how we did that in AuthenticationFailureHandlerImpl...
        // Looks like we need to augment our custom RestLoginFilter so it
        // will put username to request
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return ret != null ? ret : new NotAuthorizedResult("(username not resolved)", SecurityMessageCodes.AUTH_FATAL);
    }
    AccessDeniedException ade = ExceptionUtils.findExceptionOfType(ex, AccessDeniedException.class);
    if (ade != null) {
        if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication())) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.LOGIN_REQUIRED);
        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.ACCESS_DENIED);
    }
    CurrentUserNotFoundException cunfe = ExceptionUtils.findExceptionOfType(ex, CurrentUserNotFoundException.class);
    if (cunfe != null) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.LOGIN_REQUIRED);
    }
    // TODO: Do we really need to send whole stack trace to client ??? I think we
    // should do it only during development
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return new GenericServerErrorResult(exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale()), new ExceptionInfo(ex));
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) AuthenticationException(org.springframework.security.core.AuthenticationException) NotAuthorizedResult(org.summerb.approaches.security.api.dto.NotAuthorizedResult) CurrentUserNotFoundException(org.summerb.approaches.security.api.CurrentUserNotFoundException) NotAuthorizedException(org.summerb.approaches.security.api.exceptions.NotAuthorizedException) GenericServerErrorResult(org.summerb.utils.exceptions.dto.GenericServerErrorResult) ExceptionInfo(org.summerb.utils.exceptions.dto.ExceptionInfo)

Example 28 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project summerb by skarpushin.

the class RestLoginFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (!requiresAuthentication(request, response)) {
        chain.doFilter(request, response);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Request is to process authentication");
    }
    Authentication authResult;
    try {
        authResult = attemptAuthentication(request, response);
        if (authResult == null) {
            return;
        }
        sessionAuthenticationStrategy.onAuthentication(authResult, request, response);
    } catch (AuthenticationException failed) {
        unsuccessfulAuthentication(request, response, failed);
        return;
    }
    successfulAuthentication(request, response, authResult);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 29 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project spring-security-oauth by spring-projects.

the class OAuthProcessingFilterTests method testDoFilter.

/**
 * tests do filter.
 */
@Test
public void testDoFilter() throws Exception {
    final boolean[] triggers = new boolean[2];
    Arrays.fill(triggers, false);
    OAuthProviderProcessingFilter filter = new OAuthProviderProcessingFilter() {

        @Override
        protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
            return true;
        }

        protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
            chain.doFilter(null, null);
        }

        @Override
        protected void validateOAuthParams(ConsumerDetails consumerDetails, Map<String, String> oauthParams) throws InvalidOAuthParametersException {
            triggers[0] = true;
        }

        @Override
        protected void validateSignature(ConsumerAuthentication authentication) throws AuthenticationException {
            triggers[1] = true;
        }

        @Override
        protected void fail(HttpServletRequest request, HttpServletResponse response, AuthenticationException failure) throws IOException, ServletException {
            throw failure;
        }

        @Override
        protected Object createDetails(HttpServletRequest request, ConsumerDetails consumerDetails) {
            return null;
        }

        @Override
        protected void resetPreviousAuthentication(Authentication previousAuthentication) {
        // no-op
        }

        @Override
        protected boolean skipProcessing(HttpServletRequest request) {
            return false;
        }
    };
    filter.setProviderSupport(providerSupport);
    filter.setConsumerDetailsService(consumerDetailsService);
    filter.setNonceServices(nonceServices);
    filter.setSignatureMethodFactory(signatureFactory);
    filter.setTokenServices(tokenServices);
    when(request.getMethod()).thenReturn("DELETE");
    filter.doFilter(request, response, filterChain);
    verify(response).sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    assertFalse(triggers[0]);
    assertFalse(triggers[1]);
    Arrays.fill(triggers, false);
    when(request.getMethod()).thenReturn("GET");
    HashMap<String, String> requestParams = new HashMap<String, String>();
    when(providerSupport.parseParameters(request)).thenReturn(requestParams);
    try {
        filter.doFilter(request, response, filterChain);
        fail("should have required a consumer key.");
    } catch (InvalidOAuthParametersException e) {
        assertFalse(triggers[0]);
        assertFalse(triggers[1]);
        Arrays.fill(triggers, false);
    }
    when(request.getMethod()).thenReturn("GET");
    requestParams = new HashMap<String, String>();
    requestParams.put(OAuthConsumerParameter.oauth_consumer_key.toString(), "consumerKey");
    when(providerSupport.parseParameters(request)).thenReturn(requestParams);
    ConsumerDetails consumerDetails = mock(ConsumerDetails.class);
    when(consumerDetails.getAuthorities()).thenReturn(new ArrayList<GrantedAuthority>());
    when(consumerDetailsService.loadConsumerByConsumerKey("consumerKey")).thenReturn(consumerDetails);
    requestParams.put(OAuthConsumerParameter.oauth_token.toString(), "tokenvalue");
    requestParams.put(OAuthConsumerParameter.oauth_signature_method.toString(), "methodvalue");
    requestParams.put(OAuthConsumerParameter.oauth_signature.toString(), "signaturevalue");
    when(providerSupport.getSignatureBaseString(request)).thenReturn("sigbasestring");
    filter.doFilter(request, response, filterChain);
    verify(filterChain).doFilter(null, null);
    verify(request).setAttribute(OAuthProviderProcessingFilter.OAUTH_PROCESSING_HANDLED, Boolean.TRUE);
    ConsumerAuthentication authentication = (ConsumerAuthentication) SecurityContextHolder.getContext().getAuthentication();
    assertSame(consumerDetails, authentication.getConsumerDetails());
    assertEquals("tokenvalue", authentication.getConsumerCredentials().getToken());
    assertEquals("methodvalue", authentication.getConsumerCredentials().getSignatureMethod());
    assertEquals("signaturevalue", authentication.getConsumerCredentials().getSignature());
    assertEquals("sigbasestring", authentication.getConsumerCredentials().getSignatureBaseString());
    assertEquals("consumerKey", authentication.getConsumerCredentials().getConsumerKey());
    assertTrue(authentication.isSignatureValidated());
    SecurityContextHolder.getContext().setAuthentication(null);
    assertTrue(triggers[0]);
    assertTrue(triggers[1]);
    Arrays.fill(triggers, false);
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) HashMap(java.util.HashMap) FilterChain(javax.servlet.FilterChain) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) Authentication(org.springframework.security.core.Authentication) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) HashMap(java.util.HashMap) Map(java.util.Map) ConsumerDetails(org.springframework.security.oauth.provider.ConsumerDetails) Test(org.junit.Test)

Example 30 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project spring-security-oauth by spring-projects.

the class OAuthProviderProcessingFilter method doFilter.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (!skipProcessing(request)) {
        if (requiresAuthentication(request, response, chain)) {
            if (!allowMethod(request.getMethod().toUpperCase())) {
                if (log.isDebugEnabled()) {
                    log.debug("Method " + request.getMethod() + " not supported.");
                }
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                return;
            }
            try {
                Map<String, String> oauthParams = getProviderSupport().parseParameters(request);
                if (parametersAreAdequate(oauthParams)) {
                    if (log.isDebugEnabled()) {
                        StringBuilder builder = new StringBuilder("OAuth parameters parsed: ");
                        for (String param : oauthParams.keySet()) {
                            builder.append(param).append('=').append(oauthParams.get(param)).append(' ');
                        }
                        log.debug(builder.toString());
                    }
                    String consumerKey = oauthParams.get(OAuthConsumerParameter.oauth_consumer_key.toString());
                    if (consumerKey == null) {
                        throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.missingConsumerKey", "Missing consumer key."));
                    }
                    // load the consumer details.
                    ConsumerDetails consumerDetails = getConsumerDetailsService().loadConsumerByConsumerKey(consumerKey);
                    if (log.isDebugEnabled()) {
                        log.debug("Consumer details loaded for " + consumerKey + ": " + consumerDetails);
                    }
                    // validate the parameters for the consumer.
                    validateOAuthParams(consumerDetails, oauthParams);
                    if (log.isDebugEnabled()) {
                        log.debug("Parameters validated.");
                    }
                    // extract the credentials.
                    String token = oauthParams.get(OAuthConsumerParameter.oauth_token.toString());
                    String signatureMethod = oauthParams.get(OAuthConsumerParameter.oauth_signature_method.toString());
                    String signature = oauthParams.get(OAuthConsumerParameter.oauth_signature.toString());
                    String signatureBaseString = getProviderSupport().getSignatureBaseString(request);
                    ConsumerCredentials credentials = new ConsumerCredentials(consumerKey, signature, signatureMethod, signatureBaseString, token);
                    // create an authentication request.
                    ConsumerAuthentication authentication = new ConsumerAuthentication(consumerDetails, credentials, oauthParams);
                    authentication.setDetails(createDetails(request, consumerDetails));
                    Authentication previousAuthentication = SecurityContextHolder.getContext().getAuthentication();
                    try {
                        // set the authentication request (unauthenticated) into the context.
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        // validate the signature.
                        validateSignature(authentication);
                        // mark the authentication request as validated.
                        authentication.setSignatureValidated(true);
                        // mark that processing has been handled.
                        request.setAttribute(OAUTH_PROCESSING_HANDLED, Boolean.TRUE);
                        if (log.isDebugEnabled()) {
                            log.debug("Signature validated.");
                        }
                        // go.
                        onValidSignature(request, response, chain);
                    } finally {
                        // clear out the consumer authentication to make sure it doesn't get cached.
                        resetPreviousAuthentication(previousAuthentication);
                    }
                } else if (!isIgnoreInadequateCredentials()) {
                    throw new InvalidOAuthParametersException(messages.getMessage("OAuthProcessingFilter.missingCredentials", "Inadequate OAuth consumer credentials."));
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Supplied OAuth parameters are inadequate. Ignoring.");
                    }
                    chain.doFilter(request, response);
                }
            } catch (AuthenticationException ae) {
                fail(request, response, ae);
            } catch (ServletException e) {
                if (e.getRootCause() instanceof AuthenticationException) {
                    fail(request, response, (AuthenticationException) e.getRootCause());
                } else {
                    throw e;
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Request does not require authentication.  OAuth processing skipped.");
            }
            chain.doFilter(servletRequest, servletResponse);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Processing explicitly skipped.");
        }
        chain.doFilter(servletRequest, servletResponse);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) ConsumerCredentials(org.springframework.security.oauth.provider.ConsumerCredentials) AuthenticationException(org.springframework.security.core.AuthenticationException) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) Authentication(org.springframework.security.core.Authentication) ConsumerAuthentication(org.springframework.security.oauth.provider.ConsumerAuthentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) ConsumerDetails(org.springframework.security.oauth.provider.ConsumerDetails)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)152 Authentication (org.springframework.security.core.Authentication)79 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)42 HttpServletRequest (javax.servlet.http.HttpServletRequest)26 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)24 HttpServletResponse (javax.servlet.http.HttpServletResponse)23 Test (org.junit.Test)20 Test (org.junit.jupiter.api.Test)19 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)14 IOException (java.io.IOException)13 ServletException (javax.servlet.ServletException)12 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)9 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)8 GrantedAuthority (org.springframework.security.core.GrantedAuthority)8 Map (java.util.Map)7 UserDetails (org.springframework.security.core.userdetails.UserDetails)7 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)6 HashMap (java.util.HashMap)6