Search in sources :

Example 31 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project CILManagement-Server by LiuinStein.

the class MyAuthenticationFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if ("application/json".equals(request.getHeader("Content-Type"))) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            JSONObject jsonObject = JSONObject.parseObject(stringBuilder.toString());
            this.userId = jsonObject.getLong("username");
            this.password = jsonObject.getString("password");
        } catch (Exception e) {
            throw new UsernameNotFoundException("username error");
        }
    }
    return super.attemptAuthentication(request, response);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) JSONObject(com.alibaba.fastjson.JSONObject) BufferedReader(java.io.BufferedReader) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.security.core.AuthenticationException)

Example 32 with AuthenticationException

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

the class DefaultWebResponseExceptionTranslator method translate.

@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
    // Try to extract a SpringSecurityException from the stacktrace
    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception((OAuth2Exception) ase);
    }
    ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
    }
    ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase instanceof AccessDeniedException) {
        return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
    }
    ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase instanceof HttpRequestMethodNotSupportedException) {
        return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
    }
    return handleOAuth2Exception(new ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) IOException(java.io.IOException) AuthenticationException(org.springframework.security.core.AuthenticationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 33 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project metalnx-web by irods-contrib.

the class IRODSAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = authentication.getCredentials().toString();
    AuthResponse authResponse;
    UsernamePasswordAuthenticationToken authObject;
    logger.debug("Setting username {}", username);
    try {
        authResponse = this.authenticateAgainstIRODS(username, password);
        // Settings iRODS account
        this.irodsAccount = authResponse.getAuthenticatedIRODSAccount();
        // Retrieving logging user
        User irodsUser = new User();
        try {
            irodsUser = this.irodsAccessObjectFactory.getUserAO(this.irodsAccount).findByName(username);
        } catch (JargonException e) {
            logger.error("Could not find user: " + e.getMessage());
        }
        GrantedAuthority grantedAuth;
        if (irodsUser.getUserType().equals(UserTypeEnum.RODS_ADMIN)) {
            grantedAuth = new IRODSAdminGrantedAuthority();
        } else {
            grantedAuth = new IRODSUserGrantedAuthority();
        }
        // Settings granted authorities
        List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
        grantedAuths.add(grantedAuth);
        // Returning authentication token with the access object factory injected
        authObject = new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
        // Creating UserTokenDetails instance for the current authenticated user
        UserTokenDetails userDetails = new UserTokenDetails();
        userDetails.setIrodsAccount(this.irodsAccount);
        userDetails.setUser(this.user);
        // Settings the user details object into the authentication object
        authObject.setDetails(userDetails);
    } catch (TransactionException e) {
        logger.error("Database not responding");
        throw new DataGridDatabaseException(e.getMessage());
    } catch (InvalidUserException | org.irods.jargon.core.exception.AuthenticationException e) {
        logger.error("Could not authenticate user: ", username);
        throw new DataGridAuthenticationException(e.getMessage());
    } catch (JargonException e) {
        logger.error("Server not responding");
        throw new DataGridServerException(e.getMessage());
    }
    return authObject;
}
Also used : DataGridUser(com.emc.metalnx.core.domain.entity.DataGridUser) User(org.irods.jargon.core.pub.domain.User) DataGridAuthenticationException(com.emc.metalnx.core.domain.exceptions.DataGridAuthenticationException) AuthenticationException(org.springframework.security.core.AuthenticationException) JargonException(org.irods.jargon.core.exception.JargonException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) InvalidUserException(org.irods.jargon.core.exception.InvalidUserException) DataGridAuthenticationException(com.emc.metalnx.core.domain.exceptions.DataGridAuthenticationException) AuthResponse(org.irods.jargon.core.connection.auth.AuthResponse) DataGridDatabaseException(com.emc.metalnx.core.domain.exceptions.DataGridDatabaseException) TransactionException(org.springframework.transaction.TransactionException) DataGridServerException(com.emc.metalnx.core.domain.exceptions.DataGridServerException)

Example 34 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project tesb-rt-se by Talend.

the class BasicAuthHttpContext method handleSecurity.

@Override
public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        SecurityContextHolder.getContext().setAuthentication(null);
        DummyFilterChain dummyFilter = new DummyFilterChain();
        filter.doFilter(request, response, dummyFilter);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null) {
            AuthenticationException ex = new AuthenticationCredentialsNotFoundException("Anonymous access denied");
            authenticationEntryPoint.commence(request, response, ex);
            return false;
        }
        return dummyFilter.isCalled();
    } catch (ServletException e) {
        return false;
    }
}
Also used : ServletException(javax.servlet.ServletException) AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication)

Example 35 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project herd by FINRAOS.

the class HttpHeaderAuthenticationFilter method authenticateUser.

/**
 * Creates the user based on the given request, and puts the user into the security context. Throws if authentication fails.
 *
 * @param servletRequest {@link HttpServletRequest} containing the user's request.
 */
private void authenticateUser(HttpServletRequest servletRequest) {
    try {
        // Setup the authentication request and perform the authentication. Perform the authentication based on the fully built user.
        PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken = new PreAuthenticatedAuthenticationToken(applicationUserBuilder.build(servletRequest), "N/A");
        preAuthenticatedAuthenticationToken.setDetails(authenticationDetailsSource.buildDetails(servletRequest));
        Authentication authentication = authenticationManager.authenticate(preAuthenticatedAuthenticationToken);
        // The authentication returned so it was successful.
        successfulAuthentication(authentication);
    } catch (AuthenticationException e) {
        // An authentication exception was thrown so authentication failed.
        unsuccessfulAuthentication(servletRequest, e);
        // exist for the logged in user or it couldn't be retrieved).
        throw e;
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken)

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