List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest setApproved
public void setApproved(boolean approved)
From source file:org.cloudfoundry.identity.uaa.oauth.UaaUserApprovalHandler.java
@Override public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { boolean approved = false; String clientId = authorizationRequest.getClientId(); Set<String> scopes = authorizationRequest.getScope(); if (clientDetailsService != null) { try {//from w w w . j a v a 2 s . c o m 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 = tokenServices.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; }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaUserApprovalHandler.java
@Override public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { Map<String, String> approvalParameters = authorizationRequest.getApprovalParameters(); String flag = approvalParameters.get(approvalParameter); boolean approved = flag != null && flag.toLowerCase().equals("true"); authorizationRequest.setApproved(approved); return authorizationRequest; }
From source file:org.orcid.core.oauth.OrcidClientCredentialsChecker.java
public OAuth2Request validateCredentials(String grantType, TokenRequest tokenRequest) { String clientId = tokenRequest.getClientId(); Set<String> scopes = tokenRequest.getScope(); ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId); orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails); validateGrantType(grantType, clientDetails); if (scopes != null) { validateScope(clientDetails, scopes); }//from w w w. j a v a 2 s . co m Map<String, String> authorizationParams = new HashMap<String, String>(); authorizationParams.putAll(tokenRequest.getRequestParameters()); authorizationParams.put(OrcidOauth2Constants.GRANT_TYPE, grantType); authorizationParams.put(OAuth2Utils.SCOPE, StringUtils.join(scopes, ' ')); authorizationParams.put(OAuth2Utils.CLIENT_ID, clientId); AuthorizationRequest authorizationRequest = oAuth2RequestFactory .createAuthorizationRequest(authorizationParams); authorizationRequest.setAuthorities(clientDetails.getAuthorities()); authorizationRequest.setResourceIds(clientDetails.getResourceIds()); authorizationRequest.setApproved(true); return oAuth2RequestFactory.createOAuth2Request(authorizationRequest); }
From source file:org.orcid.core.oauth.service.OrcidTokenStoreServiceImpl.java
private OAuth2Authentication getOAuth2AuthenticationFromDetails(OrcidOauth2TokenDetail details) { if (details != null) { ClientDetailsEntity clientDetailsEntity = clientDetailsEntityCacheManager .retrieve(details.getClientDetailsId()); Authentication authentication = null; AuthorizationRequest request = null; if (clientDetailsEntity != null) { //Check member is not locked orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetailsEntity); Set<String> scopes = OAuth2Utils.parseParameterList(details.getScope()); request = new AuthorizationRequest(clientDetailsEntity.getClientId(), scopes); request.setAuthorities(clientDetailsEntity.getAuthorities()); Set<String> resourceIds = new HashSet<>(); resourceIds.add(details.getResourceId()); request.setResourceIds(resourceIds); request.setApproved(details.isApproved()); ProfileEntity profile = details.getProfile(); if (profile != null) { authentication = new OrcidOauth2UserAuthentication(profile, details.isApproved()); }/* w w w .j a v a 2s . c o m*/ } return new OrcidOAuth2Authentication(request, authentication, details.getTokenValue()); } throw new InvalidTokenException("Token not found"); }
From source file:org.springframework.security.oauth2.provider.approval.ApprovalStoreUserApprovalHandler.java
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 {/*ww w. j a v a2 s . co m*/ ClientDetails client = clientDetailsService.loadClientByClientId(clientId); for (String scope : requestedScopes) { if (client.isAutoApprove(scope) || client.isAutoApprove("all")) { approvedScopes.add(scope); } } if (approvedScopes.containsAll(requestedScopes)) { 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)) { validUserApprovedScopes.add(approval.getScope()); if (approval.getStatus() == ApprovalStatus.APPROVED) { approvedScopes.add(approval.getScope()); } } } if (logger.isDebugEnabled()) { logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes); } // If the requested scopes have already been acted upon by the user, // 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; }
From source file:org.springframework.security.oauth2.provider.approval.ApprovalStoreUserApprovalHandler.java
/** * Requires the authorization request to be explicitly approved, including all individual scopes, and the user to be * authenticated. A scope that was requested in the authorization request can be approved by sending a request * parameter <code>scope.<scopename></code> equal to "true" or "approved" (otherwise it will be assumed to * have been denied). The {@link ApprovalStore} will be updated to reflect the inputs. * // w w w.ja v a 2 s. c o m * @param authorizationRequest The authorization request. * @param userAuthentication the current user authentication * * @return An approved request if all scopes have been approved by the current user. */ public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { // Get the approved scopes Set<String> requestedScopes = authorizationRequest.getScope(); Set<String> approvedScopes = new HashSet<String>(); Set<Approval> approvals = new HashSet<Approval>(); Date expiry = computeExpiry(); // Store the scopes that have been approved / denied Map<String, String> approvalParameters = authorizationRequest.getApprovalParameters(); for (String requestedScope : requestedScopes) { String approvalParameter = scopePrefix + requestedScope; String value = approvalParameters.get(approvalParameter); value = value == null ? "" : value.toLowerCase(); if ("true".equals(value) || value.startsWith("approve")) { approvedScopes.add(requestedScope); approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), requestedScope, expiry, ApprovalStatus.APPROVED)); } else { approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), requestedScope, expiry, ApprovalStatus.DENIED)); } } approvalStore.addApprovals(approvals); boolean approved; authorizationRequest.setScope(approvedScopes); if (approvedScopes.isEmpty() && !requestedScopes.isEmpty()) { approved = false; } else { approved = true; } authorizationRequest.setApproved(approved); return authorizationRequest; }
From source file:org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler.java
@Override public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { boolean approved = false; String clientId = authorizationRequest.getClientId(); Set<String> scopes = authorizationRequest.getScope(); if (clientDetailsService != null) { try {/*from w ww.j a va2s . c o m*/ 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; }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
@RequestMapping(value = "/oauth/authorize") public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal) { logger.info("paramters:" + parameters.toString()); logger.info("model:" + model.toString()); // 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); }//www . java 2 s. c om 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; } }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
@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) { logger.info("paramters2:" + approvalParameters.toString()); logger.info("model:" + model.toString()); logger.info("PID:" + approvalParameters.get("PID")); String PID = (String) approvalParameters.get("PID"); httpSession.setAttribute("PID", PID); logger.info("session PID:" + httpSession.getAttribute("PID")); if (!(principal instanceof Authentication)) { sessionStatus.setComplete();//w ww . j a va2s.c o m 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(); } }