Search in sources :

Example 16 with InsufficientAuthenticationException

use of org.springframework.security.authentication.InsufficientAuthenticationException in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationProcessingFilter 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 authentication = tokenExtractor.extract(request);
        if (authentication == null) {
            if (stateless && isAuthenticated()) {
                if (debug) {
                    logger.debug("Clearing security context.");
                }
                SecurityContextHolder.clearContext();
            }
            if (debug) {
                logger.debug("No token in request, will continue chain.");
            }
        } else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
            }
            Authentication authResult = authenticationManager.authenticate(authentication);
            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }
            eventPublisher.publishAuthenticationSuccess(authResult);
            SecurityContextHolder.getContext().setAuthentication(authResult);
        }
    } catch (OAuth2Exception failed) {
        SecurityContextHolder.clearContext();
        if (debug) {
            logger.debug("Authentication request failed: " + failed);
        }
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed), new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
        authenticationEntryPoint.commence(request, response, new InsufficientAuthenticationException(failed.getMessage(), failed));
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 17 with InsufficientAuthenticationException

use of org.springframework.security.authentication.InsufficientAuthenticationException in project midpoint by Evolveum.

the class SecurityEnforcerImpl method decide.

/**
	 * Spring security method. It is practically applicable only for simple cases.
	 */
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if (object instanceof MethodInvocation) {
        MethodInvocation methodInvocation = (MethodInvocation) object;
    // TODO
    } else if (object instanceof FilterInvocation) {
        FilterInvocation filterInvocation = (FilterInvocation) object;
    // TODO
    } else {
        SecurityUtil.logSecurityDeny(object, ": Unknown type of secure object");
        throw new IllegalArgumentException("Unknown type of secure object");
    }
    Object principalObject = authentication.getPrincipal();
    if (!(principalObject instanceof MidPointPrincipal)) {
        if (authentication.getPrincipal() instanceof String && "anonymousUser".equals(principalObject)) {
            SecurityUtil.logSecurityDeny(object, ": Not logged in");
            throw new InsufficientAuthenticationException("Not logged in.");
        }
        throw new IllegalArgumentException("Expected that spring security principal will be of type " + MidPointPrincipal.class.getName() + " but it was " + principalObject.getClass());
    }
    Collection<String> configActions = SecurityUtil.getActions(configAttributes);
    for (String configAction : configActions) {
        boolean isAuthorized;
        try {
            isAuthorized = isAuthorized(configAction, null, null, null, null, null);
        } catch (SchemaException e) {
            throw new SystemException(e.getMessage(), e);
        }
        if (isAuthorized) {
            return;
        }
    }
    SecurityUtil.logSecurityDeny(object, ": Not authorized", null, configActions);
    // Better message is logged.
    throw new AccessDeniedException("Not authorized");
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) SystemException(com.evolveum.midpoint.util.exception.SystemException) MethodInvocation(org.aopalliance.intercept.MethodInvocation) FilterInvocation(org.springframework.security.web.FilterInvocation) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 18 with InsufficientAuthenticationException

use of org.springframework.security.authentication.InsufficientAuthenticationException in project midpoint by Evolveum.

the class MidPointGuiAuthorizationEvaluator method decide.

@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if (!(object instanceof FilterInvocation)) {
        return;
    }
    FilterInvocation filterInvocation = (FilterInvocation) object;
    Collection<ConfigAttribute> guiConfigAttr = new ArrayList<>();
    for (PageUrlMapping urlMapping : PageUrlMapping.values()) {
        addSecurityConfig(filterInvocation, guiConfigAttr, urlMapping.getUrl(), urlMapping.getAction());
    }
    Map<String, DisplayableValue<String>[]> actions = DescriptorLoader.getActions();
    for (Map.Entry<String, DisplayableValue<String>[]> entry : actions.entrySet()) {
        addSecurityConfig(filterInvocation, guiConfigAttr, entry.getKey(), entry.getValue());
    }
    if (configAttributes == null || guiConfigAttr.isEmpty()) {
        return;
    }
    Collection<ConfigAttribute> configAttributesToUse = guiConfigAttr;
    if (guiConfigAttr.isEmpty()) {
        configAttributesToUse = configAttributes;
    }
    try {
        securityEnforcer.decide(authentication, object, configAttributesToUse);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("DECIDE: authentication={}, object={}, configAttributesToUse={}: OK", authentication, object, configAttributesToUse);
        }
    } catch (AccessDeniedException | InsufficientAuthenticationException e) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("DECIDE: authentication={}, object={}, configAttributesToUse={}: {}", authentication, object, configAttributesToUse, e);
        }
        throw e;
    }
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) ConfigAttribute(org.springframework.security.access.ConfigAttribute) ArrayList(java.util.ArrayList) FilterInvocation(org.springframework.security.web.FilterInvocation) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) Map(java.util.Map)

Example 19 with InsufficientAuthenticationException

use of org.springframework.security.authentication.InsufficientAuthenticationException 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)

Aggregations

InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)19 Authentication (org.springframework.security.core.Authentication)13 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)6 ArrayList (java.util.ArrayList)4 AccessDeniedException (org.springframework.security.access.AccessDeniedException)4 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 HashSet (java.util.HashSet)2 Test (org.junit.Test)2 OrcidInvalidScopeException (org.orcid.core.exception.OrcidInvalidScopeException)2 ScopePathType (org.orcid.jaxb.model.message.ScopePathType)2 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)2 GrantedAuthority (org.springframework.security.core.GrantedAuthority)2 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)2 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)2 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)2 InvalidRequestException (org.springframework.security.oauth2.common.exceptions.InvalidRequestException)2 UnsupportedGrantTypeException (org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException)2 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)2