Search in sources :

Example 11 with Approval

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

the class JwtTokenStoreTests method testReadRefreshTokenForUnapprovedScope.

@Test
public void testReadRefreshTokenForUnapprovedScope() throws Exception {
    tokenStore.setApprovalStore(approvalStore);
    approvalStore.addApprovals(Collections.singleton(new Approval("test", "id", "write", new Date(), ApprovalStatus.APPROVED)));
    assertEquals(1, approvalStore.getApprovals("test", "id").size());
    assertEquals(null, tokenStore.readRefreshToken(expectedOAuth2RefreshToken.getValue()));
}
Also used : Approval(org.springframework.security.oauth2.provider.approval.Approval) Date(java.util.Date) Test(org.junit.Test)

Example 12 with Approval

use of org.springframework.security.oauth2.provider.approval.Approval 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 13 with Approval

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

the class ApprovalStoreUserApprovalHandler method checkForPreApproval.

public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    String clientId = authorizationRequest.getClientId();
    Collection<String> requestedScopes = authorizationRequest.getScope();
    Set<String> approvedScopes = new HashSet<String>();
    Set<String> validUserApprovedScopes = new HashSet<String>();
    if (clientDetailsService != null) {
        try {
            ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
            for (String scope : requestedScopes) {
                if (client.isAutoApprove(scope)) {
                    approvedScopes.add(scope);
                }
            }
            if (approvedScopes.containsAll(requestedScopes)) {
                // gh-877 - if all scopes are auto approved, approvals still need to be added to the approval store.
                Set<Approval> approvals = new HashSet<Approval>();
                Date expiry = computeExpiry();
                for (String approvedScope : approvedScopes) {
                    approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), approvedScope, expiry, ApprovalStatus.APPROVED));
                }
                approvalStore.addApprovals(approvals);
                authorizationRequest.setApproved(true);
                return authorizationRequest;
            }
        } catch (ClientRegistrationException e) {
            logger.warn("Client registration problem prevent autoapproval check for client=" + clientId);
        }
    }
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up user approved authorizations for ");
        builder.append("client_id=" + clientId);
        builder.append(" and username=" + userAuthentication.getName());
        logger.debug(builder.toString());
    }
    // Find the stored approvals for that user and client
    Collection<Approval> userApprovals = approvalStore.getApprovals(userAuthentication.getName(), clientId);
    // Look at the scopes and see if they have expired
    Date today = new Date();
    for (Approval approval : userApprovals) {
        if (approval.getExpiresAt().after(today)) {
            if (approval.getStatus() == ApprovalStatus.APPROVED) {
                validUserApprovedScopes.add(approval.getScope());
                approvedScopes.add(approval.getScope());
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes);
    }
    // this request is approved
    if (validUserApprovedScopes.containsAll(requestedScopes)) {
        approvedScopes.retainAll(requestedScopes);
        // Set only the scopes that have been approved by the user
        authorizationRequest.setScope(approvedScopes);
        authorizationRequest.setApproved(true);
    }
    return authorizationRequest;
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) ClientRegistrationException(org.springframework.security.oauth2.provider.ClientRegistrationException) Date(java.util.Date) HashSet(java.util.HashSet)

Example 14 with Approval

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

the class TokenApprovalStore method getApprovals.

/**
	 * Extract the implied approvals from any tokens associated with the user and client id supplied.
	 * 
	 * @see org.springframework.security.oauth2.provider.approval.ApprovalStore#getApprovals(java.lang.String,
	 * java.lang.String)
	 */
@Override
public Collection<Approval> getApprovals(String userId, String clientId) {
    Collection<Approval> result = new HashSet<Approval>();
    Collection<OAuth2AccessToken> tokens = store.findTokensByClientIdAndUserName(clientId, userId);
    for (OAuth2AccessToken token : tokens) {
        OAuth2Authentication authentication = store.readAuthentication(token);
        if (authentication != null) {
            Date expiresAt = token.getExpiration();
            for (String scope : token.getScope()) {
                result.add(new Approval(userId, clientId, scope, expiresAt, ApprovalStatus.APPROVED));
            }
        }
    }
    return result;
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Date(java.util.Date) HashSet(java.util.HashSet)

Example 15 with Approval

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

the class TokenStoreUserApprovalHandler method checkForPreApproval.

@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    boolean approved = false;
    String clientId = authorizationRequest.getClientId();
    Set<String> scopes = authorizationRequest.getScope();
    if (clientDetailsService != null) {
        try {
            ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
            approved = true;
            for (String scope : scopes) {
                if (!client.isAutoApprove(scope)) {
                    approved = false;
                }
            }
            if (approved) {
                authorizationRequest.setApproved(true);
                return authorizationRequest;
            }
        } catch (ClientRegistrationException e) {
            logger.warn("Client registration problem prevent autoapproval check for client=" + clientId);
        }
    }
    OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest);
    OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, userAuthentication);
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up existing token for ");
        builder.append("client_id=" + clientId);
        builder.append(", scope=" + scopes);
        builder.append(" and username=" + userAuthentication.getName());
        logger.debug(builder.toString());
    }
    OAuth2AccessToken accessToken = tokenStore.getAccessToken(authentication);
    logger.debug("Existing access token=" + accessToken);
    if (accessToken != null && !accessToken.isExpired()) {
        logger.debug("User already approved with token=" + accessToken);
        // A token was already granted and is still valid, so this is already approved
        approved = true;
    } else {
        logger.debug("Checking explicit approval");
        approved = userAuthentication.isAuthenticated() && approved;
    }
    authorizationRequest.setApproved(approved);
    return authorizationRequest;
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) ClientRegistrationException(org.springframework.security.oauth2.provider.ClientRegistrationException)

Aggregations

Test (org.junit.Test)12 Date (java.util.Date)10 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)9 Approval (org.springframework.security.oauth2.provider.approval.Approval)7 UserRedirectRequiredException (org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)6 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)6 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)5 AccessTokenRequest (org.springframework.security.oauth2.client.token.AccessTokenRequest)4 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)4 HashSet (java.util.HashSet)3 Authentication (org.springframework.security.core.Authentication)3 UserApprovalRequiredException (org.springframework.security.oauth2.client.resource.UserApprovalRequiredException)3 AuthorizationCodeResourceDetails (org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails)3 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)3 ClientRegistrationException (org.springframework.security.oauth2.provider.ClientRegistrationException)3 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)3 ModelAndView (org.springframework.web.servlet.ModelAndView)3 HashMap (java.util.HashMap)2 HttpHeaders (org.springframework.http.HttpHeaders)2 UnsupportedResponseTypeException (org.springframework.security.oauth2.common.exceptions.UnsupportedResponseTypeException)2