Search in sources :

Example 1 with InsufficientAuthenticationException

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

the class AccessTokenProviderChain method obtainAccessToken.

public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails resource, AccessTokenRequest request) throws UserRedirectRequiredException, AccessDeniedException {
    OAuth2AccessToken accessToken = null;
    OAuth2AccessToken existingToken = null;
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof AnonymousAuthenticationToken) {
        if (!resource.isClientOnly()) {
            throw new InsufficientAuthenticationException("Authentication is required to obtain an access token (anonymous not allowed)");
        }
    }
    if (resource.isClientOnly() || (auth != null && auth.isAuthenticated())) {
        existingToken = request.getExistingToken();
        if (existingToken == null && clientTokenServices != null) {
            existingToken = clientTokenServices.getAccessToken(resource, auth);
        }
        if (existingToken != null) {
            if (existingToken.isExpired()) {
                if (clientTokenServices != null) {
                    clientTokenServices.removeAccessToken(resource, auth);
                }
                OAuth2RefreshToken refreshToken = existingToken.getRefreshToken();
                if (refreshToken != null) {
                    accessToken = refreshAccessToken(resource, refreshToken, request);
                }
            } else {
                accessToken = existingToken;
            }
        }
    }
    if (accessToken == null) {
        // looks like we need to try to obtain a new token.
        accessToken = obtainNewAccessTokenInternal(resource, request);
        if (accessToken == null) {
            throw new IllegalStateException("An OAuth 2 access token must be obtained or an exception thrown.");
        }
    }
    if (clientTokenServices != null && (resource.isClientOnly() || auth != null && auth.isAuthenticated())) {
        clientTokenServices.saveAccessToken(resource, auth, accessToken);
    }
    return accessToken;
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) Authentication(org.springframework.security.core.Authentication) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 2 with InsufficientAuthenticationException

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

the class OAuthUserAuthorizationProcessingFilterTests method testAttemptAuthentication.

/**
	 * tests the attempt to authenticate.
	 */
@Test
public void testAttemptAuthentication() throws Exception {
    UserAuthorizationProcessingFilter filter = new UserAuthorizationProcessingFilter("/");
    OAuthVerifierServices vs = mock(OAuthVerifierServices.class);
    filter.setVerifierServices(vs);
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    Authentication authentication = mock(Authentication.class);
    OAuthProviderTokenServices tokenServices = mock(OAuthProviderTokenServices.class);
    filter.setTokenServices(tokenServices);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    when(request.getParameter("requestToken")).thenReturn("tok");
    OAuthProviderTokenImpl token = new OAuthProviderTokenImpl();
    token.setCallbackUrl("callback");
    when(tokenServices.getToken("tok")).thenReturn(token);
    when(authentication.isAuthenticated()).thenReturn(false);
    try {
        filter.attemptAuthentication(request, response);
        fail();
    } catch (InsufficientAuthenticationException e) {
    }
    verify(request).setAttribute(UserAuthorizationProcessingFilter.CALLBACK_ATTRIBUTE, "callback");
    reset(request);
    when(authentication.isAuthenticated()).thenReturn(true);
    when(request.getParameter("requestToken")).thenReturn("tok");
    when(tokenServices.getToken("tok")).thenReturn(token);
    when(vs.createVerifier()).thenReturn("verifier");
    tokenServices.authorizeRequestToken("tok", "verifier", authentication);
    filter.setTokenServices(tokenServices);
    filter.attemptAuthentication(request, response);
    verify(request).setAttribute(UserAuthorizationProcessingFilter.CALLBACK_ATTRIBUTE, "callback");
    verify(request).setAttribute(UserAuthorizationProcessingFilter.VERIFIER_ATTRIBUTE, "verifier");
    SecurityContextHolder.getContext().setAuthentication(null);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuthProviderTokenServices(org.springframework.security.oauth.provider.token.OAuthProviderTokenServices) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthVerifierServices(org.springframework.security.oauth.provider.verifier.OAuthVerifierServices) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) OAuthProviderTokenImpl(org.springframework.security.oauth.provider.token.OAuthProviderTokenImpl) Test(org.junit.Test)

Example 3 with InsufficientAuthenticationException

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

the class UserAuthorizationProcessingFilter method attemptAuthentication.

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    String requestToken = request.getParameter(getTokenParameterName());
    if (requestToken == null) {
        throw new InvalidOAuthParametersException("An OAuth token id is required.");
    }
    OAuthProviderToken token = getTokenServices().getToken(requestToken);
    if (token == null) {
        throw new InvalidOAuthTokenException("No callback value has been provided for request token " + requestToken + ".");
    }
    String callbackURL = token.getCallbackUrl();
    if (isRequire10a() && callbackURL == null) {
        throw new InvalidOAuthTokenException("No callback value has been provided for request token " + requestToken + ".");
    }
    if (callbackURL != null) {
        request.setAttribute(CALLBACK_ATTRIBUTE, callbackURL);
    }
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || !authentication.isAuthenticated()) {
        throw new InsufficientAuthenticationException("User must be authenticated before authorizing a request token.");
    }
    String verifier = getVerifierServices().createVerifier();
    request.setAttribute(VERIFIER_ATTRIBUTE, verifier);
    getTokenServices().authorizeRequestToken(requestToken, verifier, authentication);
    return authentication;
}
Also used : OAuthProviderToken(org.springframework.security.oauth.provider.token.OAuthProviderToken) InvalidOAuthParametersException(org.springframework.security.oauth.provider.InvalidOAuthParametersException) Authentication(org.springframework.security.core.Authentication) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) InvalidOAuthTokenException(org.springframework.security.oauth.provider.token.InvalidOAuthTokenException)

Example 4 with InsufficientAuthenticationException

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

the class TokenEndpoint method getClientId.

/**
	 * @param principal the currently authentication principal
	 * @return a client id if there is one in the principal
	 */
protected String getClientId(Principal principal) {
    Authentication client = (Authentication) principal;
    if (!client.isAuthenticated()) {
        throw new InsufficientAuthenticationException("The client is not authenticated.");
    }
    String clientId = client.getName();
    if (client instanceof OAuth2Authentication) {
        // Might be a client and user combined authentication
        clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();
    }
    return clientId;
}
Also used : 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 5 with InsufficientAuthenticationException

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

the class TokenEndpoint method postAccessToken.

@RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter.");
    }
    String clientId = getClientId(principal);
    ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
    if (clientId != null && !clientId.equals("")) {
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }
    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }
    if (!StringUtils.hasText(tokenRequest.getGrantType())) {
        throw new InvalidRequestException("Missing grant type");
    }
    if (tokenRequest.getGrantType().equals("implicit")) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }
    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            logger.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }
    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }
    OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
    }
    return getResponse(token);
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException) 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