当前位置: 首页>>代码示例>>Java>>正文


Java OAuth2Utils类代码示例

本文整理汇总了Java中org.springframework.security.oauth2.common.util.OAuth2Utils的典型用法代码示例。如果您正苦于以下问题:Java OAuth2Utils类的具体用法?Java OAuth2Utils怎么用?Java OAuth2Utils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


OAuth2Utils类属于org.springframework.security.oauth2.common.util包,在下文中一共展示了OAuth2Utils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getAccessConfirmation

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
	AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
	ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
	model.put("auth_request", clientAuth);
	model.put("client", client);
	Map<String, String> scopes = new LinkedHashMap<String, String>();
	for (String scope : clientAuth.getScope()) {
		scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");
	}
	for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
		if (clientAuth.getScope().contains(approval.getScope())) {
			scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
					approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false");
		}
	}
	model.put("scopes", scopes);
	return new ModelAndView("authorize", model);
}
 
开发者ID:venus-boot,项目名称:saluki,代码行数:20,代码来源:AccessConfirmationController.java

示例2: getAuthParameters

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
/**
 * Generate an authorization parameter map from the session's token request
 * @param defaultSavedRequest the default saved request from the session
 * @return a map of parameters containing the OAuth2 request details
 */
private Map<String, String> getAuthParameters(DefaultSavedRequest defaultSavedRequest) {
    Map<String, String> authParams = new HashMap<>();

    authParams.put(OAuth2Utils.CLIENT_ID,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.CLIENT_ID)[0]);

    authParams.put(OAuth2Utils.REDIRECT_URI,
            defaultSavedRequest.getParameterMap().get(OAuth2Utils.REDIRECT_URI)[0]);

    if(defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE) != null) {
        authParams.put(OAuth2Utils.STATE,
                defaultSavedRequest.getParameterMap().get(OAuth2Utils.STATE)[0]);
    }

    authParams.put(OAuth2Utils.RESPONSE_TYPE, "code");
    authParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    authParams.put(OAuth2Utils.GRANT_TYPE, "authorization_code");
    return authParams;
}
 
开发者ID:kbastani,项目名称:cloud-native-microservice-strangler-example,代码行数:25,代码来源:LoginController.java

示例3: onAuthenticationFailure

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
/**
 * Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise returns a 401 error code.
 * <p>
 * If redirecting or forwarding, {@code saveException} will be called to cache the exception for use in
 * the target view.
 */
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                    AuthenticationException exception) throws IOException, ServletException {

    if (defaultFailureUrl == null) {
        logger.debug("No failure URL set, sending 401 Unauthorized error");

        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage());
    } else {
        saveException(request, exception);

        if (forwardToDestination) {
            logger.debug("Forwarding to " + defaultFailureUrl);

            request.getRequestDispatcher(defaultFailureUrl).forward(request, response);
        } else {
            logger.debug("Redirecting to " + defaultFailureUrl);
            redirectStrategy.sendRedirect(request, response, defaultFailureUrl + "&client_id=" + request.getParameter(OAuth2Utils.CLIENT_ID));
        }
    }
}
 
开发者ID:gravitee-io,项目名称:graviteeio-access-management,代码行数:27,代码来源:ClientAwareAuthenticationFailureHandler.java

示例4: buildDetails

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
public Map<String, String> buildDetails(HttpServletRequest request) {
    Map<String, String> mapDetails = new HashMap<>();
    mapDetails.put("remote_address", request.getRemoteAddr());

    HttpSession session = request.getSession(false);
    mapDetails.put("session_id",  (session != null) ? session.getId() : null);

    String clientId = request.getParameter(OAuth2Utils.CLIENT_ID);

    // In case of basic authentication, extract client_id from authorization header
    if (clientId == null || clientId.isEmpty()) {
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (header != null && header.startsWith("Basic ")) {
            try {
                String[] tokens = extractAndDecodeHeader(header);
                clientId = tokens[0];
            } catch (IOException ioe) {
                // Nothing to do
            }
        }
    }

    mapDetails.put(OAuth2Utils.CLIENT_ID, clientId);

    return mapDetails;
}
 
开发者ID:gravitee-io,项目名称:graviteeio-access-management,代码行数:27,代码来源:ClientAwareAuthenticationDetailsSource.java

示例5: getAccessConfirmation

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
    AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
    ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
    model.put("auth_request", clientAuth);
    model.put("client", client);
    Map<String, String> scopes = new LinkedHashMap<String, String>();
    for (String scope : clientAuth.getScope()) {
        scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");
    }
    for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
        if (clientAuth.getScope().contains(approval.getScope())) {
            scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
                    approval.getStatus() == Approval.ApprovalStatus.APPROVED ? "true" : "false");
        }
    }
    model.put("scopes", scopes);
    return new ModelAndView("access_confirmation", model); // 订阅 appproval 页面
}
 
开发者ID:h819,项目名称:spring-boot,代码行数:20,代码来源:AccessConfirmationController.java

示例6: extractKey

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的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

示例7: getOutboundSecurityObject

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的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

示例8: setScope

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
protected void setScope(Collection<String> scope) {
	if (scope != null && scope.size() == 1) {
		String value = scope.iterator().next();
		/*
		 * This is really an error, but it can catch out unsuspecting users
		 * and it's easy to fix. It happens when an AuthorizationRequest
		 * gets bound accidentally from request parameters using
		 * @ModelAttribute.
		 */
		if (value.contains(" ") || value.contains(",")) {
			scope = OAuth2Utils.parseParameterList(value);
		}
	}
	this.scope = Collections
			.unmodifiableSet(scope == null ? new LinkedHashSet<String>()
					: new LinkedHashSet<String>(scope));
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:18,代码来源:BaseRequest.java

示例9: createAuthorizationRequest

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
public AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters) {
	
	String clientId = authorizationParameters.get(OAuth2Utils.CLIENT_ID);
	Set<String> scopes = OAuth2Utils.parseParameterList(authorizationParameters.get(OAuth2Utils.SCOPE));
	String state = authorizationParameters.get(OAuth2Utils.STATE);
	String redirectUri = authorizationParameters.get(OAuth2Utils.REDIRECT_URI);
	Set<String> responseTypes = OAuth2Utils.parseParameterList(authorizationParameters.get(OAuth2Utils.RESPONSE_TYPE));
			
	ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);

	if ((scopes == null || scopes.isEmpty())) {
		// If no scopes are specified in the incoming data, use the default values registered with the client
		// (the spec allows us to choose between this option and rejecting the request completely, so we'll take the
		// least obnoxious choice as a default).
		scopes = clientDetails.getScope();
	}

	AuthorizationRequest request = new AuthorizationRequest(authorizationParameters, Collections.<String, String> emptyMap(), 
			clientId, scopes, null, null, false, state, redirectUri, responseTypes);
	
	request.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
	
	return request;

}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:26,代码来源:DefaultOAuth2RequestFactory.java

示例10: testScopeSortedOrder

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
/**
 * Tests that the construction of an AuthorizationRequest objects using
 * a parameter Map maintains a sorted order of the scope.
 */
@Test
public void testScopeSortedOrder() {
	// Arbitrary scope set
	String scopeString = "AUTHORITY_A AUTHORITY_X AUTHORITY_B AUTHORITY_C AUTHORITY_D " +
			"AUTHORITY_Y AUTHORITY_V AUTHORITY_ZZ AUTHORITY_DYV AUTHORITY_ABC AUTHORITY_BA " +
			"AUTHORITY_AV AUTHORITY_AB AUTHORITY_CDA AUTHORITY_ABCD";
	// Create correctly sorted scope string
	Set<String> sortedSet = OAuth2Utils.parseParameterList(scopeString);
	Assert.assertTrue(sortedSet instanceof SortedSet);
	String sortedScopeString = OAuth2Utils.formatParameterList(sortedSet);

	parameters.put("scope", scopeString);
	AuthorizationRequest authorizationRequest = createFromParameters(parameters);
	authorizationRequest.setScope(sortedSet);
			
	// Assert that the scope parameter is still sorted
	
	String fromAR = OAuth2Utils.formatParameterList(authorizationRequest.getScope());
	
	Assert.assertEquals(sortedScopeString, fromAR);
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:26,代码来源:DefaultAuthorizationRequestTests.java

示例11: getAuthorizationRequest

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
private AuthorizationRequest getAuthorizationRequest(String clientId, String redirectUri, String state,
		String scope, Set<String> responseTypes) {
	HashMap<String, String> parameters = new HashMap<String, String>();
	parameters.put(OAuth2Utils.CLIENT_ID, clientId);
	if (redirectUri != null) {
		parameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
	}
	if (state != null) {
		parameters.put(OAuth2Utils.STATE, state);
	}
	if (scope != null) {
		parameters.put(OAuth2Utils.SCOPE, scope);
	}
	if (responseTypes != null) {
		parameters.put(OAuth2Utils.RESPONSE_TYPE, OAuth2Utils.formatParameterList(responseTypes));
	}
	return new AuthorizationRequest(parameters, Collections.<String, String> emptyMap(), 
			parameters.get(OAuth2Utils.CLIENT_ID), 
			OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)), null,
			null, false, parameters.get(OAuth2Utils.STATE), 
			parameters.get(OAuth2Utils.REDIRECT_URI), 
			OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.RESPONSE_TYPE)));
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:24,代码来源:AuthorizationEndpointTests.java

示例12: testGetAccessTokenWithNoClientId

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
@Test
public void testGetAccessTokenWithNoClientId() {

	HashMap<String, String> parameters = new HashMap<String, String>();
	parameters.put(OAuth2Utils.GRANT_TYPE, "authorization_code");

	OAuth2AccessToken expectedToken = new DefaultOAuth2AccessToken("FOO");
	when(tokenGranter.grant(Mockito.eq("authorization_code"), Mockito.any(TokenRequest.class))).thenReturn(
			expectedToken);
	@SuppressWarnings("unchecked")
	Map<String, String> anyMap = Mockito.any(Map.class);
	when(authorizationRequestFactory.createTokenRequest(anyMap, Mockito.any(ClientDetails.class))).thenReturn(
			createFromParameters(parameters));

	clientAuthentication = new UsernamePasswordAuthenticationToken(null, null,
			Collections.singleton(new SimpleGrantedAuthority("ROLE_CLIENT")));
	ResponseEntity<OAuth2AccessToken> response = endpoint.getAccessToken(clientAuthentication, parameters);

	assertNotNull(response);
	assertEquals(HttpStatus.OK, response.getStatusCode());
	OAuth2AccessToken body = response.getBody();
	assertEquals(body, expectedToken);
	assertTrue("Wrong body: " + body, body.getTokenType() != null);
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:25,代码来源:TokenEndpointTests.java

示例13: getAccessConfirmation

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
@RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, Principal principal) throws Exception {
	AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest");
	ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId());
	model.put("auth_request", clientAuth);
	model.put("client", client);
	Map<String, String> scopes = new LinkedHashMap<String, String>();
	for (String scope : clientAuth.getScope()) {
		scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false");
	}
	for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) {
		if (clientAuth.getScope().contains(approval.getScope())) {
			scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(),
					approval.getStatus() == ApprovalStatus.APPROVED ? "true" : "false");
		}
	}
	model.put("scopes", scopes);
	return new ModelAndView("access_confirmation", model);
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:20,代码来源:AccessConfirmationController.java

示例14: testUnauthenticatedAuthorizationRequestRedirectsToLogin

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
@Test
@OAuth2ContextConfiguration(resource = MyLessTrustedClient.class, initialize = false)
public void testUnauthenticatedAuthorizationRequestRedirectsToLogin() throws Exception {

	AccessTokenRequest request = context.getAccessTokenRequest();
	request.setCurrentUri("http://anywhere");
	request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");

	String location = null;

	try {
		String code = accessTokenProvider.obtainAuthorizationCode(context.getResource(), request);
		assertNotNull(code);
		fail("Expected UserRedirectRequiredException");
	}
	catch (UserRedirectRequiredException e) {
		location = e.getRedirectUri();
	}

	assertNotNull(location);
	assertEquals(serverRunning.getUrl("/sparklr2/login.jsp"), location);

}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:24,代码来源:AuthorizationCodeProviderTests.java

示例15: testPostForNonAutomaticApprovalToken

import org.springframework.security.oauth2.common.util.OAuth2Utils; //导入依赖的package包/类
@Test
@OAuth2ContextConfiguration(resource = NonAutoApproveImplicit.class, initialize = false)
public void testPostForNonAutomaticApprovalToken() throws Exception {
	context.getAccessTokenRequest().setCookie(cookie);
	try {
		assertNotNull(context.getAccessToken());
		fail("Expected UserRedirectRequiredException");
	}
	catch (UserRedirectRequiredException e) {
		// ignore
	}
	// add user approval parameter for the second request
	context.getAccessTokenRequest().add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
	context.getAccessTokenRequest().add("scope.read", "true");
	assertNotNull(context.getAccessToken());
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:17,代码来源:ImplicitProviderTests.java


注:本文中的org.springframework.security.oauth2.common.util.OAuth2Utils类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。