當前位置: 首頁>>代碼示例>>Java>>正文


Java OAuth2Request類代碼示例

本文整理匯總了Java中org.springframework.security.oauth2.provider.OAuth2Request的典型用法代碼示例。如果您正苦於以下問題:Java OAuth2Request類的具體用法?Java OAuth2Request怎麽用?Java OAuth2Request使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


OAuth2Request類屬於org.springframework.security.oauth2.provider包,在下文中一共展示了OAuth2Request類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: validateToken

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@RequestMapping(value = "/validation", method = RequestMethod.POST)
@ResponseBody
public AccessToken validateToken(@RequestHeader("Authorization") final String authorization) {
    String token = getToken(authorization);
    OAuth2Authentication auth = tokenStore.readAuthentication(token);
    OAuth2AccessToken accessToken = tokenStore.getAccessToken(auth);
    OAuth2Request authReq = auth.getOAuth2Request();

    AccessToken.Builder tokenBuilder = new AccessToken.Builder(token).setClientId(authReq.getClientId());

    if (auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) {
        User user = (User) auth.getPrincipal();
        tokenBuilder.setUserName(user.getUserName());
        tokenBuilder.setUserId(user.getId());
    }

    tokenBuilder.setExpiresAt(accessToken.getExpiration());
    for (String scopeString : authReq.getScope()) {
        tokenBuilder.addScope(new Scope(scopeString));
    }

    return tokenBuilder.build();
}
 
開發者ID:osiam,項目名稱:auth-server,代碼行數:24,代碼來源:TokenController.java

示例2: getOauth2Request

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
/**
 * Mock OAuth2Request
 * 
 * @param withMockOAuth2Token
 * @return
 */
private OAuth2Request getOauth2Request(WithMockOAuth2Token withMockOAuth2Token) {
	String clientId = withMockOAuth2Token.clientId();
	Map<String, String> requestParameters = Collections.emptyMap();
	boolean approved = true;
	String redirectUrl = withMockOAuth2Token.redirectUrl();
	Set<String> responseTypes = Collections.emptySet();
	Set<String> scopes = new HashSet<>(Arrays.asList(withMockOAuth2Token.scopes()));
	Set<String> resourceIds = Collections.emptySet();
	Map<String, Serializable> extensionProperties = Collections.emptyMap();
	List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(withMockOAuth2Token.authorities());

	OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId, authorities, approved, scopes,
			resourceIds, redirectUrl, responseTypes, extensionProperties);

	return oAuth2Request;
}
 
開發者ID:anilallewar,項目名稱:microservices-basics-spring-boot,代碼行數:23,代碼來源:WithOAuth2MockAccessTokenSecurityContextFactory.java

示例3: testGetAccessTokenForDeletedUser

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@Test
public void testGetAccessTokenForDeletedUser() throws Exception {
	//Test approved request
	OAuth2Request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", true);
	OAuth2Authentication expectedAuthentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test", true));
	OAuth2AccessToken expectedOAuth2AccessToken = new DefaultOAuth2AccessToken("testToken");
	getTokenStore().storeAccessToken(expectedOAuth2AccessToken, expectedAuthentication);
	assertEquals(expectedOAuth2AccessToken, getTokenStore().getAccessToken(expectedAuthentication));
	assertEquals(expectedAuthentication, getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()));
	
	//Test unapproved request
	storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", false);
	OAuth2Authentication anotherAuthentication = new OAuth2Authentication(storedOAuth2Request, new TestAuthentication("test", true));
	assertEquals(expectedOAuth2AccessToken, getTokenStore().getAccessToken(anotherAuthentication));
	// The generated key for the authentication is the same as before, but the two auths are not equal. This could
	// happen if there are 2 users in a system with the same username, or (more likely), if a user account was
	// deleted and re-created.
	assertEquals(anotherAuthentication.getUserAuthentication(), getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()).getUserAuthentication());
	// The authorizationRequest does not match because it is unapproved, but the token was granted to an approved request
	assertFalse(storedOAuth2Request.equals(getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()).getOAuth2Request()));
}
 
開發者ID:Mert-Z,項目名稱:spring-oauth2-cassandra-token-store,代碼行數:22,代碼來源:TokenStoreBaseTests.java

示例4: convertAccessToken

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
/**
 * Values placed into the map will be included in the JWT token only, not the OAuth 2 response itself.
 */
@Override
public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
	Map<String, Object> map = (Map<String, Object>) super.convertAccessToken(token, authentication);

	OAuth2Request request = authentication.getOAuth2Request();
	Set<String> authorities = request.getAuthorities().stream().map(a -> a.getAuthority()).collect(Collectors.toSet());

	ClientDetails client = clientAuthenticationService.loadClientByClientId(request.getClientId());
	if (client.getResourceIds() != null && !client.getResourceIds().isEmpty()) {
		map.put(AUDIENCE, client.getResourceIds());
	}

	Authentication userAuthentication = authentication.getUserAuthentication();
	if (userAuthentication == null) {
		map.remove("authorities");
	}

	map.put(CLIENT_AUTHORITIES, authorities);

	return map;
}
 
開發者ID:PatternFM,項目名稱:tokamak,代碼行數:25,代碼來源:JWTTokenConverter.java

示例5: getIssuerIdOrFail

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@Override
public String getIssuerIdOrFail() {
    String issuer = null;
    OAuth2Request oAuth2Request = getAuthentication().getOAuth2Request();

    if (oAuth2Request != null) {
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();

        if (requestParameters != null && requestParameters.containsKey("iss")) {
            issuer = requestParameters.get("iss");
        }
    }

    if (issuer == null) {
        throw new InvalidACSRequestException("Authetication issuer cannot be null");
    }

    return issuer;
}
 
開發者ID:eclipse,項目名稱:keti,代碼行數:20,代碼來源:SpringSecurityPolicyContextResolver.java

示例6: setUp

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
    subject = new CustomOAuth2AuthenticationManager(customUserDetailsService, defaultTokenServices);
    when(previousAuthentication.getPrincipal()).thenReturn("SomePrincipal");
    mockAuthorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));

    OAuth2Request request = new OAuth2Request(null, null, mockAuthorities, true,
            null, null, null, null, null);

    when(previousAuthentication.getOAuth2Request()).thenReturn(request);
    when(previousAuthentication.getDetails()).thenReturn(mockTokenDetails);
    when(previousAuthentication.getCredentials()).thenReturn(mockCredentials);
    when(previousAuthentication.getAuthorities()).thenReturn(mockAuthorities);
    when(defaultTokenServices.loadAuthentication("SomePrincipal")).thenReturn(previousAuthentication);

    when(customUserDetailsService.loadUserByUsername("SomePrincipal")).thenReturn(mockUserDetails);
}
 
開發者ID:themadweaz,項目名稱:weazbootgradle,代碼行數:18,代碼來源:CustomOAuth2AuthenticationManagerTest.java

示例7: loadAuthentication

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
    GitHubClient gitHubClient = GitHubClient.withAccessToken(accessToken);
    UserResource gitHubUser = gitHubClient.getUser();

    List<String> allowedOrganizations = ofNullable(loginDetails.get().getRestrictions())
            .flatMap(restrictions -> ofNullable(restrictions.get("organizations")))
            .map(it -> Splitter.on(",").omitEmptyStrings().splitToList(it))
            .orElse(emptyList());
    if (!allowedOrganizations.isEmpty()) {
        boolean assignedToOrganization = gitHubClient.getUserOrganizations(gitHubUser).stream().map(userOrg -> userOrg.login)
                .anyMatch(allowedOrganizations::contains);
        if (!assignedToOrganization) {
            throw new InsufficientOrganizationException("User '" + gitHubUser.login + "' does not belong to allowed GitHUB organization");
        }
    }

    User user = replicator.replicateUser(gitHubUser, gitHubClient);

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getId(), "N/A",
            AuthUtils.AS_AUTHORITIES.apply(user.getRole()));

    Map<String, Serializable> extensionProperties = Collections.singletonMap("upstream_token", accessToken);
    OAuth2Request request = new OAuth2Request(null, loginDetails.get().getClientId(), null, true, null, null, null, null, extensionProperties);
    return new OAuth2Authentication(request, token);
}
 
開發者ID:reportportal,項目名稱:service-authorization,代碼行數:27,代碼來源:GitHubTokenServices.java

示例8: loadAuthentication

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
        throws AuthenticationException, InvalidTokenException {
    OAuth2Authentication authentication = super.loadAuthentication(accessToken);
    OAuth2Request request = authentication.getOAuth2Request();
    UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.class.cast(authentication.getUserAuthentication());
    Map<String, Object> map = Map.class.cast(token.getDetails());

    String id = map.getOrDefault("id", "").toString();
    Triple<OAuthSource, String, Integer> principal = Triple.of(source, id, null);
    Object credentials = token.getCredentials();
    List<GrantedAuthority> authorities = Lists.newArrayList(token.getAuthorities());

    OAuthUser user = this.repository.findBySourceAndId(source, id);
    if (user != null) {
        Assert.state(user.getUser() != null);
        principal = Triple.of(source, id, user.getUser().getId());
        authorities.add(new SimpleGrantedAuthority("ROLE_SU"));
    }

    token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
    token.setDetails(map);
    return new OAuth2Authentication(request, token);
}
 
開發者ID:HeroXXiv,項目名稱:Robocode,代碼行數:25,代碼來源:SecurityConfig.java

示例9: extractAuthentication

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@Override
public OAuth2Authentication extractAuthentication(Map<String, Object> map, String clientId) {
    Object principal = getPrincipal(map);

    Set<String> roles = grantUserRoles(principal);

    UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(
            principal,
            "N/A",
            rolesToGrantedAuthorities(roles)
    );
    user.setDetails(map);

    OAuth2Request request = new OAuth2Request(null, clientId, null, true, resolveScopes(map), null, null, null, null);
    return new OAuth2Authentication(request, user);
}
 
開發者ID:pazuzu-io,項目名稱:pazuzu-registry,代碼行數:17,代碼來源:ClientIdAuthorityGrantingAuthenticationExtractor.java

示例10: extractKey

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@Override
public String extractKey(OAuth2Authentication authentication) {
    Map<String, String> values = new LinkedHashMap<>();
    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(authorizationRequest.getScope()));
    }
    String uuid = UUID.randomUUID().toString();
    values.put(UUID_KEY, uuid);

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).");
    }

    byte[] bytes = digest.digest(values.toString().getBytes(StandardCharsets.UTF_8));
    return String.format("%032x", new BigInteger(1, bytes));
}
 
開發者ID:cuba-platform,項目名稱:cuba,代碼行數:25,代碼來源:UniqueAuthenticationKeyGenerator.java

示例11: getOutboundSecurityObject

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
public Object getOutboundSecurityObject() {
	Map<String, ClientDetails> clientDetailsStore = new HashMap<>();
	clientDetailsStore.put("testClient", new BaseClientDetails("testClient", "",
			"", "", ""));
	InMemoryClientDetailsService inMemoryClientDetailsService = new InMemoryClientDetailsService();
	inMemoryClientDetailsService.setClientDetailsStore(clientDetailsStore);
	DefaultOAuth2RequestFactory defaultOAuth2RequestFactory = new DefaultOAuth2RequestFactory(inMemoryClientDetailsService);
	MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
	mockHttpServletRequest.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, "Bearer");
	mockHttpServletRequest.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, "testvalue");
	Map<String, String> authorizationParameters = new HashMap<>();
	authorizationParameters.put(OAuth2Utils.CLIENT_ID, "testClient");
	OAuth2Request oAuth2Request = defaultOAuth2RequestFactory.createOAuth2Request(defaultOAuth2RequestFactory.createAuthorizationRequest(authorizationParameters));
	OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, null);
	OAuth2AuthenticationDetails details = new OAuth2AuthenticationDetails(mockHttpServletRequest);
	auth.setDetails(details);
	return auth;
}
 
開發者ID:ordina-jworks,項目名稱:microservices-dashboard-server,代碼行數:19,代碼來源:ForwardOAuth2TokenStrategyIntegrationTest.java

示例12: readAuthentication

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@Override
public OAuth2Authentication readAuthentication(String token) {
    String consumerKeyFromToken = oAuth2TokenValidationService.getConsumerKeyFromToken(token);
    OAuth2Authentication oAuth2Authentication = null;
    if (consumerKeyFromToken != null) {
        String applicationName = oAuthAdminService.getApplicationName(consumerKeyFromToken);
        HashSet<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(applicationName));
        OAuth2Request oAuth2Request = new OAuth2Request(null, applicationName, authorities, true, null, null, null, null, null);
        oAuth2Authentication = new OAuth2Authentication(oAuth2Request, null);
    }

    return oAuth2Authentication;


}
 
開發者ID:angel-git,項目名稱:wso2is-springoauth,代碼行數:17,代碼來源:WSWso2TokenStore.java

示例13: createAccessToken

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
public AccessToken createAccessToken() {
    Set<String> scopes = new HashSet<>();
    scopes.add(Scope.ADMIN.toString());
    // Random scope, because the token services generates for every scope but same client
    // a different access token. This is only made due to the token expired problem, when the auth server
    // takes his actual access token, but the token is expired during the request to the resource server
    scopes.add(new Scope(UUID.randomUUID().toString()).toString());

    Map<String, String> parameters = new HashMap<>();
    parameters.put("client_id", OsiamAuthServerClientProvider.AUTH_SERVER_CLIENT_ID);
    OAuth2Request authRequest = new OAuth2Request(
            parameters, OsiamAuthServerClientProvider.AUTH_SERVER_CLIENT_ID, null, true, scopes,
            null, null, null, null
    );

    OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(authRequest, null);

    OAuth2AccessToken oAuth2AccessToken = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());

    tokenStore.storeAccessToken(oAuth2AccessToken, oAuth2Authentication);

    return new AccessToken.Builder(oAuth2AccessToken.getValue()).build();
}
 
開發者ID:osiam,項目名稱:auth-server,代碼行數:24,代碼來源:OsiamAccessTokenProvider.java

示例14: readAuthentication

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
private OAuth2Authentication readAuthentication(Claims claims) {

        Set<GrantedAuthority> authorities = getAuthoritiesFromClaims(claims);

        OAuth2Request request = new OAuth2Request(
                getRequestParametersFromClaims(claims),
                JwtExtraClaims.getClientId(claims),
                authorities,
                true,
                JwtExtraClaims.getScope(claims),
                claims.getAudiences(),
                null, null, null);

        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(claims.getSubject(), null, authorities);

        return new OAuth2Authentication(request, authentication);
    }
 
開發者ID:unbroken-dome,項目名稱:jsonwebtoken,代碼行數:19,代碼來源:JwtTokenStore.java

示例15: convert

import org.springframework.security.oauth2.provider.OAuth2Request; //導入依賴的package包/類
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public OAuth2Authentication convert(DBObject source) {
  DBObject storedRequest = (DBObject) source.get("storedRequest");
  OAuth2Request oauth2Request =
      new OAuth2Request((Map<String, String>) storedRequest.get("requestParameters"),
          (String) storedRequest.get("clientId"), null, true,
          new HashSet((List) storedRequest.get("scope")), null, null, null, null);

  DBObject userAuthorization = (DBObject) source.get("userAuthentication");
  Object principal = getPrincipalObject(userAuthorization.get("principal"));
  Authentication userAuthentication =
      new UsernamePasswordAuthenticationToken(principal, userAuthorization.get("credentials"),
          getAuthorities((List) userAuthorization.get("authorities")));

  return new OAuth2Authentication(oauth2Request, userAuthentication);
}
 
開發者ID:dzhw,項目名稱:metadatamanagement,代碼行數:18,代碼來源:OAuth2AuthenticationReadConverter.java


注:本文中的org.springframework.security.oauth2.provider.OAuth2Request類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。