Search in sources :

Example 11 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project spring-security by spring-projects.

the class DefaultJaasAuthenticationProviderTests method authenticateBadPassword.

@Test
public void authenticateBadPassword() {
    try {
        provider.authenticate(new UsernamePasswordAuthenticationToken("user", "asdf"));
        fail("LoginException should have been thrown for the bad password");
    } catch (AuthenticationException success) {
    }
    verifyFailedLogin();
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Test(org.junit.Test)

Example 12 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project spring-security-oauth by spring-projects.

the class DefaultTokenServicesWithInMemoryTests method testRefreshTokenWithUnauthenticatedUser.

@Test
public void testRefreshTokenWithUnauthenticatedUser() throws Exception {
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(RequestTokenFactory.createOAuth2Request("id", false, Collections.singleton("read")), new TestAuthentication("test2", false));
    getTokenServices().setAuthenticationManager(new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            throw new AccountExpiredException("Not valid");
        }
    });
    DefaultOAuth2AccessToken firstAccessToken = (DefaultOAuth2AccessToken) getTokenServices().createAccessToken(expectedAuthentication);
    assertNotNull(firstAccessToken.getRefreshToken());
    expected.expect(AccountExpiredException.class);
    TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap("client_id", "id"), "id", null, null);
    getTokenServices().refreshAccessToken(firstAccessToken.getRefreshToken().getValue(), tokenRequest);
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) AccountExpiredException(org.springframework.security.authentication.AccountExpiredException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Test(org.junit.Test)

Example 13 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project spring-security-oauth by spring-projects.

the class TokenEndpointAuthenticationFilter 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 credentials = extractCredentials(request);
        if (credentials != null) {
            if (debug) {
                logger.debug("Authentication credentials found for '" + credentials.getName() + "'");
            }
            Authentication authResult = authenticationManager.authenticate(credentials);
            if (debug) {
                logger.debug("Authentication success: " + authResult.getName());
            }
            Authentication clientAuth = SecurityContextHolder.getContext().getAuthentication();
            if (clientAuth == null) {
                throw new BadCredentialsException("No client authentication found. Remember to put a filter upstream of the TokenEndpointAuthenticationFilter.");
            }
            Map<String, String> map = getSingleValueMap(request);
            map.put(OAuth2Utils.CLIENT_ID, clientAuth.getName());
            AuthorizationRequest authorizationRequest = oAuth2RequestFactory.createAuthorizationRequest(map);
            authorizationRequest.setScope(getScope(request));
            if (clientAuth.isAuthenticated()) {
                // Ensure the OAuth2Authentication is authenticated
                authorizationRequest.setApproved(true);
            }
            OAuth2Request storedOAuth2Request = oAuth2RequestFactory.createOAuth2Request(authorizationRequest);
            SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(storedOAuth2Request, authResult));
            onSuccessfulAuthentication(request, response, authResult);
        }
    } catch (AuthenticationException failed) {
        SecurityContextHolder.clearContext();
        if (debug) {
            logger.debug("Authentication request for failed: " + failed);
        }
        onUnsuccessfulAuthentication(request, response, failed);
        authenticationEntryPoint.commence(request, response, failed);
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 14 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 {
        ReflectionSaltSource saltSource = new ReflectionSaltSource();
        saltSource.setUserPropertyToUse("username");
        DaoAuthenticationProvider authenticator = new DaoAuthenticationProvider();
        authenticator.setUserDetailsService(userDetailsService);
        if (encoder != null && "SHA256".equalsIgnoreCase(encoder)) {
            authenticator.setPasswordEncoder(new ShaPasswordEncoder(256));
        } else if (encoder != null && "MD5".equalsIgnoreCase(encoder)) {
            authenticator.setPasswordEncoder(new Md5PasswordEncoder());
        }
        authenticator.setSaltSource(saltSource);
        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;
    }
    return authentication;
}
Also used : ShaPasswordEncoder(org.springframework.security.authentication.encoding.ShaPasswordEncoder) 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) ReflectionSaltSource(org.springframework.security.authentication.dao.ReflectionSaltSource) Md5PasswordEncoder(org.springframework.security.authentication.encoding.Md5PasswordEncoder) 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 15 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();
    List<String> allowedOrganizations = ofNullable(loginDetails.get().getRestrictions()).flatMap(restrictions -> ofNullable(restrictions.get("organizations"))).map(it -> Splitter.on(",").omitEmptyStrings().splitToList(it)).orElse(emptyList());
    if (!allowedOrganizations.isEmpty()) {
        boolean assignedToOrganization = gitHubClient.getUserOrganizations(gitHubUser).stream().map(userOrg -> userOrg.login).anyMatch(allowedOrganizations::contains);
        if (!assignedToOrganization) {
            throw new InsufficientOrganizationException("User '" + gitHubUser.login + "' does not belong to allowed GitHUB organization");
        }
    }
    User user = replicator.replicateUser(gitHubUser, gitHubClient);
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getId(), "N/A", AuthUtils.AS_AUTHORITIES.apply(user.getRole()));
    Map<String, Serializable> extensionProperties = Collections.singletonMap("upstream_token", accessToken);
    OAuth2Request request = new OAuth2Request(null, loginDetails.get().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) OAuth2LoginDetails(com.epam.ta.reportportal.database.entity.settings.OAuth2LoginDetails) 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) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) AuthUtils(com.epam.reportportal.auth.AuthUtils) Map(java.util.Map) User(com.epam.ta.reportportal.database.entity.user.User) AuthenticationException(org.springframework.security.core.AuthenticationException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) 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) User(com.epam.ta.reportportal.database.entity.user.User) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Aggregations

AuthenticationException (org.springframework.security.core.AuthenticationException)152 Authentication (org.springframework.security.core.Authentication)79 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)42 HttpServletRequest (javax.servlet.http.HttpServletRequest)26 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)24 HttpServletResponse (javax.servlet.http.HttpServletResponse)23 Test (org.junit.Test)20 Test (org.junit.jupiter.api.Test)19 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)14 IOException (java.io.IOException)13 ServletException (javax.servlet.ServletException)12 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)10 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)9 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 UserDetails (org.springframework.security.core.userdetails.UserDetails)7 MidPointPrincipal (com.evolveum.midpoint.security.api.MidPointPrincipal)6 HashMap (java.util.HashMap)6