List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest getState
public String getState()
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
public String buildRedirectURI(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken, Authentication authUser) {/*from ww w.ja va 2s . 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.mitre.openid.connect.filter.AuthorizationRequestFilter.java
/** * //from w w w. java 2 s.c om */ @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(); // skip everything that's not an authorize URL if (!requestMatcher.matches(request)) { chain.doFilter(req, res); return; } try { // we have to create our own auth request in order to get at all the parmeters appropriately AuthorizationRequest authRequest = null; ClientDetailsEntity client = null; authRequest = authRequestFactory .createAuthorizationRequest(createRequestMap(request.getParameterMap())); if (!Strings.isNullOrEmpty(authRequest.getClientId())) { client = clientService.loadClientByClientId(authRequest.getClientId()); } // save the login hint to the session // but first check to see if the login hint makes any sense String loginHint = loginHintExtracter.extractHint((String) authRequest.getExtensions().get(LOGIN_HINT)); if (!Strings.isNullOrEmpty(loginHint)) { session.setAttribute(LOGIN_HINT, loginHint); } else { session.removeAttribute(LOGIN_HINT); } if (authRequest.getExtensions().get(PROMPT) != null) { // we have a "prompt" parameter String prompt = (String) authRequest.getExtensions().get(PROMPT); List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt)); if (prompts.contains(PROMPT_NONE)) { // see if the user's logged in Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { // user's been logged in already (by session management) // we're OK, continue without prompting chain.doFilter(req, res); } else { logger.info("Client requested no prompt"); // user hasn't been logged in, we need to "return an error" if (client != null && authRequest.getRedirectUri() != null) { // if we've got a redirect URI then we'll send it String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client); try { URIBuilder uriBuilder = new URIBuilder(url); uriBuilder.addParameter(ERROR, LOGIN_REQUIRED); if (!Strings.isNullOrEmpty(authRequest.getState())) { uriBuilder.addParameter(STATE, authRequest.getState()); // copy the state parameter if one was given } response.sendRedirect(uriBuilder.toString()); return; } catch (URISyntaxException e) { logger.error("Can't build redirect URI for prompt=none, sending error instead", e); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied"); return; } } response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied"); return; } } else if (prompts.contains(PROMPT_LOGIN)) { // first see if the user's already been prompted in this session if (session.getAttribute(PROMPTED) == null) { // user hasn't been PROMPTED yet, we need to check session.setAttribute(PROMPT_REQUESTED, Boolean.TRUE); // see if the user's logged in Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { // user's been logged in already (by session management) // log them out and continue SecurityContextHolder.getContext().setAuthentication(null); chain.doFilter(req, res); } else { // user hasn't been logged in yet, we can keep going since we'll get there chain.doFilter(req, res); } } else { // user has been PROMPTED, we're fine // but first, undo the prompt tag session.removeAttribute(PROMPTED); chain.doFilter(req, res); } } else { // prompt parameter is a value we don't care about, not our business chain.doFilter(req, res); } } else if (authRequest.getExtensions().get(MAX_AGE) != null || (client != null && client.getDefaultMaxAge() != null)) { // default to the client's stored value, check the string parameter Integer max = (client != null ? client.getDefaultMaxAge() : null); String maxAge = (String) authRequest.getExtensions().get(MAX_AGE); if (maxAge != null) { max = Integer.parseInt(maxAge); } if (max != null) { Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP); Date now = new Date(); if (authTime != null) { long seconds = (now.getTime() - authTime.getTime()) / 1000; if (seconds > max) { // session is too old, log the user out and continue SecurityContextHolder.getContext().setAuthentication(null); } } } chain.doFilter(req, res); } else { // no prompt parameter, not our business chain.doFilter(req, res); } } catch (InvalidClientException e) { // we couldn't find the client, move on and let the rest of the system catch the error chain.doFilter(req, res); } }
From source file:org.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java
/** * @param inputParams//w w w. j av a 2 s. c om * @return */ private void processRequestObject(String jwtString, AuthorizationRequest request) { // parse the request object try { JWT jwt = JWTParser.parse(jwtString); if (jwt instanceof SignedJWT) { // it's a signed JWT, check the signature SignedJWT signedJwt = (SignedJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm(); if (client.getRequestObjectSigningAlg() == null || !client.getRequestObjectSigningAlg().equals(alg)) { throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")"); } JWTSigningAndValidationService validator = validators.getValidator(client, alg); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client " + client + " and algorithm " + alg); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } else if (jwt instanceof PlainJWT) { PlainJWT plainJwt = (PlainJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } if (client.getRequestObjectSigningAlg() == null) { throw new InvalidClientException( "Client is not registered for unsigned request objects (no request_object_signing_alg registered)"); } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) { throw new InvalidClientException( "Client is not registered for unsigned request objects (request_object_signing_alg is " + client.getRequestObjectSigningAlg() + ")"); } // if we got here, we're OK, keep processing } else if (jwt instanceof EncryptedJWT) { EncryptedJWT encryptedJWT = (EncryptedJWT) jwt; // decrypt the jwt if we can encryptionService.decryptJwt(encryptedJWT); // TODO: what if the content is a signed JWT? (#525) if (!encryptedJWT.getState().equals(State.DECRYPTED)) { throw new InvalidClientException("Unable to decrypt the request object"); } // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } } /* * NOTE: Claims inside the request object always take precedence over those in the parameter map. */ // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims JWTClaimsSet claims = jwt.getJWTClaimsSet(); Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim(RESPONSE_TYPE)); if (responseTypes != null && !responseTypes.isEmpty()) { if (!responseTypes.equals(request.getResponseTypes())) { logger.info( "Mismatch between request object and regular parameter for response_type, using request object"); } request.setResponseTypes(responseTypes); } String redirectUri = claims.getStringClaim(REDIRECT_URI); if (redirectUri != null) { if (!redirectUri.equals(request.getRedirectUri())) { logger.info( "Mismatch between request object and regular parameter for redirect_uri, using request object"); } request.setRedirectUri(redirectUri); } String state = claims.getStringClaim(STATE); if (state != null) { if (!state.equals(request.getState())) { logger.info( "Mismatch between request object and regular parameter for state, using request object"); } request.setState(state); } String nonce = claims.getStringClaim(NONCE); if (nonce != null) { if (!nonce.equals(request.getExtensions().get(NONCE))) { logger.info( "Mismatch between request object and regular parameter for nonce, using request object"); } request.getExtensions().put(NONCE, nonce); } String display = claims.getStringClaim(DISPLAY); if (display != null) { if (!display.equals(request.getExtensions().get(DISPLAY))) { logger.info( "Mismatch between request object and regular parameter for display, using request object"); } request.getExtensions().put(DISPLAY, display); } String prompt = claims.getStringClaim(PROMPT); if (prompt != null) { if (!prompt.equals(request.getExtensions().get(PROMPT))) { logger.info( "Mismatch between request object and regular parameter for prompt, using request object"); } request.getExtensions().put(PROMPT, prompt); } Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim(SCOPE)); if (scope != null && !scope.isEmpty()) { if (!scope.equals(request.getScope())) { logger.info( "Mismatch between request object and regular parameter for scope, using request object"); } request.setScope(scope); } JsonObject claimRequest = parseClaimRequest(claims.getStringClaim(CLAIMS)); if (claimRequest != null) { if (!claimRequest.equals(parseClaimRequest(request.getExtensions().get(CLAIMS).toString()))) { logger.info( "Mismatch between request object and regular parameter for claims, using request object"); } // we save the string because the object might not be a Java Serializable, and we can parse it easily enough anyway request.getExtensions().put(CLAIMS, claimRequest.toString()); } String loginHint = claims.getStringClaim(LOGIN_HINT); if (loginHint != null) { if (!loginHint.equals(request.getExtensions().get(LOGIN_HINT))) { logger.info( "Mistmatch between request object and regular parameter for login_hint, using requst object"); } request.getExtensions().put(LOGIN_HINT, loginHint); } } catch (ParseException e) { logger.error("ParseException while parsing RequestObject:", e); } }
From source file:org.mitre.openid.connect.ConnectOAuth2RequestFactory.java
/** * @param inputParams// w w w. ja v a 2 s .c o m * @return */ private void processRequestObject(String jwtString, AuthorizationRequest request) { // parse the request object try { JWT jwt = JWTParser.parse(jwtString); // TODO: check parameter consistency, move keys to constants if (jwt instanceof SignedJWT) { // it's a signed JWT, check the signature SignedJWT signedJwt = (SignedJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm(); if (client.getRequestObjectSigningAlg() != null) { if (!client.getRequestObjectSigningAlg().equals(alg)) { throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")"); } } if (alg.equals(JWSAlgorithm.RS256) || alg.equals(JWSAlgorithm.RS384) || alg.equals(JWSAlgorithm.RS512)) { // it's RSA, need to find the JWK URI and fetch the key if (client.getJwksUri() == null) { throw new InvalidClientException( "Client must have a JWKS URI registered to use signed request objects."); } // check JWT signature JwtSigningAndValidationService validator = validators.getValidator(client.getJwksUri()); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client's JWKS URI: " + client.getJwksUri()); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } else if (alg.equals(JWSAlgorithm.HS256) || alg.equals(JWSAlgorithm.HS384) || alg.equals(JWSAlgorithm.HS512)) { // it's HMAC, we need to make a validator based on the client secret JwtSigningAndValidationService validator = getSymmetricValidtor(client); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client's secret: " + client.getClientSecret()); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } } else if (jwt instanceof PlainJWT) { PlainJWT plainJwt = (PlainJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } if (client.getRequestObjectSigningAlg() == null) { throw new InvalidClientException( "Client is not registered for unsigned request objects (no request_object_signing_alg registered)"); } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) { throw new InvalidClientException( "Client is not registered for unsigned request objects (request_object_signing_alg is " + client.getRequestObjectSigningAlg() + ")"); } // if we got here, we're OK, keep processing } else if (jwt instanceof EncryptedJWT) { EncryptedJWT encryptedJWT = (EncryptedJWT) jwt; // decrypt the jwt if we can encryptionService.decryptJwt(encryptedJWT); if (!encryptedJWT.getState().equals(State.DECRYPTED)) { throw new InvalidClientException("Unable to decrypt the request object"); } // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } } /* * Claims precedence order logic: * * if (in Claims): * if (in params): * if (equal): * OK * else (not equal): * error * else (not in params): * add to params * else (not in claims): * we don't care */ // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims ReadOnlyJWTClaimsSet claims = jwt.getJWTClaimsSet(); Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim("response_type")); if (responseTypes != null && !responseTypes.isEmpty()) { if (request.getResponseTypes() == null || request.getResponseTypes().isEmpty()) { // if it's null or empty, we fill in the value with what we were passed request.setResponseTypes(responseTypes); } else if (!request.getResponseTypes().equals(responseTypes)) { // FIXME: throw an error } } String redirectUri = claims.getStringClaim("redirect_uri"); if (redirectUri != null) { if (request.getRedirectUri() == null) { request.setRedirectUri(redirectUri); } else if (!request.getRedirectUri().equals(redirectUri)) { // FIXME: throw an error } } String state = claims.getStringClaim("state"); if (state != null) { if (request.getState() == null) { request.setState(state); } else if (!request.getState().equals(state)) { // FIXME: throw an error } } String nonce = claims.getStringClaim("nonce"); if (nonce != null) { if (request.getExtensions().get("nonce") == null) { request.getExtensions().put("nonce", nonce); } else if (!request.getExtensions().get("nonce").equals(nonce)) { // FIXME: throw an error } } String display = claims.getStringClaim("display"); if (display != null) { if (request.getExtensions().get("display") == null) { request.getExtensions().put("display", display); } else if (!request.getExtensions().get("display").equals(display)) { // FIXME: throw an error } } String prompt = claims.getStringClaim("prompt"); if (prompt != null) { if (request.getExtensions().get("prompt") == null) { request.getExtensions().put("prompt", prompt); } else if (!request.getExtensions().get("prompt").equals(prompt)) { // FIXME: throw an error } } Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope")); if (scope != null && !scope.isEmpty()) { if (request.getScope() == null || request.getScope().isEmpty()) { request.setScope(scope); } else if (!request.getScope().equals(scope)) { // FIXME: throw an error } } JsonObject claimRequest = parseClaimRequest(claims.getStringClaim("claims")); if (claimRequest != null) { if (request.getExtensions().get("claims") == null) { // we save the string because the object might not serialize request.getExtensions().put("claims", claimRequest.toString()); } else if (parseClaimRequest(request.getExtensions().get("claims").toString()) .equals(claimRequest)) { // FIXME: throw an error } } } catch (ParseException e) { logger.error("ParseException while parsing RequestObject:", e); } }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
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"); }/*from w w w . jav a2 s . c o m*/ 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); }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
private String getSuccessfulRedirect(AuthorizationRequest authorizationRequest, String authorizationCode) { if (authorizationCode == null) { throw new IllegalStateException("No authorization code found in the current request scope."); }//from w ww . ja v a2 s. co m Map<String, String> query = new LinkedHashMap<String, String>(); query.put("code", authorizationCode); String state = authorizationRequest.getState(); if (state != null) { query.put("state", state); } return append(authorizationRequest.getRedirectUri(), query, false); }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
private String getUnsuccessfulRedirect(AuthorizationRequest authorizationRequest, OAuth2Exception failure, boolean fragment) { if (authorizationRequest == null || authorizationRequest.getRedirectUri() == null) { // we have no redirect for the user. very sad. throw new UnapprovedClientAuthenticationException("Authorization failure, and no redirect URI.", failure);/* www.j a v a 2 s .co m*/ } Map<String, String> query = new LinkedHashMap<String, String>(); query.put("error", failure.getOAuth2ErrorCode()); query.put("error_description", failure.getMessage()); if (authorizationRequest.getState() != null) { query.put("state", authorizationRequest.getState()); } if (failure.getAdditionalInformation() != null) { for (Map.Entry<String, String> additionalInfo : failure.getAdditionalInformation().entrySet()) { query.put(additionalInfo.getKey(), additionalInfo.getValue()); } } return append(authorizationRequest.getRedirectUri(), query, fragment); }