Search in sources :

Example 6 with InsufficientAuthenticationException

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

the class AuthorizationEndpoint method authorize.

@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal) {
    // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
    // query off of the authorization request instead of referring back to the parameters map. The contents of the
    // parameters map will be stored without change in the AuthorizationRequest object once it is created.
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
    Set<String> responseTypes = authorizationRequest.getResponseTypes();
    if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
        throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
    }
    if (authorizationRequest.getClientId() == null) {
        throw new InvalidClientException("A client id must be provided");
    }
    try {
        if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
            throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorization can be completed.");
        }
        ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());
        // The resolved redirect URI is either the redirect_uri from the parameters or the one from
        // clientDetails. Either way we need to store it on the AuthorizationRequest.
        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        if (!StringUtils.hasText(resolvedRedirect)) {
            throw new RedirectMismatchException("A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }
        authorizationRequest.setRedirectUri(resolvedRedirect);
        // We intentionally only validate the parameters requested by the client (ignoring any data that may have
        // been added to the request by the manager).
        oauth2RequestValidator.validateScope(authorizationRequest, client);
        // Some systems may allow for approval decisions to be remembered or approved by default. Check for
        // such logic here, and set the approved flag on the authorization request accordingly.
        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, (Authentication) principal);
        // TODO: is this call necessary?
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);
        // Validation is all done, so we can check for auto approval...
        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token")) {
                return getImplicitGrantResponse(authorizationRequest);
            }
            if (responseTypes.contains("code")) {
                return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }
        // Place auth request into the model so that it is stored in the session
        // for approveOrDeny to use. That way we make sure that auth request comes from the session,
        // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
        model.put("authorizationRequest", authorizationRequest);
        return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
    } catch (RuntimeException e) {
        sessionStatus.setComplete();
        throw e;
    }
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) ModelAndView(org.springframework.web.servlet.ModelAndView) UnsupportedResponseTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedResponseTypeException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with InsufficientAuthenticationException

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

the class ImplicitTokenGranter method getOAuth2Authentication.

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest clientToken) {
    Authentication userAuth = SecurityContextHolder.getContext().getAuthentication();
    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InsufficientAuthenticationException("There is no currently logged in user");
    }
    Assert.state(clientToken instanceof ImplicitTokenRequest, "An ImplicitTokenRequest is required here. Caller needs to wrap the TokenRequest.");
    OAuth2Request requestForStorage = ((ImplicitTokenRequest) clientToken).getOAuth2Request();
    return new OAuth2Authentication(requestForStorage, userAuth);
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 8 with InsufficientAuthenticationException

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

the class OAuthErrorUtilsTest method testGetOAuthErrorForInsufficientAuthenticationException.

@Test
public void testGetOAuthErrorForInsufficientAuthenticationException() {
    OAuthError error = OAuthErrorUtils.getOAuthError(new InsufficientAuthenticationException("message here"));
    assertEquals(OAuthError.UNAUTHORIZED_CLIENT, error.getError());
    assertEquals(Status.UNAUTHORIZED, error.getResponseStatus());
    assertEquals("message here", error.getErrorDescription());
}
Also used : InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) Test(org.junit.Test)

Example 9 with InsufficientAuthenticationException

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

the class InternalClientCredentialEndPointDelegatorImpl method obtainOauth2Token.

@Override
@Transactional
public Response obtainOauth2Token(String authorization, MultivaluedMap<String, String> formParams) {
    String clientId = formParams.getFirst("client_id");
    String scopeList = formParams.getFirst("scope");
    String grantType = formParams.getFirst("grant_type");
    // Verify it is a client_credentials grant type request
    if (!OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
        Object[] params = { grantType };
        throw new UnsupportedGrantTypeException(localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    Authentication client = getClientAuthentication();
    if (!client.isAuthenticated()) {
        LOGGER.info("Not authenticated for OAuth2: clientId={}, grantType={}, scope={}", new Object[] { clientId, grantType, scopeList });
        throw new InsufficientAuthenticationException(localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
    }
    Set<String> scopes = new HashSet<String>();
    if (StringUtils.isNotEmpty(scopeList)) {
        scopes = OAuth2Utils.parseParameterList(scopeList);
    }
    // Verify it is requesting an internal scope
    HashSet<String> filteredScopes = new HashSet<String>();
    for (String scope : scopes) {
        ScopePathType scopeType = ScopePathType.fromValue(scope);
        if (scopeType.isInternalScope()) {
            filteredScopes.add(scope);
        }
    }
    if (filteredScopes.isEmpty()) {
        String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
        throw new OrcidInvalidScopeException(message);
    }
    OAuth2AccessToken token = generateToken(client, scopes, null, null, grantType, null, null, null, false, 0L);
    return getResponse(token);
}
Also used : ScopePathType(org.orcid.jaxb.model.message.ScopePathType) Authentication(org.springframework.security.core.Authentication) OrcidInvalidScopeException(org.orcid.core.exception.OrcidInvalidScopeException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 10 with InsufficientAuthenticationException

use of org.springframework.security.authentication.InsufficientAuthenticationException in project libresonic by Libresonic.

the class JWTAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth;
    if (authentication.getCredentials() == null || !(authentication.getCredentials() instanceof String)) {
        logger.error("Credentials not present");
        return null;
    }
    String rawToken = (String) auth.getCredentials();
    DecodedJWT token = JWTSecurityService.verify(jwtKey, rawToken);
    Claim path = token.getClaim(JWTSecurityService.CLAIM_PATH);
    authentication.setAuthenticated(true);
    // TODO:AD This is super unfortunate, but not sure there is a better way when using JSP
    if (StringUtils.contains(authentication.getRequestedPath(), "/WEB-INF/jsp/")) {
        logger.warn("BYPASSING AUTH FOR WEB-INF page");
    } else if (!roughlyEqual(path.asString(), authentication.getRequestedPath())) {
        throw new InsufficientAuthenticationException("Credentials not valid for path " + authentication.getRequestedPath() + ". They are valid for " + path.asString());
    }
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("IS_AUTHENTICATED_FULLY"));
    authorities.add(new SimpleGrantedAuthority("ROLE_TEMP"));
    return new JWTAuthenticationToken(authorities, rawToken, authentication.getRequestedPath());
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

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