Search in sources :

Example 91 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationProcessingFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;
    try {
        Authentication authentication = tokenExtractor.extract(request);
        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            Authentication authResult = authenticationManager.authenticate(authentication);
            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }
            eventPublisher.publishAuthenticationSuccess(authResult);
            SecurityContextHolder.getContext().setAuthentication(authResult);
        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();
        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
        authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(failed.getMessage(), failed));
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 92 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security-oauth by spring-projects.

the class ClientCredentialsTokenEndpointFilter method afterPropertiesSet.

@Override
public void afterPropertiesSet() {
    super.afterPropertiesSet();
    setAuthenticationFailureHandler(new AuthenticationFailureHandler() {

        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
            if (exception instanceof BadCredentialsException) {
                exception = new BadCredentialsException(exception.getMessage(), new BadClientCredentialsException());
            }
            authenticationEntryPoint.commence(request, response, exception);
        }
    });
    setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {

        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // no-op - just allow filter chain to continue to token endpoint
        }
    });
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) BadClientCredentialsException(org.springframework.security.oauth2.common.exceptions.BadClientCredentialsException) AuthenticationSuccessHandler(org.springframework.security.web.authentication.AuthenticationSuccessHandler) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) AuthenticationFailureHandler(org.springframework.security.web.authentication.AuthenticationFailureHandler) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 93 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security-oauth by spring-projects.

the class ClientCredentialsTokenEndpointFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) {
        throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[] { "POST" });
    }
    String clientId = request.getParameter("client_id");
    String clientSecret = request.getParameter("client_secret");
    // If the request is already authenticated we can assume that this
    // filter is not needed
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        return authentication;
    }
    if (clientId == null) {
        throw new BadCredentialsException("No client credentials presented");
    }
    if (clientSecret == null) {
        clientSecret = "";
    }
    clientId = clientId.trim();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
    return this.getAuthenticationManager().authenticate(authRequest);
}
Also used : Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException)

Example 94 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationEntryPointTests method testTypeName.

@Test
public void testTypeName() throws Exception {
    entryPoint.setTypeName("Foo");
    entryPoint.commence(request, response, new BadCredentialsException("Bad"));
    assertEquals("Foo realm=\"foo\", error=\"unauthorized\", error_description=\"Bad\"", response.getHeader("WWW-Authenticate"));
}
Also used : BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Example 95 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-boot by spring-projects.

the class SecurityAutoConfigurationTests method pingAuthenticationListener.

private void pingAuthenticationListener() {
    AuthenticationListener listener = new AuthenticationListener();
    this.context.addApplicationListener(listener);
    AuthenticationManager manager = this.context.getBean(AuthenticationManager.class);
    try {
        manager.authenticate(new UsernamePasswordAuthenticationToken("foo", "wrong"));
        fail("Expected BadCredentialsException");
    } catch (BadCredentialsException e) {
    // expected
    }
    assertThat(listener.event).isInstanceOf(AuthenticationFailureBadCredentialsEvent.class);
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)174 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)32 Test (org.junit.Test)26 AuthenticationException (org.springframework.security.core.AuthenticationException)24 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)22 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 FilterChain (jakarta.servlet.FilterChain)10 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)10 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7