Search in sources :

Example 71 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project gocd by gocd.

the class AbstractBasicAuthenticationFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    try {
        if (isPreviouslyAuthenticated(request)) {
            LOGGER.debug("Request is already authenticated.");
            filterChain.doFilter(request, response);
            return;
        }
        final UsernamePassword credential = BasicAuthHeaderExtractor.extractBasicAuthenticationCredentials(request.getHeader("Authorization"));
        if (credential != null) {
            LOGGER.debug("[Basic Authentication] Authorization header found for user '{}'", credential.getUsername());
        }
        if (securityService.isSecurityEnabled()) {
            LOGGER.debug("Security is enabled.");
            filterWhenSecurityEnabled(request, response, filterChain, credential);
        } else {
            LOGGER.debug("Security is disabled.");
            filterWhenSecurityDisabled(request, response, filterChain, credential);
        }
    } catch (AuthenticationException e) {
        onAuthenticationFailure(request, response, e.getMessage());
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) UsernamePassword(com.thoughtworks.go.server.newsecurity.models.UsernamePassword)

Example 72 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project gocd by gocd.

the class AccessTokenAuthenticationFilter method filterWhenSecurityEnabled.

private void filterWhenSecurityEnabled(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, AccessTokenCredential accessTokenCredential) throws IOException, ServletException {
    if (accessTokenCredential == null) {
        LOGGER.debug("Bearer auth credentials are not provided in request.");
        filterChain.doFilter(request, response);
    } else {
        accessTokenService.updateLastUsedCacheWith(accessTokenCredential.getAccessToken());
        ACCESS_TOKEN_LOGGER.debug("[Bearer Token Authentication] Authenticating bearer token for: " + "GoCD User: '{}'. " + "GoCD API endpoint: '{}', " + "API Client: '{}', " + "Is Admin Scoped Token: '{}', " + "Current Time: '{}'.", accessTokenCredential.getAccessToken().getUsername(), request.getRequestURI(), request.getHeader("User-Agent"), securityService.isUserAdmin(new Username(accessTokenCredential.getAccessToken().getUsername())), new Timestamp(System.currentTimeMillis()));
        try {
            String authConfigId = accessTokenCredential.getAccessToken().getAuthConfigId();
            SecurityAuthConfig authConfig = securityAuthConfigService.findProfile(authConfigId);
            if (authConfig == null) {
                String errorMessage = String.format("Can not find authorization configuration \"%s\" to which the requested personal access token belongs. Authorization Configuration \"%s\" might have been renamed or deleted. Please revoke the existing token and create a new one for the same.", authConfigId, authConfigId);
                onAuthenticationFailure(request, response, errorMessage);
                return;
            }
            final AuthenticationToken<AccessTokenCredential> authenticationToken = authenticationProvider.authenticateUser(accessTokenCredential, authConfig);
            if (authenticationToken == null) {
                onAuthenticationFailure(request, response, BAD_CREDENTIALS_MSG);
            } else {
                SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
                filterChain.doFilter(request, response);
            }
        } catch (AuthenticationException e) {
            LOGGER.debug("Failed to authenticate user.", e);
            onAuthenticationFailure(request, response, e.getMessage());
        }
    }
}
Also used : SecurityAuthConfig(com.thoughtworks.go.config.SecurityAuthConfig) Username(com.thoughtworks.go.server.domain.Username) AuthenticationException(org.springframework.security.core.AuthenticationException) Timestamp(java.sql.Timestamp) AccessTokenCredential(com.thoughtworks.go.server.newsecurity.models.AccessTokenCredential)

Example 73 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project cas by apereo.

the class EndpointLdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    try {
        val username = authentication.getPrincipal().toString();
        val credentials = authentication.getCredentials();
        val password = Optional.ofNullable(credentials).map(Object::toString).orElse(null);
        if (StringUtils.isBlank(password)) {
            throw new IllegalArgumentException("Password cannot be blank");
        }
        LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
        val request = new AuthenticationRequest(username, new Credential(password), ReturnAttributes.ALL.value());
        LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
        val response = this.authenticator.authenticate(request);
        LOGGER.debug("LDAP response: [{}]", response);
        if (response.isSuccess()) {
            val roles = securityProperties.getUser().getRoles();
            if (roles.isEmpty()) {
                LOGGER.info("No user security roles are defined to enable authorization. User [{}] is considered authorized", username);
                return generateAuthenticationToken(authentication, new ArrayList<>(0));
            }
            val entry = response.getLdapEntry();
            val profile = new CommonProfile();
            profile.setId(username);
            entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
            LOGGER.debug("Collected user profile [{}]", profile);
            val context = new JEEContext(HttpRequestUtils.getHttpServletRequestFromRequestAttributes(), HttpRequestUtils.getHttpServletResponseFromRequestAttributes());
            val authZGen = buildAuthorizationGenerator();
            authZGen.generate(context, JEESessionStore.INSTANCE, profile);
            LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
            val authorities = profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toCollection(ArrayList::new));
            LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
            val authorizer = new RequireAnyRoleAuthorizer(roles);
            LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
            if (authorizer.isAllAuthorized(context, JEESessionStore.INSTANCE, CollectionUtils.wrap(profile))) {
                return generateAuthenticationToken(authentication, authorities);
            }
            LOGGER.warn("User [{}] is not authorized to access the requested resource allowed to roles [{}]", username, authorizer.getElements());
        } else {
            LOGGER.warn("LDAP authentication response produced no results for [{}]", username);
        }
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
    }
    throw new BadCredentialsException("Could not authenticate provided credentials");
}
Also used : lombok.val(lombok.val) Credential(org.ldaptive.Credential) CommonProfile(org.pac4j.core.profile.CommonProfile) JEEContext(org.pac4j.core.context.JEEContext) AuthenticationRequest(org.ldaptive.auth.AuthenticationRequest) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 74 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project CzechIdMng by bcvsolutions.

the class AuthenticationExceptionContextTest method testDisabledOrNotFound.

@Test
public void testDisabledOrNotFound() {
    AuthenticationException e = new IdmAuthenticationException("test");
    AuthenticationExceptionContext ctx = new AuthenticationExceptionContext();
    ctx.setAuthEx(e);
    Assert.assertFalse(ctx.isAuthoritiesChanged());
    Assert.assertTrue(ctx.isDisabledOrNotExists());
    Assert.assertFalse(ctx.isExpired());
}
Also used : IdmAuthenticationException(eu.bcvsolutions.idm.core.security.api.exception.IdmAuthenticationException) AuthenticationException(org.springframework.security.core.AuthenticationException) IdmAuthenticationException(eu.bcvsolutions.idm.core.security.api.exception.IdmAuthenticationException) AbstractUnitTest(eu.bcvsolutions.idm.test.api.AbstractUnitTest) Test(org.junit.Test)

Example 75 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ArachneCentralAPI by OHDSI.

the class BaseAuthenticationController method login.

@ApiOperation("Login with specified credentials.")
@RequestMapping(value = "/api/v1/auth/login", method = RequestMethod.POST)
public JsonResult<CommonAuthenticationResponse> login(@Valid @RequestBody CommonAuthenticationRequest authenticationRequest) throws AuthenticationException {
    JsonResult<CommonAuthenticationResponse> jsonResult;
    String username = authenticationRequest.getUsername();
    try {
        checkIfUserBlocked(username);
        checkIfUserHasTenant(username);
        String authToken = authenticationService.authenticateAndGetAuthToken(authenticationRequest);
        CommonAuthenticationResponse authenticationResponse = new CommonAuthenticationResponse(authToken);
        jsonResult = new JsonResult<>(JsonResult.ErrorCode.NO_ERROR, authenticationResponse);
        loginAttemptService.loginSucceeded(username);
    } catch (Exception ex) {
        jsonResult = getJsonResultForUnsuccessfulLogin(username, ex);
    }
    // Return the token
    return jsonResult;
}
Also used : CommonAuthenticationResponse(com.odysseusinc.arachne.commons.api.v1.dto.CommonAuthenticationResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) NoDefaultTenantException(com.odysseusinc.arachne.portal.exception.NoDefaultTenantException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) AuthenticationException(org.springframework.security.core.AuthenticationException) UserNotActivatedException(com.odysseusinc.arachne.portal.exception.UserNotActivatedException) UserNotFoundException(com.odysseusinc.arachne.portal.exception.UserNotFoundException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) IOException(java.io.IOException) PermissionDeniedException(com.odysseusinc.arachne.portal.exception.PermissionDeniedException) PasswordValidationException(com.odysseusinc.arachne.portal.exception.PasswordValidationException) NotExistException(com.odysseusinc.arachne.portal.exception.NotExistException) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)156 Authentication (org.springframework.security.core.Authentication)78 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)42 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)28 HttpServletRequest (javax.servlet.http.HttpServletRequest)27 HttpServletResponse (javax.servlet.http.HttpServletResponse)25 Test (org.junit.Test)24 Test (org.junit.jupiter.api.Test)19 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)15 IOException (java.io.IOException)13 ServletException (javax.servlet.ServletException)12 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 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 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)6 HashMap (java.util.HashMap)6 InternalAuthenticationServiceException (org.springframework.security.authentication.InternalAuthenticationServiceException)6