Search in sources :

Example 11 with AuthenticationServiceException

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

the class DigestAuthenticationFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith("Digest ")) {
        chain.doFilter(request, response);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Digest Authorization header received from user agent: " + header);
    }
    DigestData digestAuth = new DigestData(header);
    try {
        digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(), this.authenticationEntryPoint.getRealmName());
    } catch (BadCredentialsException e) {
        fail(request, response, e);
        return;
    }
    // Lookup password for presented username
    // NB: DAO-provided password MUST be clear text - not encoded/salted
    // (unless this instance's passwordAlreadyEncoded property is 'false')
    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
    String serverDigestMd5;
    try {
        if (user == null) {
            cacheWasUsed = false;
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            if (user == null) {
                throw new AuthenticationServiceException("AuthenticationDao returned null, which is an interface contract violation");
            }
            this.userCache.putUserInCache(user);
        }
        serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        // If digest is incorrect, try refreshing from backend and recomputing
        if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
            if (logger.isDebugEnabled()) {
                logger.debug("Digest comparison failure; trying to refresh user from DAO in case password had changed");
            }
            user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
            this.userCache.putUserInCache(user);
            serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
        }
    } catch (UsernameNotFoundException notFound) {
        fail(request, response, new BadCredentialsException(this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound", new Object[] { digestAuth.getUsername() }, "Username {0} not found")));
        return;
    }
    // If digest is still incorrect, definitely reject authentication attempt
    if (!serverDigestMd5.equals(digestAuth.getResponse())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '" + digestAuth.getResponse() + "'; is AuthenticationDao returning clear text passwords?");
        }
        fail(request, response, new BadCredentialsException(this.messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response")));
        return;
    }
    // but the request was otherwise appearing to be valid
    if (digestAuth.isNonceExpired()) {
        fail(request, response, new NonceExpiredException(this.messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '" + digestAuth.getResponse() + "'");
    }
    Authentication authentication = createSuccessfulAuthentication(request, user);
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authentication);
    SecurityContextHolder.setContext(context);
    chain.doFilter(request, response);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) HttpServletResponse(javax.servlet.http.HttpServletResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext)

Example 12 with AuthenticationServiceException

use of org.springframework.security.authentication.AuthenticationServiceException 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 13 with AuthenticationServiceException

use of org.springframework.security.authentication.AuthenticationServiceException in project opennms by OpenNMS.

the class RadiusAuthenticationProvider method retrieveUser.

/* (non-Javadoc)
     * @see org.springframework.security.providers.dao.AbstractUserDetailsAuthenticationProvider#retrieveUser(java.lang.String, org.springframework.security.providers.UsernamePasswordAuthenticationToken)
     */
/** {@inheritDoc} */
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token) throws AuthenticationException {
    if (!StringUtils.hasLength(username)) {
        LOG.info("Authentication attempted with empty username");
        throw new BadCredentialsException(messages.getMessage("RadiusAuthenticationProvider.emptyUsername", "Username cannot be empty"));
    }
    String password = (String) token.getCredentials();
    if (!StringUtils.hasLength(password)) {
        LOG.info("Authentication attempted with empty password");
        throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    InetAddress serverIP = null;
    serverIP = InetAddressUtils.addr(server);
    if (serverIP == null) {
        LOG.error("Could not resolve radius server address {}", server);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.unknownServer", "Could not resolve radius server address"));
    }
    AttributeFactory.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl");
    AttributeList attributeList = new AttributeList();
    attributeList.add(new Attr_UserName(username));
    attributeList.add(new Attr_UserPassword(password));
    RadiusPacket reply;
    try {
        RadiusClient radiusClient = new RadiusClient(serverIP, secret, port, port + 1, timeout);
        AccessRequest request = new AccessRequest(radiusClient, attributeList);
        LOG.debug("Sending AccessRequest message to {}:{} using {} protocol with timeout = {}, retries = {}, attributes:\n{}", InetAddressUtils.str(serverIP), port, (authTypeClass == null ? "PAP" : authTypeClass.getAuthName()), timeout, retries, attributeList.toString());
        reply = radiusClient.authenticate(request, authTypeClass, retries);
    } catch (RadiusException e) {
        LOG.error("Error connecting to radius server {} : {}", server, e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e));
    } catch (IOException e) {
        LOG.error("Error connecting to radius server {} : {}", server, e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError", new Object[] { e }, "Error connecting to radius server: " + e));
    }
    if (reply == null) {
        LOG.error("Timed out connecting to radius server {}", server);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusTimeout", "Timed out connecting to radius server"));
    }
    if (!(reply instanceof AccessAccept)) {
        LOG.info("Received a reply other than AccessAccept from radius server {} for user {} :\n{}", server, username, reply.toString());
        throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    LOG.debug("Received AccessAccept message from {}:{} for user {} with attributes:\n{}", InetAddressUtils.str(serverIP), port, username, reply.getAttributes().toString());
    String roles = null;
    if (!StringUtils.hasLength(rolesAttribute)) {
        LOG.debug("rolesAttribute not set, using default roles ({}) for user {}", defaultRoles, username);
        roles = new String(defaultRoles);
    } else {
        Iterator<RadiusAttribute> attributes = reply.getAttributes().getAttributeList().iterator();
        while (attributes.hasNext()) {
            RadiusAttribute attribute = attributes.next();
            if (rolesAttribute.equals(attribute.getAttributeName())) {
                roles = new String(attribute.getValue().getBytes());
                break;
            }
        }
        if (roles == null) {
            LOG.info("Radius attribute {} not found, using default roles ({}) for user {}", rolesAttribute, defaultRoles, username);
            roles = new String(defaultRoles);
        }
    }
    String[] rolesArray = roles.replaceAll("\\s*", "").split(",");
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(rolesArray.length);
    for (String role : rolesArray) {
        authorities.add(new SimpleGrantedAuthority(role));
    }
    StringBuffer readRoles = new StringBuffer();
    for (GrantedAuthority authority : authorities) {
        readRoles.append(authority.toString() + ", ");
    }
    if (readRoles.length() > 0) {
        readRoles.delete(readRoles.length() - 2, readRoles.length());
    }
    LOG.debug("Parsed roles {} for user {}", readRoles, username);
    return new User(username, password, true, true, true, true, authorities);
}
Also used : RadiusClient(net.jradius.client.RadiusClient) User(org.springframework.security.core.userdetails.User) AccessRequest(net.jradius.packet.AccessRequest) AttributeList(net.jradius.packet.attribute.AttributeList) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Attr_UserPassword(net.jradius.dictionary.Attr_UserPassword) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) RadiusAttribute(net.jradius.packet.attribute.RadiusAttribute) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) RadiusPacket(net.jradius.packet.RadiusPacket) Attr_UserName(net.jradius.dictionary.Attr_UserName) InetAddress(java.net.InetAddress) RadiusException(net.jradius.exception.RadiusException) AccessAccept(net.jradius.packet.AccessAccept)

Example 14 with AuthenticationServiceException

use of org.springframework.security.authentication.AuthenticationServiceException in project midpoint by Evolveum.

the class AuthenticationEvaluatorImpl method getCredentialsPolicy.

private CredentialPolicyType getCredentialsPolicy(MidPointPrincipal principal, T authnCtx) {
    SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
    CredentialPolicyType credentialsPolicy = null;
    try {
        credentialsPolicy = getEffectiveCredentialPolicy(securityPolicy, authnCtx);
    } catch (SchemaException e) {
        // TODO how to properly hanlde the error????
        throw new AuthenticationServiceException("Bad config");
    }
    return credentialsPolicy;
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 15 with AuthenticationServiceException

use of org.springframework.security.authentication.AuthenticationServiceException in project midpoint by Evolveum.

the class AuthenticationEvaluatorImpl method decryptAndMatch.

//	protected boolean matchDecryptedValue(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, String decryptedValue,
//			String enteredPassword){
//		return enteredPassword.equals(decryptedValue);
//	}
//	
protected boolean decryptAndMatch(ConnectionEnvironment connEnv, @NotNull MidPointPrincipal principal, ProtectedStringType protectedString, String enteredPassword) {
    ProtectedStringType entered = new ProtectedStringType();
    entered.setClearValue(enteredPassword);
    try {
        return protector.compare(entered, protectedString);
    } catch (SchemaException | EncryptionException e) {
        recordAuthenticationFailure(principal, connEnv, "error decrypting password: " + e.getMessage());
        throw new AuthenticationServiceException("web.security.provider.unavailable", e);
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Aggregations

AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)17 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)6 Authentication (org.springframework.security.core.Authentication)6 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)5 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)3 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)3 Test (org.junit.Test)3 ConnectionEnvironment (com.evolveum.midpoint.security.api.ConnectionEnvironment)2 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpSession (javax.servlet.http.HttpSession)2 LockedException (org.springframework.security.authentication.LockedException)2 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)2 PasswordAuthenticationContext (com.evolveum.midpoint.model.api.context.PasswordAuthenticationContext)1 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)1 Task (com.evolveum.midpoint.task.api.Task)1 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)1 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)1 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)1