Search in sources :

Example 86 with AuthenticationException

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

the class RememberMeAuthenticationFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        Authentication rememberMeAuth = rememberMeServices.autoLogin(request, response);
        if (rememberMeAuth != null) {
            // Attempt authenticaton via AuthenticationManager
            try {
                rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
                // Store to SecurityContextHolder
                SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
                onSuccessfulAuthentication(request, response, rememberMeAuth);
                if (logger.isDebugEnabled()) {
                    logger.debug("SecurityContextHolder populated with remember-me token: '" + SecurityContextHolder.getContext().getAuthentication() + "'");
                }
                // Fire event
                if (this.eventPublisher != null) {
                    eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(SecurityContextHolder.getContext().getAuthentication(), this.getClass()));
                }
                if (successHandler != null) {
                    successHandler.onAuthenticationSuccess(request, response, rememberMeAuth);
                    return;
                }
            } catch (AuthenticationException authenticationException) {
                if (logger.isDebugEnabled()) {
                    logger.debug("SecurityContextHolder not populated with remember-me token, as " + "AuthenticationManager rejected Authentication returned by RememberMeServices: '" + rememberMeAuth + "'; invalidating remember-me token", authenticationException);
                }
                rememberMeServices.loginFail(request, response);
                onUnsuccessfulAuthentication(request, response, authenticationException);
            }
        }
        chain.doFilter(request, response);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("SecurityContextHolder not populated with remember-me token, as it already contained: '" + SecurityContextHolder.getContext().getAuthentication() + "'");
        }
        chain.doFilter(request, response);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) InteractiveAuthenticationSuccessEvent(org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 87 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project libresonic by Libresonic.

the class RESTRequestParameterProcessingFilter method authenticate.

private RESTController.ErrorCode authenticate(String username, String password, String salt, String token, Authentication previousAuth) {
    // Previously authenticated and username not overridden?
    if (username == null && previousAuth != null) {
        return null;
    }
    if (salt != null && token != null) {
        User user = securityService.getUserByName(username);
        if (user == null) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
        String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
        if (!expectedToken.equals(token)) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
        password = user.getPassword();
    }
    if (password != null) {
        try {
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            Authentication authResult = authenticationManager.authenticate(authRequest);
            SecurityContextHolder.getContext().setAuthentication(authResult);
            return null;
        } catch (AuthenticationException x) {
            return RESTController.ErrorCode.NOT_AUTHENTICATED;
        }
    }
    return RESTController.ErrorCode.MISSING_PARAMETER;
}
Also used : User(org.libresonic.player.domain.User) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 88 with AuthenticationException

use of org.springframework.security.core.AuthenticationException in project cas by apereo.

the class LdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    try {
        final String username = authentication.getPrincipal().toString();
        final Object credentials = authentication.getCredentials();
        final String password = credentials == null ? null : credentials.toString();
        LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
        final AuthenticationRequest request = new AuthenticationRequest(username, new org.ldaptive.Credential(password), ReturnAttributes.ALL.value());
        final Authenticator authenticator = LdapUtils.newLdaptiveAuthenticator(adminPagesSecurityProperties.getLdap());
        LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
        final AuthenticationResponse response = authenticator.authenticate(request);
        LOGGER.debug("LDAP response: [{}]", response);
        if (response.getResult()) {
            final LdapEntry entry = response.getLdapEntry();
            final CommonProfile profile = new CommonProfile();
            profile.setId(username);
            entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
            LOGGER.debug("Collected user profile [{}]", profile);
            this.authorizationGenerator.generate(Pac4jUtils.getPac4jJ2EContext(), profile);
            LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
            final Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.addAll(profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
            final RequireAnyRoleAuthorizer authorizer = new RequireAnyRoleAuthorizer(adminPagesSecurityProperties.getAdminRoles());
            LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
            final J2EContext context = Pac4jUtils.getPac4jJ2EContext();
            if (authorizer.isAllAuthorized(context, CollectionUtils.wrap(profile))) {
                return new UsernamePasswordAuthenticationToken(username, password, authorities);
            }
            LOGGER.warn("User [{}] is not authorized to access the requested resource allowed to roles [{}]", username, authorizer.getElements());
        } else {
            LOGGER.warn("LDAP authentication response produced no results for [{}]", username);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
    }
    throw new BadCredentialsException("Could not authenticate provided credentials");
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) LdapEntry(org.ldaptive.LdapEntry) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) J2EContext(org.pac4j.core.context.J2EContext) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationResponse(org.ldaptive.auth.AuthenticationResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) CommonProfile(org.pac4j.core.profile.CommonProfile) AuthenticationRequest(org.ldaptive.auth.AuthenticationRequest) Authenticator(org.ldaptive.auth.Authenticator) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer)

Example 89 with AuthenticationException

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

the class AccessResource method createAccessTokenFromTicket.

/**
 * Creates a token for accessing the REST API via Kerberos ticket exchange / SPNEGO negotiation.
 *
 * @param httpServletRequest the servlet request
 * @return A JWT (string)
 */
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@Path("/kerberos")
@ApiOperation(value = "Creates a token for accessing the REST API via Kerberos ticket exchange / SPNEGO negotiation", notes = "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, " + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header " + "in the format 'Authorization: Bearer <token>'.", response = String.class)
@ApiResponses(value = { @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."), @ApiResponse(code = 401, message = "NiFi was unable to complete the request because it did not contain a valid Kerberos " + "ticket in the Authorization header. Retry this request after initializing a ticket with kinit and " + "ensuring your browser is configured to support SPNEGO."), @ApiResponse(code = 409, message = "Unable to create access token because NiFi is not in the appropriate state. (i.e. may not be configured to support Kerberos login."), @ApiResponse(code = 500, message = "Unable to create access token because an unexpected error occurred.") })
public Response createAccessTokenFromTicket(@Context HttpServletRequest httpServletRequest) {
    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS.");
    }
    // If Kerberos Service Principal and keytab location not configured, throws exception
    if (!properties.isKerberosSpnegoSupportEnabled() || kerberosService == null) {
        throw new IllegalStateException("Kerberos ticket login not supported by this NiFi.");
    }
    String authorizationHeaderValue = httpServletRequest.getHeader(KerberosService.AUTHORIZATION_HEADER_NAME);
    if (!kerberosService.isValidKerberosHeader(authorizationHeaderValue)) {
        final Response response = generateNotAuthorizedResponse().header(KerberosService.AUTHENTICATION_CHALLENGE_HEADER_NAME, KerberosService.AUTHORIZATION_NEGOTIATE).build();
        return response;
    } else {
        try {
            // attempt to authenticate
            Authentication authentication = kerberosService.validateKerberosTicket(httpServletRequest);
            if (authentication == null) {
                throw new IllegalArgumentException("Request is not HTTPS or Kerberos ticket missing or malformed");
            }
            final String expirationFromProperties = properties.getKerberosAuthenticationExpiration();
            long expiration = FormatUtils.getTimeDuration(expirationFromProperties, TimeUnit.MILLISECONDS);
            final String identity = authentication.getName();
            expiration = validateTokenExpiration(expiration, identity);
            // create the authentication token
            final LoginAuthenticationToken loginAuthenticationToken = new LoginAuthenticationToken(identity, expiration, "KerberosService");
            // generate JWT for response
            final String token = jwtService.generateSignedToken(loginAuthenticationToken);
            // build the response
            final URI uri = URI.create(generateResourceUri("access", "kerberos"));
            return generateCreatedResponse(uri, token).build();
        } catch (final AuthenticationException e) {
            throw new AccessDeniedException(e.getMessage(), e);
        }
    }
}
Also used : Response(javax.ws.rs.core.Response) AuthenticationResponse(org.apache.nifi.authentication.AuthenticationResponse) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ApiResponse(io.swagger.annotations.ApiResponse) AccessDeniedException(org.apache.nifi.authorization.AccessDeniedException) AuthenticationException(org.springframework.security.core.AuthenticationException) InvalidAuthenticationException(org.apache.nifi.web.security.InvalidAuthenticationException) Authentication(org.springframework.security.core.Authentication) LoginAuthenticationToken(org.apache.nifi.web.security.token.LoginAuthenticationToken) URI(java.net.URI) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 90 with AuthenticationException

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

the class NiFiAuthenticationFilter method authenticate.

private void authenticate(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
    String dnChain = null;
    try {
        final Authentication authenticationRequest = attemptAuthentication(request);
        if (authenticationRequest != null) {
            // log the request attempt - response details will be logged later
            log.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", authenticationRequest.toString(), request.getMethod(), request.getRequestURL().toString(), request.getRemoteAddr()));
            // attempt to authorize the user
            final Authentication authenticated = authenticationManager.authenticate(authenticationRequest);
            successfulAuthorization(request, response, authenticated);
        }
        // continue
        chain.doFilter(request, response);
    } catch (final AuthenticationException ae) {
        // invalid authentication - always error out
        unsuccessfulAuthorization(request, response, ae);
    }
}
Also used : AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication)

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