Search in sources :

Example 51 with AuthenticationException

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

the class OpenClinicaUsernamePasswordAuthenticationFilter method attemptAuthentication.

//~ Methods ========================================================================================================
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }
    String username = obtainUsername(request);
    String password = obtainPassword(request);
    if (username == null) {
        username = "";
    }
    if (password == null) {
        password = "";
    }
    username = username.trim();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
    // Place the last username attempted into HttpSession for views
    HttpSession session = request.getSession(false);
    if (session != null || getAllowSessionCreation()) {
        request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextEscapeUtils.escapeEntities(username));
    }
    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);
    Authentication authentication = null;
    UserAccountBean userAccountBean = null;
    ResourceBundleProvider.updateLocale(new Locale("en_US"));
    try {
        EntityBean eb = getUserAccountDao().findByUserName(username);
        userAccountBean = eb.getId() != 0 ? (UserAccountBean) eb : null;
        authentication = this.getAuthenticationManager().authenticate(authRequest);
        auditUserLogin(username, LoginStatus.SUCCESSFUL_LOGIN, userAccountBean);
        resetLockCounter(username, LoginStatus.SUCCESSFUL_LOGIN, userAccountBean);
    } catch (LockedException le) {
        auditUserLogin(username, LoginStatus.FAILED_LOGIN_LOCKED, userAccountBean);
        throw le;
    } catch (BadCredentialsException au) {
        auditUserLogin(username, LoginStatus.FAILED_LOGIN, userAccountBean);
        lockAccount(username, LoginStatus.FAILED_LOGIN, userAccountBean);
        throw au;
    } catch (AuthenticationException ae) {
        throw ae;
    }
    return authentication;
}
Also used : Locale(java.util.Locale) LockedException(org.springframework.security.authentication.LockedException) AuthenticationException(org.springframework.security.core.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) Authentication(org.springframework.security.core.Authentication) EntityBean(org.akaza.openclinica.bean.core.EntityBean) UserAccountBean(org.akaza.openclinica.bean.login.UserAccountBean) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 52 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project libresonic by Libresonic.

the class RESTRequestParameterProcessingFilter method authenticate.

private RESTController.ErrorCode authenticate(String username, String password, String salt, String token, Authentication previousAuth) {
    // Previously authenticated and username not overridden?
    if (username == null && previousAuth != null) {
        return null;
    }
    if (salt != null && token != null) {
        User user = securityService.getUserByName(username);
        if (user == null) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
        String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
        if (!expectedToken.equals(token)) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
        password = user.getPassword();
    }
    if (password != null) {
        try {
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            Authentication authResult = authenticationManager.authenticate(authRequest);
            SecurityContextHolder.getContext().setAuthentication(authResult);
            return null;
        } catch (AuthenticationException x) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
    }
    return RESTController.ErrorCode.MISSING_PARAMETER;
}
Also used : User(org.libresonic.player.domain.User) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 53 with AuthenticationException

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

the class LdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    try {
        final String username = authentication.getPrincipal().toString();
        final Object credentials = authentication.getCredentials();
        final String password = credentials == null ? null : credentials.toString();
        LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
        final AuthenticationRequest request = new AuthenticationRequest(username, new org.ldaptive.Credential(password), ReturnAttributes.ALL.value());
        final Authenticator authenticator = LdapUtils.newLdaptiveAuthenticator(adminPagesSecurityProperties.getLdap());
        LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
        final AuthenticationResponse response = authenticator.authenticate(request);
        LOGGER.debug("LDAP response: [{}]", response);
        if (response.getResult()) {
            final LdapEntry entry = response.getLdapEntry();
            final CommonProfile profile = new CommonProfile();
            profile.setId(username);
            entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
            LOGGER.debug("Collected user profile [{}]", profile);
            this.authorizationGenerator.generate(Pac4jUtils.getPac4jJ2EContext(), profile);
            LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
            final Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.addAll(profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
            final RequireAnyRoleAuthorizer authorizer = new RequireAnyRoleAuthorizer(adminPagesSecurityProperties.getAdminRoles());
            LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
            final J2EContext context = Pac4jUtils.getPac4jJ2EContext();
            if (authorizer.isAllAuthorized(context, CollectionUtils.wrap(profile))) {
                return new UsernamePasswordAuthenticationToken(username, password, 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) {
        LOGGER.error(e.getMessage(), e);
        throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
    }
    throw new BadCredentialsException("Could not authenticate provided credentials");
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) LdapEntry(org.ldaptive.LdapEntry) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) J2EContext(org.pac4j.core.context.J2EContext) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.ldaptive.auth.AuthenticationResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) CommonProfile(org.pac4j.core.profile.CommonProfile) AuthenticationRequest(org.ldaptive.auth.AuthenticationRequest) Authenticator(org.ldaptive.auth.Authenticator) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer)

Example 54 with AuthenticationException

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

the class JwtIdmAuthenticationFilter method authorize.

@Override
public boolean authorize(String token, HttpServletRequest request, HttpServletResponse response) {
    IdmJwtAuthenticationDto claims = null;
    try {
        Optional<Jwt> jwt = HttpFilterUtils.parseToken(token);
        if (!jwt.isPresent()) {
            return false;
        }
        HttpFilterUtils.verifyToken(jwt.get(), jwtTokenMapper.getVerifier());
        claims = jwtTokenMapper.getClaims(jwt.get());
        ctx.setToken(claims);
        Authentication auth = authenticationManager.authenticate(jwtTokenMapper.fromDto(claims));
        LOG.debug("User [{}] successfully logged in.", auth.getName());
        return auth.isAuthenticated();
    } catch (ResultCodeException ex) {
        LOG.warn("Invalid token, reason: [{}]", ex.getMessage());
        ctx.setCodeEx(ex);
        // only expired or authorities changed
        ctx.setToken(claims);
    } catch (AuthenticationException ex) {
        LOG.warn("Invalid authentication, reason: [{}]", ex.getMessage());
        ctx.setAuthEx(ex);
    } catch (InvalidSignatureException | IOException | IllegalArgumentException ex) {
        // client sent some rubbish, just log and ignore
        LOG.warn("Invalid IdM auth token received.", ex);
    }
    return false;
}
Also used : InvalidSignatureException(org.springframework.security.jwt.crypto.sign.InvalidSignatureException) AuthenticationException(org.springframework.security.core.AuthenticationException) Jwt(org.springframework.security.jwt.Jwt) Authentication(org.springframework.security.core.Authentication) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) IOException(java.io.IOException)

Example 55 with AuthenticationException

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

the class OAuthAuthenticationManagerTest method testIdentityNotExists.

/**
 * Non-existent identities cannot possess auth. tokens.
 */
@Test
public void testIdentityNotExists() {
    IdmJwtAuthentication authentication = getAuthentication(USER_NAME, DateTime.now().plusHours(1), DateTime.now());
    when(identityService.getByUsername(USER_NAME)).thenReturn(null);
    try {
        authManager.authenticate(authentication);
        Assert.fail("Cannot authenticate unknown identity.");
    } catch (AuthenticationException e) {
        verify(identityService).getByUsername(USER_NAME);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) Test(org.junit.Test) AbstractUnitTest(eu.bcvsolutions.idm.test.api.AbstractUnitTest)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)56 Authentication (org.springframework.security.core.Authentication)30 Test (org.junit.Test)24 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)19 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 HttpServletResponse (javax.servlet.http.HttpServletResponse)12 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)12 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)7 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)6 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)6 IOException (java.io.IOException)5 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)5 HashMap (java.util.HashMap)3 ServletException (javax.servlet.ServletException)3 HttpSession (javax.servlet.http.HttpSession)3 LockedException (org.springframework.security.authentication.LockedException)3 AbstractUnitTest (eu.bcvsolutions.idm.test.api.AbstractUnitTest)2 Map (java.util.Map)2 LoginException (javax.security.auth.login.LoginException)2 FilterChain (javax.servlet.FilterChain)2