Search in sources :

Example 11 with InsufficientAuthenticationException

use of org.springframework.security.authentication.InsufficientAuthenticationException in project dhis2-core by dhis2.

the class SpringSecurityActionAccessResolver method hasAccess.

// -------------------------------------------------------------------------
// ActionAccessResolver implementation
// -------------------------------------------------------------------------
@Override
public boolean hasAccess(String module, String name) {
    // ---------------------------------------------------------------------
    // Get ObjectDefinitionSource
    // ---------------------------------------------------------------------
    Configuration config = Dispatcher.getInstance().getConfigurationManager().getConfiguration();
    PackageConfig packageConfig = config.getPackageConfig(module);
    if (packageConfig == null) {
        throw new IllegalArgumentException("Module doesn't exist: '" + module + "'");
    }
    ActionConfig actionConfig = packageConfig.getActionConfigs().get(name);
    if (actionConfig == null) {
        throw new IllegalArgumentException("Module " + module + " doesn't have an action named: '" + name + "'");
    }
    SecurityMetadataSource securityMetadataSource = requiredAuthoritiesProvider.createSecurityMetadataSource(actionConfig);
    // ---------------------------------------------------------------------
    // Test access
    // ---------------------------------------------------------------------
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    try {
        if (securityMetadataSource.getAttributes(actionConfig) != null) {
            if (authentication == null || !authentication.isAuthenticated()) {
                return false;
            }
            accessDecisionManager.decide(authentication, actionConfig, securityMetadataSource.getAttributes(actionConfig));
        }
        log.debug("Access to [" + module + ", " + name + "]: TRUE");
        return true;
    } catch (AccessDeniedException e) {
        log.debug("Access to [" + module + ", " + name + "]: FALSE (access denied)");
        return false;
    } catch (InsufficientAuthenticationException e) {
        log.debug("Access to [" + module + ", " + name + "]: FALSE (insufficient authentication)");
        return false;
    }
}
Also used : ActionConfig(com.opensymphony.xwork2.config.entities.ActionConfig) AccessDeniedException(org.springframework.security.access.AccessDeniedException) Configuration(com.opensymphony.xwork2.config.Configuration) SecurityMetadataSource(org.springframework.security.access.SecurityMetadataSource) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) PackageConfig(com.opensymphony.xwork2.config.entities.PackageConfig)

Example 12 with InsufficientAuthenticationException

use of org.springframework.security.authentication.InsufficientAuthenticationException in project dhis2-core by dhis2.

the class LogicalOrAccessDecisionManager method decide.

// -------------------------------------------------------------------------
// Interface implementation
// -------------------------------------------------------------------------
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    AccessDeniedException ade = null;
    InsufficientAuthenticationException iae = null;
    for (AccessDecisionManager accessDecisionManager : accessDecisionManagers) {
        if (accessDecisionManager.supports(object.getClass())) {
            try {
                accessDecisionManager.decide(authentication, object, configAttributes);
                LOG.debug("ACCESS GRANTED [" + object.toString() + "]");
                return;
            } catch (AccessDeniedException e) {
                ade = e;
            } catch (InsufficientAuthenticationException e) {
                iae = e;
            }
        }
    }
    LOG.debug("ACCESS DENIED [" + object.toString() + "]");
    if (ade != null) {
        throw ade;
    }
    if (iae != null) {
        throw iae;
    }
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) AccessDecisionManager(org.springframework.security.access.AccessDecisionManager) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 13 with InsufficientAuthenticationException

use of org.springframework.security.authentication.InsufficientAuthenticationException in project ORCID-Source by ORCID.

the class OrcidClientCredentialEndPointDelegatorImpl method obtainOauth2Token.

@Transactional
public Response obtainOauth2Token(String authorization, MultivaluedMap<String, String> formParams) {
    String code = formParams.getFirst("code");
    String clientId = formParams.getFirst(OrcidOauth2Constants.CLIENT_ID_PARAM);
    String state = formParams.getFirst(OrcidOauth2Constants.STATE_PARAM);
    String redirectUri = formParams.getFirst(OrcidOauth2Constants.REDIRECT_URI_PARAM);
    String refreshToken = formParams.getFirst(OrcidOauth2Constants.REFRESH_TOKEN);
    String scopeList = formParams.getFirst(OrcidOauth2Constants.SCOPE_PARAM);
    String grantType = formParams.getFirst(OrcidOauth2Constants.GRANT_TYPE);
    Boolean revokeOld = formParams.containsKey(OrcidOauth2Constants.REVOKE_OLD) ? Boolean.valueOf(formParams.getFirst(OrcidOauth2Constants.REVOKE_OLD)) : true;
    Long expiresIn = calculateExpiresIn(formParams);
    String bearerToken = null;
    Set<String> scopes = new HashSet<String>();
    if (StringUtils.isNotEmpty(scopeList)) {
        scopes = OAuth2Utils.parseParameterList(scopeList);
    }
    if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
        if (!PojoUtil.isEmpty(authorization)) {
            if ((authorization.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
                String authHeaderValue = authorization.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                bearerToken = authHeaderValue;
                if (PojoUtil.isEmpty(bearerToken)) {
                    throw new IllegalArgumentException("Refresh token request doesnt include the authorization");
                }
            }
        }
    }
    LOGGER.info("OAuth2 authorization requested: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
    Authentication client = getClientAuthentication();
    if (!client.isAuthenticated()) {
        LOGGER.info("Not authenticated for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new InsufficientAuthenticationException(localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
    }
    /**
         * Patch, update any orcid-grants scope to funding scope
         * */
    for (String scope : scopes) {
        if (scope.contains("orcid-grants")) {
            String newScope = scope.replace("orcid-grants", "funding");
            LOGGER.info("Client {} provided a grants scope {} which will be updated to {}", new Object[] { clientId, scope, newScope });
            scopes.remove(scope);
            scopes.add(newScope);
        }
    }
    try {
        if (scopes != null) {
            List<String> toRemove = new ArrayList<String>();
            for (String scope : scopes) {
                ScopePathType scopeType = ScopePathType.fromValue(scope);
                if (scopeType.isInternalScope()) {
                    // You should not allow any internal scope here! go away!
                    String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
                    throw new OrcidInvalidScopeException(message);
                } else if (OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
                    if (!scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                } else {
                    if (scopeType.isClientCreditalScope())
                        toRemove.add(scope);
                }
            }
            for (String remove : toRemove) {
                scopes.remove(remove);
            }
        }
    } catch (IllegalArgumentException iae) {
        String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
        throw new OrcidInvalidScopeException(message);
    }
    OAuth2AccessToken token = generateToken(client, scopes, code, redirectUri, grantType, refreshToken, state, bearerToken, revokeOld, expiresIn);
    return getResponse(token);
}
Also used : OrcidInvalidScopeException(org.orcid.core.exception.OrcidInvalidScopeException) ArrayList(java.util.ArrayList) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) AbstractEndpoint(org.springframework.security.oauth2.provider.endpoint.AbstractEndpoint) ScopePathType(org.orcid.jaxb.model.message.ScopePathType) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 14 with InsufficientAuthenticationException

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

the class OAuthConsumerProcessingFilter method doFilter.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    Set<String> accessTokenDeps = getAccessTokenDependencies(request, response, chain);
    if (!accessTokenDeps.isEmpty()) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (isRequireAuthenticated() && !authentication.isAuthenticated()) {
            throw new InsufficientAuthenticationException("An authenticated principal must be present.");
        }
        OAuthSecurityContext context = OAuthSecurityContextHolder.getContext();
        if (context == null) {
            throw new IllegalStateException("No OAuth security context has been established. Unable to access resources.");
        }
        Map<String, OAuthConsumerToken> accessTokens = context.getAccessTokens();
        for (String dependency : accessTokenDeps) {
            if (!accessTokens.containsKey(dependency)) {
                throw new AccessTokenRequiredException(getProtectedResourceDetailsService().loadProtectedResourceDetailsById(dependency));
            }
        }
        chain.doFilter(request, response);
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No access token dependencies for request.");
        }
        chain.doFilter(servletRequest, servletResponse);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Authentication(org.springframework.security.core.Authentication) AccessTokenRequiredException(org.springframework.security.oauth.consumer.AccessTokenRequiredException) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthSecurityContext(org.springframework.security.oauth.consumer.OAuthSecurityContext) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken)

Example 15 with InsufficientAuthenticationException

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

the class AuthorizationEndpoint method approveOrDeny.

@RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model, SessionStatus sessionStatus, Principal principal) {
    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();
        throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorizing an access token.");
    }
    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
    if (authorizationRequest == null) {
        sessionStatus.setComplete();
        throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
    }
    try {
        Set<String> responseTypes = authorizationRequest.getResponseTypes();
        authorizationRequest.setApprovalParameters(approvalParameters);
        authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest, (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);
        if (authorizationRequest.getRedirectUri() == null) {
            sessionStatus.setComplete();
            throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
        }
        if (!authorizationRequest.isApproved()) {
            return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new UserDeniedAuthorizationException("User denied access"), responseTypes.contains("token")), false, true, false);
        }
        if (responseTypes.contains("token")) {
            return getImplicitGrantResponse(authorizationRequest).getView();
        }
        return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
    } finally {
        sessionStatus.setComplete();
    }
}
Also used : UserDeniedAuthorizationException(org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) RedirectView(org.springframework.web.servlet.view.RedirectView) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

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