public static boolean hasAnyScopeMatching(Authentication authentication, String[] scopesRegex) { if (authentication instanceof OAuth2Authentication) { OAuth2Request clientAuthentication = ((OAuth2Authentication) authentication).getOAuth2Request(); for (String scope : clientAuthentication.getScope()) { for (String regex : scopesRegex) { if (scope.matches(regex)) { return true; } } } } return false; }
public static boolean hasAnyScope(Authentication authentication, String[] scopes) { if (authentication instanceof OAuth2Authentication) { OAuth2Request clientAuthentication = ((OAuth2Authentication) authentication).getOAuth2Request(); Collection<String> assigned = clientAuthentication.getScope(); if (assigned != null) { for (String scope : scopes) { if (assigned.contains(scope)) { return true; } } } } return false; }
@Override public Collection<String> getScopes() { Authentication a = SecurityContextHolder.getContext().getAuthentication(); if (!(a instanceof OAuth2Authentication)) { return Collections.emptySet(); } return ((OAuth2Authentication) a).getOAuth2Request().getScope(); } }
public String extractKey(OAuth2Authentication authentication) { Map<String, String> values = new LinkedHashMap<String, String>(); OAuth2Request authorizationRequest = authentication.getOAuth2Request(); if (!authentication.isClientOnly()) { values.put(USERNAME, authentication.getName()); } values.put(CLIENT_ID, authorizationRequest.getClientId()); if (authorizationRequest.getScope() != null) { values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet<String>(authorizationRequest.getScope()))); } return generateKey(values); }
/** * Update the request parameters and return a new object with the same properties except the parameters. * @param parameters new parameters replacing the existing ones * @return a new OAuth2Request */ public OAuth2Request createOAuth2Request(Map<String, String> parameters) { return new OAuth2Request(parameters, getClientId(), authorities, approved, getScope(), resourceIds, redirectUri, responseTypes, extensions); }
/** * Makes sure the authentication contains the given scope, throws an exception otherwise * @param auth the authentication object to check * @param scope the scope to look for * @throws InsufficientScopeException if the authentication does not contain that scope */ public static void ensureOAuthScope(Authentication auth, String scope) { // if auth is OAuth, make sure we've got the right scope if (auth instanceof OAuth2Authentication) { OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) auth; if (oAuth2Authentication.getOAuth2Request().getScope() == null || !oAuth2Authentication.getOAuth2Request().getScope().contains(scope)) { throw new InsufficientScopeException("Insufficient scope", ImmutableSet.of(scope)); } } }
public OAuth2Request refresh(TokenRequest tokenRequest) { OAuth2Request request = new OAuth2Request(getRequestParameters(), getClientId(), authorities, approved, getScope(), resourceIds, redirectUri, responseTypes, extensions); request.refresh = tokenRequest; return request; }
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); } } } }
private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString()); int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request()); if (validitySeconds > 0) { token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L))); } token.setRefreshToken(refreshToken); token.setScope(authentication.getOAuth2Request().getScope()); return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token; }
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { int result = ACCESS_ABSTAIN; if (!(authentication instanceof OAuth2Authentication)) { return result; } for (ConfigAttribute attribute : attributes) { if (denyAccess.equals(attribute.getAttribute())) { return ACCESS_DENIED; } } OAuth2Request clientAuthentication = ((OAuth2Authentication) authentication).getOAuth2Request(); for (ConfigAttribute attribute : attributes) { if (this.supports(attribute)) { result = ACCESS_DENIED; Set<String> scopes = clientAuthentication.getScope(); for (String scope : scopes) { if (attribute.getAttribute().toUpperCase().equals((scopePrefix + scope).toUpperCase())) { return ACCESS_GRANTED; } } if (result == ACCESS_DENIED && throwException) { InsufficientScopeException failure = new InsufficientScopeException( "Insufficient scope for this resource", Collections.singleton(attribute.getAttribute() .substring(scopePrefix.length()))); throw new AccessDeniedException(failure.getMessage(), failure); } } } return result; }
/** * Create a refreshed authentication. * * @param authentication The authentication. * @param request The scope for the refreshed token. * @return The refreshed authentication. * @throws InvalidScopeException If the scope requested is invalid or wider than the original scope. */ private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) { OAuth2Authentication narrowed = authentication; Set<String> scope = request.getScope(); OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request); if (scope != null && !scope.isEmpty()) { Set<String> originalScope = clientAuth.getScope(); if (originalScope == null || !originalScope.containsAll(scope)) { throw new InvalidScopeException("Unable to narrow the scope of the client authentication to " + scope + ".", originalScope); } else { clientAuth = clientAuth.narrowScope(scope); } } narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication()); return narrowed; }
@Override public OAuth2RefreshToken readRefreshToken(String tokenValue) { OAuth2AccessToken encodedRefreshToken = convertAccessToken(tokenValue); OAuth2RefreshToken refreshToken = createRefreshToken(encodedRefreshToken); if (approvalStore != null) { OAuth2Authentication authentication = readAuthentication(tokenValue); if (authentication.getUserAuthentication() != null) { String userId = authentication.getUserAuthentication().getName(); String clientId = authentication.getOAuth2Request().getClientId(); Collection<Approval> approvals = approvalStore.getApprovals(userId, clientId); Collection<String> approvedScopes = new HashSet<String>(); for (Approval approval : approvals) { if (approval.isApproved()) { approvedScopes.add(approval.getScope()); } } if (!approvedScopes.containsAll(authentication.getOAuth2Request().getScope())) { return null; } } } return refreshToken; }
private void checkClientDetails(OAuth2Authentication auth) { if (clientDetailsService != null) { ClientDetails client; try { client = clientDetailsService.loadClientByClientId(auth.getOAuth2Request().getClientId()); } catch (ClientRegistrationException e) { throw new OAuth2AccessDeniedException("Invalid token contains invalid client id"); } Set<String> allowed = client.getScope(); for (String scope : auth.getOAuth2Request().getScope()) { if (!allowed.contains(scope)) { throw new OAuth2AccessDeniedException( "Invalid token contains disallowed scope (" + scope + ") for this client"); } } } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication instanceof OAuth2Authentication) { OAuth2Request creq = ((OAuth2Authentication) authentication).getOAuth2Request(); List<String> scopes = dedup(creq.getScope()); int matches = 0; int requiredMatches = getRequiredScopes().size(); for (String scope : scopes) { if (requiredScopes.contains(scope)) { matches++; } } if (matches==requiredMatches) { authentication.setAuthenticated(true); return authentication; } else if (isThrowOnNotAuthenticated()) { throw new InsufficientScopeException("Insufficient scopes"); } } else if (isThrowOnNotAuthenticated()) { throw new InvalidTokenException("Missing Oauth 2 authentication."); } return authentication; }
protected OAuth2Request(OAuth2Request other) { this(other.getRequestParameters(), other.getClientId(), other.getAuthorities(), other.isApproved(), other .getScope(), other.getResourceIds(), other.getRedirectUri(), other.getResponseTypes(), other .getExtensions()); }
public void setAuthentication(OAuth2Authentication authentication) { // pull apart the request and save its bits OAuth2Request o2Request = authentication.getOAuth2Request(); setAuthorities(o2Request.getAuthorities() == null ? null : new HashSet<>(o2Request.getAuthorities())); setClientId(o2Request.getClientId()); setExtensions(o2Request.getExtensions() == null ? null : new HashMap<>(o2Request.getExtensions())); setRedirectUri(o2Request.getRedirectUri()); setRequestParameters(o2Request.getRequestParameters() == null ? null : new HashMap<>(o2Request.getRequestParameters())); setResourceIds(o2Request.getResourceIds() == null ? null : new HashSet<>(o2Request.getResourceIds())); setResponseTypes(o2Request.getResponseTypes() == null ? null : new HashSet<>(o2Request.getResponseTypes())); setScope(o2Request.getScope() == null ? null : new HashSet<>(o2Request.getScope())); setApproved(o2Request.isApproved()); if (authentication.getUserAuthentication() != null) { this.userAuth = new SavedUserAuthentication(authentication.getUserAuthentication()); } else { this.userAuth = null; } }
@Override public OAuth2Request createOAuth2Request(ClientDetails client) { OAuth2Request request = super.createOAuth2Request(client); return new OAuth2Request( request.getRequestParameters(), client.getClientId(), client.getAuthorities(), true, request.getScope(), resourceIds, request.getRedirectUri(), responseTypes, request.getExtensions()); } }
private String validatePasswordGrantToken(String clientId, String username, String zoneSubdomain, String requestedScopes, List<String> expectedScopes) throws Exception { String pwdToken; if (zoneSubdomain == null) { pwdToken = testClient.getUserOAuthAccessToken(clientId, SECRET, username, SECRET, requestedScopes); } else { pwdToken = testClient.getUserOAuthAccessTokenForZone(clientId, SECRET, username, SECRET, requestedScopes, zoneSubdomain); IdentityZoneHolder.set(identityZoneProvisioning.retrieveBySubdomain(zoneSubdomain)); } OAuth2Authentication authContext = tokenServices.loadAuthentication(pwdToken); Set<String> grantedScopes = authContext.getOAuth2Request().getScope(); assertEquals(expectedScopes.size(), grantedScopes.size()); assertEquals(grantedScopes, new HashSet<>(expectedScopes)); IdentityZoneHolder.clear(); return pwdToken; }
OAuth2Request clientAuthentication = oauth2Authentication.getOAuth2Request(); ClientDetails client = clientDetailsService.loadClientByClientId(clientAuthentication.getClientId()); Set<String> scopes = clientAuthentication.getScope(); if (oauth2Authentication.isClientOnly() && clientAuthoritiesAreScopes) { scopes = AuthorityUtils.authorityListToSet(clientAuthentication.getAuthorities());
@Test public void testTokenRequestIncludesResourceIds() { SecurityContextAccessor securityContextAccessor = new StubSecurityContextAccessor() { @Override public boolean isUser() { return false; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return AuthorityUtils.commaSeparatedStringToAuthorityList("aud1.test aud2.test"); } }; parameters.put("scope", "aud1.test aud2.test"); parameters.put("client_id", client.getClientId()); parameters.put(OAuth2Utils.GRANT_TYPE, "client_credentials"); IdentityZoneHolder.get().getConfig().getUserConfig().setDefaultGroups(Arrays.asList("aud1.test")); factory.setSecurityContextAccessor(securityContextAccessor); client.setScope(StringUtils.commaDelimitedListToSet("aud1.test,aud2.test")); OAuth2Request request = factory.createTokenRequest(parameters, client).createOAuth2Request(client); assertEquals(StringUtils.commaDelimitedListToSet("aud1.test,aud2.test"), new TreeSet<>(request.getScope())); assertEquals(StringUtils.commaDelimitedListToSet("aud1,aud2"), new TreeSet<>(request.getResourceIds())); }