List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest AuthorizationRequest
public AuthorizationRequest(String clientId, Collection<String> scopes)
From source file:com.ge.predix.uaa.token.lib.FastTokenServices.java
@Override public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException { Map<String, Object> claims; try {//from w w w . ja v a2 s . co m claims = getTokenClaims(accessToken); } catch (IllegalArgumentException e) { LOG.error("Malformed Access Token: " + accessToken); LOG.error(e); throw new InvalidTokenException("Malformed Access Token", e); } String iss = getIssuerFromClaims(claims); verifyIssuer(iss); // check if the singerProvider for that issuer has already in the cache SignatureVerifier verifier = this.tokenKeys.get(iss); if (null == verifier) { String tokenKey = getTokenKey(iss); verifier = getVerifier(tokenKey); this.tokenKeys.put(iss, verifier); } JwtHelper.decodeAndVerify(accessToken, verifier); verifyTimeWindow(claims); Assert.state(claims.containsKey("client_id"), "Client id must be present in response from auth server"); String remoteClientId = (String) claims.get("client_id"); Set<String> scope = new HashSet<>(); if (claims.containsKey("scope")) { @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) claims.get("scope"); scope.addAll(values); } AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope); if (claims.containsKey("resource_ids") || claims.containsKey("client_authorities")) { Set<String> resourceIds = new HashSet<>(); if (claims.containsKey("resource_ids")) { @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) claims.get("resource_ids"); resourceIds.addAll(values); } Set<GrantedAuthority> clientAuthorities = new HashSet<>(); if (claims.containsKey("client_authorities")) { @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) claims.get("client_authorities"); clientAuthorities.addAll(getAuthorities(values)); } BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId(remoteClientId); clientDetails.setResourceIds(resourceIds); clientDetails.setAuthorities(clientAuthorities); clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails); } Map<String, String> requestParameters = new HashMap<>(); if (isStoreClaims()) { for (Map.Entry<String, Object> entry : claims.entrySet()) { if (entry.getValue() != null && entry.getValue() instanceof String) { requestParameters.put(entry.getKey(), (String) entry.getValue()); } } } if (claims.containsKey(Claims.ADDITIONAL_AZ_ATTR)) { try { requestParameters.put(Claims.ADDITIONAL_AZ_ATTR, JsonUtils.writeValueAsString(claims.get(Claims.ADDITIONAL_AZ_ATTR))); } catch (JsonUtils.JsonUtilException e) { throw new IllegalStateException("Cannot convert access token to JSON", e); } } clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters)); Authentication userAuthentication = getUserAuthentication(claims, scope); clientAuthentication.setApproved(true); return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication); }
From source file:org.cloudfoundry.identity.uaa.authentication.AbstractClientParametersAuthenticationFilter.java
private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo, String clientId) {/* w w w . j a v a 2s . c om*/ if (clientId != null) { Result policyResult = loginPolicy.isAllowed(clientId); if (!policyResult.isAllowed()) { throw new ClientLockoutException("Client " + clientId + " has " + policyResult.getFailureCount() + " failed authentications within the last checking period."); } } String clientSecret = loginInfo.get(CLIENT_SECRET); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId, clientSecret); authentication.setDetails(new UaaAuthenticationDetails(req, clientId)); try { Authentication auth = clientAuthenticationManager.authenticate(authentication); if (auth == null || !auth.isAuthenticated()) { throw new BadCredentialsException("Client Authentication failed."); } loginInfo.remove(CLIENT_SECRET); AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req)); authorizationRequest.setRequestParameters(getSingleValueMap(req)); authorizationRequest.setApproved(true); //must set this to true in order for //Authentication.isAuthenticated to return true OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); result.setAuthenticated(true); return result; } catch (AuthenticationException e) { throw new BadCredentialsException(e.getMessage(), e); } catch (Exception e) { logger.debug("Unable to authenticate client: " + clientId, e); throw new BadCredentialsException(e.getMessage(), e); } }
From source file:org.cloudfoundry.identity.uaa.authentication.ClientParametersAuthenticationFilter.java
private Authentication performClientAuthentication(HttpServletRequest req, Map<String, String> loginInfo, String clientId) {/*from w w w . ja v a2 s .c om*/ String clientSecret = loginInfo.get(CLIENT_SECRET); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(clientId, clientSecret); authentication.setDetails(new UaaAuthenticationDetails(req, clientId)); try { Authentication auth = clientAuthenticationManager.authenticate(authentication); if (auth == null || !auth.isAuthenticated()) { throw new BadCredentialsException("Client Authentication failed."); } loginInfo.remove(CLIENT_SECRET); AuthorizationRequest authorizationRequest = new AuthorizationRequest(clientId, getScope(req)); authorizationRequest.setRequestParameters(getSingleValueMap(req)); authorizationRequest.setApproved(true); //must set this to true in order for //Authentication.isAuthenticated to return true OAuth2Authentication result = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null); result.setAuthenticated(true); return result; } catch (AuthenticationException e) { throw new BadCredentialsException(e.getMessage(), e); } catch (Exception e) { logger.debug("Unable to authenticate client: " + clientId, e); throw new BadCredentialsException(e.getMessage(), e); } }
From source file:org.cloudfoundry.identity.uaa.oauth.RemoteTokenServices.java
@Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException { MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("token", accessToken); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret)); Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers); if (map.containsKey("error")) { logger.debug("check_token returned error: " + map.get("error")); throw new InvalidTokenException(accessToken); }//from w w w . j ava 2s . c o m Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server"); String remoteClientId = (String) map.get("client_id"); Set<String> scope = new HashSet<String>(); if (map.containsKey("scope")) { @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) map.get("scope"); scope.addAll(values); } AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope); if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) { Set<String> resourceIds = new HashSet<String>(); if (map.containsKey("resource_ids")) { @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) map.get("resource_ids"); resourceIds.addAll(values); } Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>(); if (map.containsKey("client_authorities")) { @SuppressWarnings("unchecked") Collection<String> values = (Collection<String>) map.get("client_authorities"); clientAuthorities.addAll(getAuthorities(values)); } BaseClientDetails clientDetails = new BaseClientDetails(); clientDetails.setClientId(remoteClientId); clientDetails.setResourceIds(resourceIds); clientDetails.setAuthorities(clientAuthorities); clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails); } Map<String, String> requestParameters = new HashMap<>(); if (isStoreClaims()) { for (Map.Entry<String, Object> entry : map.entrySet()) { if (entry.getValue() != null && entry.getValue() instanceof String) { requestParameters.put(entry.getKey(), (String) entry.getValue()); } } } if (map.containsKey(ClaimConstants.ADDITIONAL_AZ_ATTR)) { try { requestParameters.put(ClaimConstants.ADDITIONAL_AZ_ATTR, JsonUtils.writeValueAsString(map.get(ClaimConstants.ADDITIONAL_AZ_ATTR))); } catch (JsonUtils.JsonUtilException e) { throw new IllegalStateException("Cannot convert access token to JSON", e); } } clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters)); Authentication userAuthentication = getUserAuthentication(map, scope); clientAuthentication.setApproved(true); return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication); }
From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java
@Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException { Map<String, Object> claims = getClaimsForToken(accessToken); // Check token expiry Integer expiration = (Integer) claims.get(EXP); if (expiration != null && new Date(expiration * 1000l).before(new Date())) { throw new InvalidTokenException("Invalid access token (expired): " + accessToken + " expired at " + new Date(expiration * 1000l)); }//from w w w . j a v a 2 s. co m // Check client ID is valid validateClient((String) claims.get(CLIENT_ID)); validateClient((String) claims.get(CID)); @SuppressWarnings("unchecked") ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE); AuthorizationRequest authorizationRequest = new AuthorizationRequest((String) claims.get(CLIENT_ID), scopes); ArrayList<String> rids = (ArrayList<String>) claims.get(AUD); //TODO - Fix null resource IDs for a client_credentials request to /oauth/token Set<String> resourceIds = Collections .unmodifiableSet(rids == null ? new HashSet<String>() : new HashSet<>(rids)); authorizationRequest.setResourceIds(resourceIds); authorizationRequest.setApproved(true); Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList( StringUtils.collectionToCommaDelimitedString(defaultUserAuthorities)); if (claims.containsKey("authorities")) { Object authoritiesFromClaims = claims.get("authorities"); if (authoritiesFromClaims instanceof String) { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) authoritiesFromClaims); } if (authoritiesFromClaims instanceof Collection) { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList( StringUtils.collectionToCommaDelimitedString((Collection<?>) authoritiesFromClaims)); } } Authentication userAuthentication = null; // Is this a user token? if (claims.containsKey(EMAIL)) { UaaUser user = new UaaUser((String) claims.get(USER_ID), (String) claims.get(USER_NAME), null, (String) claims.get(EMAIL), UaaAuthority.USER_AUTHORITIES, null, null, null, null, null, null, false); UaaPrincipal principal = new UaaPrincipal(user); userAuthentication = new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES, null); } else { authorizationRequest.setAuthorities(authorities); } OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); authentication.setAuthenticated(true); return authentication; }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServices.java
@Override public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException { if (StringUtils.isEmpty(accessToken)) { throw new InvalidTokenException( "Invalid access token value, must be at least 30 characters:" + accessToken); }/*from w w w. j av a2 s. c om*/ TokenValidation tokenValidation = validateToken(accessToken); Map<String, Object> claims = tokenValidation.getClaims(); accessToken = tokenValidation.getJwt().getEncoded(); // Check token expiry Integer expiration = (Integer) claims.get(EXP); if (expiration != null && new Date(expiration * 1000l).before(new Date())) { throw new InvalidTokenException("Invalid access token (expired): " + accessToken + " expired at " + new Date(expiration * 1000l)); } @SuppressWarnings("unchecked") ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE); AuthorizationRequest authorizationRequest = new AuthorizationRequest((String) claims.get(CLIENT_ID), scopes); ArrayList<String> rids = (ArrayList<String>) claims.get(AUD); //TODO - Fix null resource IDs for a client_credentials request to /oauth/token Set<String> resourceIds = Collections .unmodifiableSet(rids == null ? new HashSet<String>() : new HashSet<>(rids)); authorizationRequest.setResourceIds(resourceIds); authorizationRequest.setApproved(true); Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList( StringUtils.collectionToCommaDelimitedString(defaultUserAuthorities)); if (claims.containsKey("authorities")) { Object authoritiesFromClaims = claims.get("authorities"); if (authoritiesFromClaims instanceof String) { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) authoritiesFromClaims); } if (authoritiesFromClaims instanceof Collection) { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList( StringUtils.collectionToCommaDelimitedString((Collection<?>) authoritiesFromClaims)); } } Authentication userAuthentication = null; // Is this a user token - minimum info is user_id if (claims.containsKey(USER_ID)) { UaaUser user = userDatabase.retrieveUserById((String) claims.get(USER_ID)); UaaPrincipal principal = new UaaPrincipal(user); userAuthentication = new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES, null); } else { authorizationRequest.setAuthorities(authorities); } OAuth2Authentication authentication = new UaaOauth2Authentication(accessToken, IdentityZoneHolder.get().getId(), authorizationRequest.createOAuth2Request(), userAuthentication); authentication.setAuthenticated(true); return authentication; }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void is_opaque_token_required() { defaultClient.setAutoApproveScopes(singleton("true")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResponseTypes(new HashSet(Arrays.asList(CompositeAccessToken.ID_TOKEN, "token"))); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, TokenConstants.GRANT_TYPE_USER_TOKEN); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);/*from w w w .j a v a 2s.c o m*/ assertTrue(tokenServices.opaqueTokenRequired(authentication)); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void testCreateAccessTokenForAClient() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, clientScopes); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS); authorizationRequest.setRequestParameters(azParameters); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null);/* w w w . ja v a 2s . c om*/ OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertCommonClientAccessTokenProperties(accessToken); assertThat(accessToken, validFor(is(accessTokenValidity))); assertThat(accessToken, issuerUri(is(ISSUER_URI))); assertThat(accessToken, zoneId(is(IdentityZoneHolder.get().getId()))); assertThat(accessToken.getRefreshToken(), is(nullValue())); validateExternalAttributes(accessToken); assertCommonEventProperties(accessToken, CLIENT_ID, expectedJson); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
protected OAuth2AccessToken performPasswordGrant(String tokenFormat) { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, PASSWORD); azParameters.put(REQUEST_TOKEN_FORMAT, tokenFormat); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);/*from w w w . j a va 2 s. c o m*/ return tokenServices.createAccessToken(authentication); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void testCreateOpaqueAccessTokenForAClient() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, clientScopes); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE); azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS); authorizationRequest.setRequestParameters(azParameters); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null);/*from w w w.ja va 2 s . c o m*/ OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertTrue("Token is not a composite token", accessToken instanceof CompositeAccessToken); assertThat("Token value should be equal to or lesser than 36 characters", accessToken.getValue().length(), lessThanOrEqualTo(36)); assertThat(accessToken.getRefreshToken(), is(nullValue())); }