Search in sources :

Example 71 with AuthorizationRequest

use of org.springframework.security.oauth2.provider.AuthorizationRequest in project spring-security-oauth by spring-projects.

the class AuthorizationEndpoint method appendAccessToken.

private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) {
    Map<String, Object> vars = new LinkedHashMap<String, Object>();
    Map<String, String> keys = new HashMap<String, String>();
    if (accessToken == null) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }
    vars.put("access_token", accessToken.getValue());
    vars.put("token_type", accessToken.getTokenType());
    String state = authorizationRequest.getState();
    if (state != null) {
        vars.put("state", state);
    }
    Date expiration = accessToken.getExpiration();
    if (expiration != null) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        vars.put("expires_in", expires_in);
    }
    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (originalScope == null || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope()));
    }
    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (value != null) {
            keys.put("extra_" + key, key);
            vars.put("extra_" + key, value);
        }
    }
    // Do not include the refresh token (even if there is one)
    return append(authorizationRequest.getRedirectUri(), vars, keys, true);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap)

Example 72 with AuthorizationRequest

use of org.springframework.security.oauth2.provider.AuthorizationRequest in project spring-security-oauth by spring-projects.

the class AuthorizationEndpoint method handleException.

private ModelAndView handleException(Exception e, ServletWebRequest webRequest) throws Exception {
    ResponseEntity<OAuth2Exception> translate = getExceptionTranslator().translate(e);
    webRequest.getResponse().setStatus(translate.getStatusCode().value());
    if (e instanceof ClientAuthenticationException || e instanceof RedirectMismatchException) {
        return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody()));
    }
    AuthorizationRequest authorizationRequest = null;
    try {
        authorizationRequest = getAuthorizationRequestForError(webRequest);
        String requestedRedirectParam = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        String requestedRedirect = redirectResolver.resolveRedirect(requestedRedirectParam, getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId()));
        authorizationRequest.setRedirectUri(requestedRedirect);
        String redirect = getUnsuccessfulRedirect(authorizationRequest, translate.getBody(), authorizationRequest.getResponseTypes().contains("token"));
        return new ModelAndView(new RedirectView(redirect, false, true, false));
    } catch (OAuth2Exception ex) {
        // response.
        return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody()));
    }
}
Also used : ClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException) UnapprovedClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 73 with AuthorizationRequest

use of org.springframework.security.oauth2.provider.AuthorizationRequest 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)

Example 74 with AuthorizationRequest

use of org.springframework.security.oauth2.provider.AuthorizationRequest in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationManager method authenticate.

/**
	 * Expects the incoming authentication request to have a principal value that is an access token value (e.g. from an
	 * authorization header). Loads an authentication from the {@link ResourceServerTokenServices} and checks that the
	 * resource id is contained in the {@link AuthorizationRequest} (if one is specified). Also copies authentication
	 * details over from the input to the output (e.g. typically so that the access token value and request details can
	 * be reported later).
	 * 
	 * @param authentication an authentication request containing an access token value as the principal
	 * @return an {@link OAuth2Authentication}
	 * 
	 * @see org.springframework.security.authentication.AuthenticationManager#authenticate(org.springframework.security.core.Authentication)
	 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication == null) {
        throw new InvalidTokenException("Invalid token (token not found)");
    }
    String token = (String) authentication.getPrincipal();
    OAuth2Authentication auth = tokenServices.loadAuthentication(token);
    if (auth == null) {
        throw new InvalidTokenException("Invalid token: " + token);
    }
    Collection<String> resourceIds = auth.getOAuth2Request().getResourceIds();
    if (resourceId != null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(resourceId)) {
        throw new OAuth2AccessDeniedException("Invalid token does not contain resource id (" + resourceId + ")");
    }
    checkClientDetails(auth);
    if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
        // Guard against a cached copy of the same details
        if (!details.equals(auth.getDetails())) {
            // Preserve the authentication details from the one loaded by token services
            details.setDecodedDetails(auth.getDetails());
        }
    }
    auth.setDetails(authentication.getDetails());
    auth.setAuthenticated(true);
    return auth;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 75 with AuthorizationRequest

use of org.springframework.security.oauth2.provider.AuthorizationRequest in project spring-security-oauth by spring-projects.

the class DefaultOAuth2RequestFactory method createAuthorizationRequest.

public AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters) {
    String clientId = authorizationParameters.get(OAuth2Utils.CLIENT_ID);
    String state = authorizationParameters.get(OAuth2Utils.STATE);
    String redirectUri = authorizationParameters.get(OAuth2Utils.REDIRECT_URI);
    Set<String> responseTypes = OAuth2Utils.parseParameterList(authorizationParameters.get(OAuth2Utils.RESPONSE_TYPE));
    Set<String> scopes = extractScopes(authorizationParameters, clientId);
    AuthorizationRequest request = new AuthorizationRequest(authorizationParameters, Collections.<String, String>emptyMap(), clientId, scopes, null, null, false, state, redirectUri, responseTypes);
    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
    request.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    return request;
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails)

Aggregations

AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)66 Test (org.junit.Test)57 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)45 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)42 Authentication (org.springframework.security.core.Authentication)33 HashMap (java.util.HashMap)18 ModelAndView (org.springframework.web.servlet.ModelAndView)16 HashSet (java.util.HashSet)15 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)15 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)14 RedirectView (org.springframework.web.servlet.view.RedirectView)14 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)13 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)12 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)12 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)12 Date (java.util.Date)11 ScopePathType (org.orcid.jaxb.model.message.ScopePathType)10 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)8 TokenGranter (org.springframework.security.oauth2.provider.TokenGranter)8 DefaultUserApprovalHandler (org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler)8