Search in sources :

Example 36 with Approval

use of org.springframework.security.oauth2.provider.approval.Approval in project MaxKey by dromara.

the class JwtTokenStore method remove.

private void remove(String token) {
    if (approvalStore != null) {
        OAuth2Authentication auth = readAuthentication(token);
        String clientId = auth.getOAuth2Request().getClientId();
        Authentication user = auth.getUserAuthentication();
        if (user != null) {
            Collection<Approval> approvals = new ArrayList<Approval>();
            for (String scope : auth.getOAuth2Request().getScope()) {
                approvals.add(new Approval(user.getName(), clientId, scope, new Date(), ApprovalStatus.APPROVED));
            }
            approvalStore.revokeApprovals(approvals);
        }
    }
}
Also used : OAuth2Authentication(org.maxkey.authz.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.maxkey.authz.oauth2.provider.OAuth2Authentication) ArrayList(java.util.ArrayList) Approval(org.maxkey.authz.oauth2.provider.approval.Approval) Date(java.util.Date)

Example 37 with Approval

use of org.springframework.security.oauth2.provider.approval.Approval in project MaxKey by dromara.

the class OAuth20AccessConfirmationEndpoint method getAccessConfirmation.

/**
 * getAccessConfirmation.
 * @param model  Map
 * @return
 * throws Exception
 */
@RequestMapping(OAuth2Constants.ENDPOINT.ENDPOINT_APPROVAL_CONFIRM)
public ModelAndView getAccessConfirmation(@RequestParam Map<String, Object> model) {
    try {
        model.remove("authorizationRequest");
        // Map<String, Object> model
        AuthorizationRequest clientAuth = (AuthorizationRequest) WebContext.getAttribute("authorizationRequest");
        ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId(), true);
        Apps app = (Apps) WebContext.getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP);
        WebContext.setAttribute(app.getId(), app.getIcon());
        model.put("auth_request", clientAuth);
        model.put("client", client);
        model.put("app", app);
        model.put("oauth_version", "oauth 2.0");
        Map<String, String> scopes = new LinkedHashMap<String, String>();
        for (String scope : clientAuth.getScope()) {
            scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + scope, "false");
        }
        String principal = ((SigninPrincipal) WebContext.getAuthentication().getPrincipal()).getUsername();
        for (Approval approval : approvalStore.getApprovals(principal, client.getClientId())) {
            if (clientAuth.getScope().contains(approval.getScope())) {
                scopes.put(OAuth2Constants.PARAMETER.SCOPE_PREFIX + approval.getScope(), approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false");
            }
        }
        model.put("scopes", scopes);
        if (!model.containsKey(OAuth2Constants.PARAMETER.APPROVAL_PROMPT)) {
            model.put(OAuth2Constants.PARAMETER.APPROVAL_PROMPT, client.getApprovalPrompt());
        }
    } catch (Exception e) {
        _logger.debug("OAuth Access Confirmation process error.", e);
    }
    ModelAndView modelAndView = new ModelAndView("authorize/oauth_access_confirmation");
    _logger.trace("Confirmation details ");
    for (Object key : model.keySet()) {
        _logger.trace("key " + key + "=" + model.get(key));
    }
    modelAndView.addObject("model", model);
    return modelAndView;
}
Also used : AuthorizationRequest(org.maxkey.authz.oauth2.provider.AuthorizationRequest) ClientDetails(org.maxkey.entity.apps.oauth2.provider.ClientDetails) SigninPrincipal(org.maxkey.authn.SigninPrincipal) ModelAndView(org.springframework.web.servlet.ModelAndView) Approval(org.maxkey.authz.oauth2.provider.approval.Approval) Apps(org.maxkey.entity.apps.Apps) LinkedHashMap(java.util.LinkedHashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 38 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");
    }
    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));
            }
        }
        // Store authorizationRequest AND an immutable Map of authorizationRequest in session
        // which will be used to validate against in approveOrDeny()
        model.put(AUTHORIZATION_REQUEST_ATTR_NAME, authorizationRequest);
        model.put(ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME, unmodifiableMap(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 39 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 40 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);
    if (logger.isDebugEnabled()) {
        logger.debug("Existing access token=" + accessToken);
    }
    if (accessToken != null && !accessToken.isExpired()) {
        if (logger.isDebugEnabled()) {
            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

AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)46 Approval (org.cloudfoundry.identity.uaa.approval.Approval)43 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)34 Authentication (org.springframework.security.core.Authentication)27 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)27 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)25 Test (org.junit.Test)24 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)22 Date (java.util.Date)21 Test (org.junit.jupiter.api.Test)19 IsEmptyString.isEmptyString (org.hamcrest.text.IsEmptyString.isEmptyString)16 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)15 Approval (org.springframework.security.oauth2.provider.approval.Approval)15 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)9 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 Map (java.util.Map)8 HashMap (java.util.HashMap)7 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)7 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)7 AuthorizationCodeResourceDetails (org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails)7