Search in sources :

Example 76 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project the-app by devops-dojo.

the class AuthenticationServiceImpl method authenticate.

@Override
public boolean authenticate(LoginInfo loginInfo) {
    try {
        Authentication usernamePasswordAuthentication = new UsernamePasswordAuthenticationToken(loginInfo.getUsername(), loginInfo.getPassword());
        Authentication authenticateResult = authenticationManager.authenticate(usernamePasswordAuthentication);
        SecurityContextHolder.getContext().setAuthentication(authenticateResult);
        logger.info(String.format("Authentication of '%s' was %ssuccessful", loginInfo.getUsername(), (authenticateResult.isAuthenticated() ? "" : "not ")));
        return authenticateResult.isAuthenticated();
    } catch (AuthenticationException e) {
        String msg = String.format("User '%s' could not authenticated correct:", loginInfo.getUsername());
        logger.info(msg, e);
    }
    return false;
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 77 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ranger by apache.

the class RangerAuthenticationProvider method getJDBCAuthentication.

private Authentication getJDBCAuthentication(Authentication authentication, String encoder) throws AuthenticationException {
    try {
        DaoAuthenticationProvider authenticator = new DaoAuthenticationProvider();
        authenticator.setUserDetailsService(userDetailsService);
        if (this.isFipsEnabled) {
            if (authentication != null && authentication.getCredentials() != null && !authentication.isAuthenticated()) {
                Pbkdf2PasswordEncoderCust passwordEncoder = new Pbkdf2PasswordEncoderCust(authentication.getName());
                passwordEncoder.setEncodeHashAsBase64(true);
                authenticator.setPasswordEncoder(passwordEncoder);
            }
        } else {
            if (encoder != null && "SHA256".equalsIgnoreCase(encoder) && authentication != null) {
                authenticator.setPasswordEncoder(new RangerCustomPasswordEncoder(authentication.getName(), "SHA-256"));
            } else if (encoder != null && "MD5".equalsIgnoreCase(encoder) && authentication != null) {
                authenticator.setPasswordEncoder(new RangerCustomPasswordEncoder(authentication.getName(), "MD5"));
            }
        }
        String userName = "";
        String userPassword = "";
        if (authentication != null) {
            userName = authentication.getName();
            if (authentication.getCredentials() != null) {
                userPassword = authentication.getCredentials().toString();
            }
        }
        String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
        if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);
            authentication = authenticator.authenticate(finalAuthentication);
            return authentication;
        } else {
            if (authentication != null && !authentication.isAuthenticated()) {
                throw new BadCredentialsException("Bad credentials");
            }
        }
    } catch (BadCredentialsException e) {
        throw e;
    } catch (AuthenticationServiceException e) {
        throw e;
    } catch (AuthenticationException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    } catch (Throwable t) {
        throw new BadCredentialsException("Bad credentials", t);
    }
    return authentication;
}
Also used : User(org.springframework.security.core.userdetails.User) AuthenticationException(org.springframework.security.core.AuthenticationException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) Pbkdf2PasswordEncoderCust(org.apache.ranger.util.Pbkdf2PasswordEncoderCust) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) DaoAuthenticationProvider(org.springframework.security.authentication.dao.DaoAuthenticationProvider) Authentication(org.springframework.security.core.Authentication)

Example 78 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project service-authorization by reportportal.

the class GitHubTokenServices method loadAuthentication.

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
    GitHubClient gitHubClient = GitHubClient.withAccessToken(accessToken);
    UserResource gitHubUser = gitHubClient.getUser();
    OAuthRegistrationResource oAuthRegistrationResource = oAuthRegistrationSupplier.get();
    List<String> allowedOrganizations = ofNullable(oAuthRegistrationResource.getRestrictions()).flatMap(restrictions -> ofNullable(restrictions.get("organizations"))).map(it -> Splitter.on(",").omitEmptyStrings().splitToList(it)).orElse(emptyList());
    if (!allowedOrganizations.isEmpty()) {
        boolean assignedToOrganization = gitHubClient.getUserOrganizations(gitHubUser.getLogin()).stream().map(OrganizationResource::getLogin).anyMatch(allowedOrganizations::contains);
        if (!assignedToOrganization) {
            throw new InsufficientOrganizationException("User '" + gitHubUser.getLogin() + "' does not belong to allowed GitHUB organization");
        }
    }
    ReportPortalUser user = replicator.replicateUser(gitHubUser, gitHubClient);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, "N/A", user.getAuthorities());
    Map<String, Serializable> extensionProperties = Collections.singletonMap(UPSTREAM_TOKEN, accessToken);
    OAuth2Request request = new OAuth2Request(null, oAuthRegistrationResource.getClientId(), null, true, null, null, null, null, extensionProperties);
    return new OAuth2Authentication(request, token);
}
Also used : Collections.emptyList(java.util.Collections.emptyList) Optional.ofNullable(java.util.Optional.ofNullable) UPSTREAM_TOKEN(com.epam.reportportal.auth.integration.github.ExternalOauth2TokenConverter.UPSTREAM_TOKEN) Supplier(java.util.function.Supplier) ResourceServerTokenServices(org.springframework.security.oauth2.provider.token.ResourceServerTokenServices) Serializable(java.io.Serializable) List(java.util.List) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) ReportPortalUser(com.epam.ta.reportportal.commons.ReportPortalUser) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Map(java.util.Map) AuthenticationException(org.springframework.security.core.AuthenticationException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) OAuthRegistrationResource(com.epam.ta.reportportal.ws.model.settings.OAuthRegistrationResource) Splitter(com.google.common.base.Splitter) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) Collections(java.util.Collections) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) Serializable(java.io.Serializable) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) OAuthRegistrationResource(com.epam.ta.reportportal.ws.model.settings.OAuthRegistrationResource) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) ReportPortalUser(com.epam.ta.reportportal.commons.ReportPortalUser)

Example 79 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project pentaho-platform by pentaho.

the class SpringSecurityLoginModule method getAuthentication.

/**
 * {@inheritDoc}
 *
 * Creates a {@code UsernamePasswordAuthenticationToken} from the given {@code principal} and {@code credentials}
 * and passes to Spring Security {@code AuthenticationManager}.
 */
@Override
protected Authentication getAuthentication(final Principal principal, final Credentials credentials) throws RepositoryException {
    // only handles SimpleCredential instances; DefaultLoginModule behaves the same way (albeit indirectly)
    if (!(credentials instanceof SimpleCredentials)) {
        // $NON-NLS-1$
        logger.debug("credentials not instance of SimpleCredentials; returning null");
        return null;
    }
    SimpleCredentials simpleCredentials = (SimpleCredentials) credentials;
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(simpleCredentials.getUserID(), String.valueOf(simpleCredentials.getPassword()));
    boolean authenticated = false;
    try {
        org.springframework.security.core.Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getName().equals(simpleCredentials.getUserID())) {
            // see if there's already an active Authentication for this user.
            authenticated = true;
        } else {
            // delegate to Spring Security
            getAuthenticationManager().authenticate(token);
            authenticated = true;
        }
    } catch (AuthenticationException e) {
        // $NON-NLS-1$
        logger.debug("authentication exception", e);
    }
    final boolean authenticateResult = authenticated;
    return new Authentication() {

        public boolean canHandle(Credentials credentials) {
            // this is decided earlier in getAuthentication
            return true;
        }

        public boolean authenticate(Credentials credentials) throws RepositoryException {
            return authenticateResult;
        }
    };
}
Also used : SimpleCredentials(javax.jcr.SimpleCredentials) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.apache.jackrabbit.core.security.authentication.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SimpleCredentials(javax.jcr.SimpleCredentials) Credentials(javax.jcr.Credentials)

Example 80 with AuthenticationException

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

the class RestPublicLoginProcessingFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (!HttpMethod.POST.name().equals(request.getMethod())) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication method not supported. Request method: " + request.getMethod());
        }
        throw new AuthMethodNotSupportedException("Authentication method not supported");
    }
    PublicLoginRequest loginRequest;
    try {
        loginRequest = objectMapper.readValue(request.getReader(), PublicLoginRequest.class);
    } catch (Exception e) {
        throw new AuthenticationServiceException("Invalid public login request payload");
    }
    if (StringUtils.isBlank(loginRequest.getPublicId())) {
        throw new AuthenticationServiceException("Public Id is not provided");
    }
    UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, loginRequest.getPublicId());
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, "");
    return this.getAuthenticationManager().authenticate(token);
}
Also used : AuthMethodNotSupportedException(org.thingsboard.server.service.security.exception.AuthMethodNotSupportedException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) ServletException(javax.servlet.ServletException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) IOException(java.io.IOException) AuthMethodNotSupportedException(org.thingsboard.server.service.security.exception.AuthMethodNotSupportedException) AuthenticationException(org.springframework.security.core.AuthenticationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal)

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