Search in sources :

Example 16 with AuthenticationException

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

the class KerberosProvider method authenticate.

@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException {
    if (provider == null) {
        throw new IdentityAccessException("The Kerberos authentication provider is not initialized.");
    }
    try {
        // Perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
        logger.debug("Created authentication token for principal {} with name {} and is authenticated {}", token.getPrincipal(), token.getName(), token.isAuthenticated());
        final Authentication authentication = provider.authenticate(token);
        logger.debug("Ran provider.authenticate() and returned authentication for " + "principal {} with name {} and is authenticated {}", authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated());
        return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
    } catch (final AuthenticationException e) {
        throw new InvalidLoginCredentialsException(e.getMessage(), e);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) InvalidLoginCredentialsException(org.apache.nifi.authentication.exception.InvalidLoginCredentialsException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) IdentityAccessException(org.apache.nifi.authentication.exception.IdentityAccessException) AuthenticationResponse(org.apache.nifi.authentication.AuthenticationResponse)

Example 17 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 18 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ocvn by devgateway.

the class SSAuthenticatedWebSession method authenticate.

@Override
public boolean authenticate(final String username, final String password) {
    boolean authenticated;
    try {
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // httpSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
        // SecurityContextHolder.getContext());
        authenticated = authentication.isAuthenticated();
        if (authenticated && rememberMeServices != null) {
            rememberMeServices.loginSuccess((HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest(), (HttpServletResponse) RequestCycle.get().getResponse().getContainerResponse(), authentication);
        }
    } catch (AuthenticationException e) {
        this.setAe(e);
        log.warn("User '{}' failed to login. Reason: {}", username, e.getMessage());
        authenticated = false;
    }
    return authenticated;
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 19 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ArachneCentralAPI by OHDSI.

the class BaseAuthenticationController method login.

@ApiOperation("Login with specified credentials.")
@RequestMapping(value = "/api/v1/auth/login", method = RequestMethod.POST)
public JsonResult<CommonAuthenticationResponse> login(@RequestBody CommonAuthenticationRequest authenticationRequest) throws AuthenticationException {
    JsonResult<CommonAuthenticationResponse> jsonResult;
    String username = authenticationRequest.getUsername();
    try {
        checkIfUserBlocked(username);
        Authentication authentication = authenticate(authenticationRequest);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = this.tokenUtils.generateToken(username);
        CommonAuthenticationResponse authenticationResponse = new CommonAuthenticationResponse(token);
        jsonResult = new JsonResult<>(JsonResult.ErrorCode.NO_ERROR, authenticationResponse);
        loginAttemptService.loginSucceeded(username);
    } catch (Exception ex) {
        jsonResult = getJsonResultForUnsuccessfulLogin(username, ex);
    }
    // Return the token
    return jsonResult;
}
Also used : CommonAuthenticationResponse(com.odysseusinc.arachne.commons.api.v1.dto.CommonAuthenticationResponse) Authentication(org.springframework.security.core.Authentication) SolrServerException(org.apache.solr.client.solrj.SolrServerException) AuthenticationException(org.springframework.security.core.AuthenticationException) UserNotActivatedException(com.odysseusinc.arachne.portal.exception.UserNotActivatedException) UserNotFoundException(com.odysseusinc.arachne.portal.exception.UserNotFoundException) IOException(java.io.IOException) PermissionDeniedException(com.odysseusinc.arachne.portal.exception.PermissionDeniedException) PasswordValidationException(com.odysseusinc.arachne.portal.exception.PasswordValidationException) MailSendException(org.springframework.mail.MailSendException) NotExistException(com.odysseusinc.arachne.portal.exception.NotExistException) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 20 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project ArachneCentralAPI by OHDSI.

the class AuthenticationTokenFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException, AuthenticationException {
    try {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String authToken = httpRequest.getHeader(tokenHeader);
        if (authToken == null && httpRequest.getCookies() != null) {
            for (Cookie cookie : httpRequest.getCookies()) {
                if (cookie.getName().equalsIgnoreCase(tokenHeader)) {
                    authToken = cookie.getValue();
                }
            }
        }
        if (authToken != null) {
            String username = this.tokenUtils.getUsernameFromToken(authToken);
            if (tokenUtils.isExpired(authToken)) {
                if (((HttpServletRequest) request).getRequestURI().startsWith("/api")) {
                    if (username != null) {
                        throw new BadCredentialsException("token expired");
                    }
                }
            }
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (this.tokenUtils.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    TenantContext.setCurrentTenant(((ArachneUser) userDetails).getActiveTenantId());
                }
            }
        }
        chain.doFilter(request, response);
    } catch (AuthenticationException ex) {
        logger.debug(ex.getMessage(), ex);
        ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        JsonResult<Boolean> result = new JsonResult<>(JsonResult.ErrorCode.UNAUTHORIZED);
        result.setResult(Boolean.FALSE);
        response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
        response.setContentType("application/json");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Cookie(javax.servlet.http.Cookie) UserDetails(org.springframework.security.core.userdetails.UserDetails) AuthenticationException(org.springframework.security.core.AuthenticationException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) WebAuthenticationDetailsSource(org.springframework.security.web.authentication.WebAuthenticationDetailsSource) JsonResult(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult)

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