当前位置: 首页>>代码示例>>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;未经允许,请勿转载。