List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest getResponseTypes
public Set<String> getResponseTypes()
From source file:com.acc.oauth2.HybrisApprovalHandler.java
/** * Allows automatic approval for a white list of clients in the implicit grant case. * //from w w w .j ava 2 s . co m * @param authorizationRequest * The authorization request. * @param userAuthentication * the current user authentication * * @return Whether the specified request has been approved by the current user. */ @Override public boolean isApproved(final AuthorizationRequest authorizationRequest, final Authentication userAuthentication) { if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) { return true; } if (!userAuthentication.isAuthenticated()) { return false; } return authorizationRequest.isApproved() || (authorizationRequest.getResponseTypes().contains("token") && autoApproveClients.contains(authorizationRequest.getClientId())); }
From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java
@Override protected void configure() { setControllerPath("oauth"); get("authorize", (req, resp) -> { Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams()); AuthorizationRequest authorizationRequest = requestFactory.createAuthorizationRequest(parameters); Set<String> responseTypes = authorizationRequest.getResponseTypes(); if (!responseTypes.contains("token") && !responseTypes.contains("code")) { throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); }//from w ww . ja v a2 s. c om if (isNull(authorizationRequest.getClientId())) { throw new InvalidClientException("A client id must be provided"); } ClientDetails client = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId()); String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); if (isEmpty(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } authorizationRequest.setRedirectUri(resolvedRedirect); requestValidator.validateScope(authorizationRequest, client); authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, null); boolean approved = userApprovalHandler.isApproved(authorizationRequest, null); authorizationRequest.setApproved(approved); if (authorizationRequest.isApproved()) { if (responseTypes.contains("token")) { resp.status(HttpStatus.FOUND); resp.header(HeaderName.LOCATION, getImplicitGrantResponse(authorizationRequest)); } if (responseTypes.contains("code")) { resp.status(HttpStatus.FOUND); resp.header(HeaderName.LOCATION, getAuthorizationCodeResponse(authorizationRequest)); } } }); }
From source file:com.example.oauth2.loginprovider.oauth.OauthUserApprovalHandler.java
/** * Allows automatic approval for a white list of clients in the implicit grant case. * //from ww w.j a va 2s . c om * @param authorizationRequest The authorization request. * @param userAuthentication the current user authentication * * @return Whether the specified request has been approved by the current user. */ @Override public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { // If we are allowed to check existing approvals this will short circuit the decision if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) { return true; } if (!userAuthentication.isAuthenticated()) { return false; } String flag = authorizationRequest.getApprovalParameters().get(AuthorizationRequest.USER_OAUTH_APPROVAL); boolean approved = flag != null && flag.toLowerCase().equals("true"); return approved || (authorizationRequest.getResponseTypes().contains("token") && autoApproveClients.contains(authorizationRequest.getClientId())); }
From source file:com.blstream.patronage.ctf.security.TokenHandler.java
/** * Allows automatic approval for a white list of clients in the implicit grant case. * * @param authorizationRequest The authorization request. * @param userAuthentication the current user authentication * * @return Whether the specified request has been approved by the current user. *//*w w w . java 2 s .c o m*/ @Override public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { if (logger.isDebugEnabled()) { logger.debug("---- isApproved"); } // If we are allowed to check existing approvals this will short circuit the decision if (useTokenServices && super.isApproved(authorizationRequest, userAuthentication)) { if (logger.isInfoEnabled()) { logger.info("return: true"); } return true; } if (!userAuthentication.isAuthenticated()) { if (logger.isInfoEnabled()) { logger.info("return: false"); } return false; } String flag = authorizationRequest.getApprovalParameters().get(AuthorizationRequest.USER_OAUTH_APPROVAL); boolean approved = flag != null && flag.toLowerCase().equals("true"); return approved || (authorizationRequest.getResponseTypes().contains("token") && autoApproveClients.contains(authorizationRequest.getClientId())); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
@RequestMapping(value = "/oauth/authorize") public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal, HttpServletRequest request) { ClientDetails client;/*from w ww .j a va 2s . co m*/ String clientId; try { clientId = parameters.get("client_id"); client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId()); } catch (NoSuchClientException x) { throw new InvalidClientException(x.getMessage()); } // 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; try { authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters); } catch (DisallowedIdpException x) { return switchIdp(model, client, clientId, request); } Set<String> responseTypes = authorizationRequest.getResponseTypes(); String grantType = deriveGrantTypeFromResponseType(responseTypes); if (!supported_response_types.containsAll(responseTypes)) { throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); } if (authorizationRequest.getClientId() == null) { throw new InvalidClientException("A client id must be provided"); } String resolvedRedirect = ""; try { String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); try { resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); } catch (RedirectMismatchException rme) { throw new RedirectMismatchException( "Invalid redirect " + redirectUriParameter + " did not match one of the registered values"); } if (!StringUtils.hasText(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } boolean isAuthenticated = (principal instanceof Authentication) && ((Authentication) principal).isAuthenticated(); if (!isAuthenticated) { throw new InsufficientAuthenticationException( "User must be authenticated with Spring Security before authorization can be completed."); } if (!(responseTypes.size() > 0)) { return new ModelAndView(new RedirectView( addQueryParameter(addQueryParameter(resolvedRedirect, "error", "invalid_request"), "error_description", "Missing response_type in authorization request"))); } 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); 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") || responseTypes.contains("id_token")) { return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType); } if (responseTypes.contains("code")) { return new ModelAndView( getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal)); } } if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) { return new ModelAndView( new RedirectView(addFragmentComponent(resolvedRedirect, "error=interaction_required"))); } else { // 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(AUTHORIZATION_REQUEST, authorizationRequest); model.put("original_uri", UrlUtils.buildFullRequestUrl(request)); model.put(ORIGINAL_AUTHORIZATION_REQUEST, unmodifiableMap(authorizationRequest)); return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal); } } catch (RedirectMismatchException e) { sessionStatus.setComplete(); throw e; } catch (Exception e) { sessionStatus.setComplete(); logger.debug("Unable to handle /oauth/authorize, internal error", e); if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) { return new ModelAndView( new RedirectView(addFragmentComponent(resolvedRedirect, "error=internal_server_error"))); } throw e; } }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
Map<String, Object> unmodifiableMap(AuthorizationRequest authorizationRequest) { Map<String, Object> authorizationRequestMap = new HashMap<>(); authorizationRequestMap.put(OAuth2Utils.CLIENT_ID, authorizationRequest.getClientId()); authorizationRequestMap.put(OAuth2Utils.STATE, authorizationRequest.getState()); authorizationRequestMap.put(OAuth2Utils.REDIRECT_URI, authorizationRequest.getRedirectUri()); if (authorizationRequest.getResponseTypes() != null) { authorizationRequestMap.put(OAuth2Utils.RESPONSE_TYPE, Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResponseTypes()))); }/*from ww w. j a v a 2 s .co m*/ if (authorizationRequest.getScope() != null) { authorizationRequestMap.put(OAuth2Utils.SCOPE, Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getScope()))); } authorizationRequestMap.put("approved", authorizationRequest.isApproved()); if (authorizationRequest.getResourceIds() != null) { authorizationRequestMap.put("resourceIds", Collections.unmodifiableSet(new HashSet<>(authorizationRequest.getResourceIds()))); } if (authorizationRequest.getAuthorities() != null) { authorizationRequestMap.put("authorities", Collections .unmodifiableSet(new HashSet<GrantedAuthority>(authorizationRequest.getAuthorities()))); } return authorizationRequestMap; }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
public String buildRedirectURI(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken, Authentication authUser) {/*from w ww. j a v a2 s. c o m*/ String requestedRedirect = authorizationRequest.getRedirectUri(); if (accessToken == null) { throw new InvalidRequestException("An implicit grant could not be made"); } StringBuilder url = new StringBuilder(); url.append("token_type=").append(encode(accessToken.getTokenType())); //only append access token if grant_type is implicit //or token is part of the response type if (authorizationRequest.getResponseTypes().contains("token")) { url.append("&access_token=").append(encode(accessToken.getValue())); } if (accessToken instanceof CompositeToken && authorizationRequest.getResponseTypes().contains(CompositeToken.ID_TOKEN)) { url.append("&").append(CompositeToken.ID_TOKEN).append("=") .append(encode(((CompositeToken) accessToken).getIdTokenValue())); } if (authorizationRequest.getResponseTypes().contains("code")) { String code = generateCode(authorizationRequest, authUser); url.append("&code=").append(encode(code)); } String state = authorizationRequest.getState(); if (state != null) { url.append("&state=").append(encode(state)); } Date expiration = accessToken.getExpiration(); if (expiration != null) { long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000; url.append("&expires_in=").append(expires_in); } String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE); if (originalScope == null || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) { url.append("&" + OAuth2Utils.SCOPE + "=") .append(encode(OAuth2Utils.formatParameterList(accessToken.getScope()))); } Map<String, Object> additionalInformation = accessToken.getAdditionalInformation(); for (String key : additionalInformation.keySet()) { Object value = additionalInformation.get(key); if (value != null) { url.append("&" + encode(key) + "=" + encode(value.toString())); } } if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) { HttpHost httpHost = URIUtils.extractHost(URI.create(requestedRedirect)); String sessionState = openIdSessionStateCalculator.calculate( ((UaaPrincipal) authUser.getPrincipal()).getId(), authorizationRequest.getClientId(), httpHost.toURI()); url.append("&session_state=").append(sessionState); } UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestedRedirect); String existingFragment = builder.build(true).getFragment(); if (StringUtils.hasText(existingFragment)) { existingFragment = existingFragment + "&" + url.toString(); } else { existingFragment = url.toString(); } builder.fragment(existingFragment); // Do not include the refresh token (even if there is one) return builder.build(true).toUriString(); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
private boolean isAuthorizationRequestModified(AuthorizationRequest authorizationRequest, Map<String, Object> originalAuthorizationRequest) { if (!ObjectUtils.nullSafeEquals(authorizationRequest.getClientId(), originalAuthorizationRequest.get(OAuth2Utils.CLIENT_ID))) { return true; }// w w w . j av a2s . c o m if (!ObjectUtils.nullSafeEquals(authorizationRequest.getState(), originalAuthorizationRequest.get(OAuth2Utils.STATE))) { return true; } if (!ObjectUtils.nullSafeEquals(authorizationRequest.getRedirectUri(), originalAuthorizationRequest.get(OAuth2Utils.REDIRECT_URI))) { return true; } if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResponseTypes(), originalAuthorizationRequest.get(OAuth2Utils.RESPONSE_TYPE))) { return true; } if (!ObjectUtils.nullSafeEquals(authorizationRequest.isApproved(), originalAuthorizationRequest.get("approved"))) { return true; } if (!ObjectUtils.nullSafeEquals(authorizationRequest.getResourceIds(), originalAuthorizationRequest.get("resourceIds"))) { return true; } if (!ObjectUtils.nullSafeEquals(authorizationRequest.getAuthorities(), originalAuthorizationRequest.get("authorities"))) { return true; } return !ObjectUtils.nullSafeEquals(authorizationRequest.getScope(), originalAuthorizationRequest.get(OAuth2Utils.SCOPE)); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
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) { Map<String, Object> map = new HashMap<>(); map.put("error", translate.getBody()); if (e instanceof UnauthorizedClientException) { map.put("error_message_code", "login.invalid_idp"); }/*w w w. ja v a 2 s . c o m*/ return new ModelAndView(errorPage, map); } AuthorizationRequest authorizationRequest = null; try { authorizationRequest = getAuthorizationRequestForError(webRequest); String requestedRedirectParam = authorizationRequest.getRequestParameters() .get(OAuth2Utils.REDIRECT_URI); String requestedRedirect = redirectResolver.resolveRedirect(requestedRedirectParam, getClientServiceExtention().loadClientByClientId(authorizationRequest.getClientId(), IdentityZoneHolder.get().getId())); 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) { // If an AuthorizationRequest cannot be created from the incoming parameters it must be // an error. OAuth2Exception can be handled this way. Other exceptions will generate a standard 500 // response. return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody())); } }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.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) { if (!(principal instanceof Authentication)) { sessionStatus.setComplete();// ww w .j ava 2s. c o m throw new InsufficientAuthenticationException( "User must be authenticated with Spring Security before authorizing an access token."); } AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get(AUTHORIZATION_REQUEST); if (authorizationRequest == null) { sessionStatus.setComplete(); throw new InvalidRequestException("Cannot approve uninitialized authorization request."); } // Check to ensure the Authorization Request was not modified during the user approval step @SuppressWarnings("unchecked") Map<String, Object> originalAuthorizationRequest = (Map<String, Object>) model .get(ORIGINAL_AUTHORIZATION_REQUEST); if (isAuthorizationRequestModified(authorizationRequest, originalAuthorizationRequest)) { logger.warn("The requested scopes are invalid"); throw new InvalidRequestException("Changes were detected from the original authorization request."); } for (String approvalParameter : approvalParameters.keySet()) { if (approvalParameter.startsWith(SCOPE_PREFIX)) { String scope = approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length()); Set<String> originalScopes = (Set<String>) originalAuthorizationRequest.get("scope"); if (!originalScopes.contains(scope)) { sessionStatus.setComplete(); logger.warn("The requested scopes are invalid"); return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new InvalidScopeException( "The requested scopes are invalid. Please use valid scope names in the request."), false), false, true, false); } } } try { Set<String> responseTypes = authorizationRequest.getResponseTypes(); String grantType = deriveGrantTypeFromResponseType(responseTypes); 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") || responseTypes.contains("id_token")) { return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType) .getView(); } return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal); } finally { sessionStatus.setComplete(); } }