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


Java OAuth2Request.getClientId方法代码示例

本文整理汇总了Java中org.springframework.security.oauth2.provider.OAuth2Request.getClientId方法的典型用法代码示例。如果您正苦于以下问题:Java OAuth2Request.getClientId方法的具体用法?Java OAuth2Request.getClientId怎么用?Java OAuth2Request.getClientId使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.springframework.security.oauth2.provider.OAuth2Request的用法示例。


在下文中一共展示了OAuth2Request.getClientId方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: authenticateUser

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
@BodyParser.Of(BodyParser.Json.class)
@PreAuthorize("#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.hasScope('trust')")
public Promise<Result> authenticateUser() {
  JsonNode json = request().body().asJson();
  String username = json.findPath("username").textValue();
  String password = json.findPath("password").textValue();

  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  OAuth2Request clientAuthenticationRequest =
      ((OAuth2Authentication) authentication).getOAuth2Request();
  Map<String, String> requestParameters = new HashMap<>();
  requestParameters.put("username", username);
  requestParameters.put("password", password);
  TokenRequest tokenRequest = new TokenRequest(requestParameters,
          clientAuthenticationRequest.getClientId(), clientAuthenticationRequest.getScope(),
          "password");
  OAuth2AccessToken token = tokenGranter.grant("password", tokenRequest);
  ObjectNode result = Json.newObject();
  result.setAll(ImmutableMap.of(
      "accessToken", result.textNode(token.getValue()),
      "username", result.textNode(username),
      "expiration", result.numberNode(token.getExpiration().getTime()),
      "refreshToken", result.textNode(token.getRefreshToken().getValue())));
  return Promise.pure(ok(result));
}
 
开发者ID:tfeng,项目名称:play-oauth2,代码行数:26,代码来源:SecurityController.java

示例2: refreshUserAccessToken

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
@BodyParser.Of(BodyParser.Json.class)
@PreAuthorize("#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.hasScope('trust')")
public Promise<Result> refreshUserAccessToken() {
  JsonNode body = request().body().asJson();
  String refreshToken = body.findPath("refreshToken").textValue();

  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  OAuth2Request clientAuthenticationRequest =
      ((OAuth2Authentication) authentication).getOAuth2Request();
  TokenRequest tokenRequest =
      new TokenRequest(Collections.emptyMap(), clientAuthenticationRequest.getClientId(),
          clientAuthenticationRequest.getScope(), "refresh");
  OAuth2AccessToken token = tokenServices.refreshAccessToken(refreshToken, tokenRequest);
  ObjectNode result = Json.newObject();
  result.setAll(ImmutableMap.of(
      "accessToken", result.textNode(token.getValue()),
      "expiration", result.numberNode(token.getExpiration().getTime()),
      "refreshToken", result.textNode(token.getRefreshToken().getValue())));
  return Promise.pure(ok(result));
}
 
开发者ID:tfeng,项目名称:play-oauth2,代码行数:21,代码来源:SecurityController.java

示例3: getOAuth2Authentication

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

    Map<String, String> parameters = tokenRequest.getRequestParameters();
    String authorizationCode = parameters.get("code");
    String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);
    String codeVerifier = parameters.get("code_verifier");

    if (authorizationCode == null) {
        throw new InvalidRequestException("An authorization code must be supplied.");
    }

    OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }

    OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request();




    // Validates code verifier
    Map<String, String> pendingOauth2RequestParams = pendingOAuth2Request.getRequestParameters();
    String codeChallenge = pendingOauth2RequestParams.get("code_challenge");
    String codeChallengeMethod = pendingOauth2RequestParams.get("code_challenge_method");

    if (codeVerifier == null && codeChallenge != null) {
        // client is using PKCE but did not send the codeVerifier
        throw new InvalidRequestException(
                "Invalid authorization code for current token request.");
    }

    if (codeVerifier != null && codeChallenge != null) {
        String hashed = codeVerifier;
        if ("S256".equals(codeChallengeMethod)) {
            hashed = DigestUtils.sha256Hex(codeVerifier);
        }

        if (!hashed.equalsIgnoreCase(codeChallenge)) {
            throw new InvalidRequestException(
                    "Invalid authorization code for current token request.");
        }
    }



    // https://jira.springsource.org/browse/SECOAUTH-333
    // This might be null, if the authorization was done without the redirect_uri parameter
    String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get(
            OAuth2Utils.REDIRECT_URI);

    if ((redirectUri != null || redirectUriApprovalParameter != null)
            && !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) {
        throw new RedirectMismatchException("Redirect URI mismatch.");
    }

    String pendingClientId = pendingOAuth2Request.getClientId();
    String clientId = tokenRequest.getClientId();
    if (clientId != null && !clientId.equals(pendingClientId)) {
        // just a sanity check.
        throw new InvalidClientException("Client ID mismatch");
    }

    // Secret is not required in the authorization request, so it won't be available
    // in the pendingAuthorizationRequest. We do want to check that a secret is provided
    // in the token request, but that happens elsewhere.

    Map<String, String> combinedParameters = new HashMap<String, String>(pendingOAuth2Request
            .getRequestParameters());
    // Combine the parameters adding the new ones last so they override if there are any clashes
    combinedParameters.putAll(parameters);

    // Make a new stored request with the combined parameters
    OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters);

    Authentication userAuth = storedAuth.getUserAuthentication();

    return new OAuth2Authentication(finalStoredOAuth2Request, userAuth);

}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:82,代码来源:CustomAuthCodeTokenGranter.java

示例4: extractAuthentication

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
	List<String> authorities = (List<String>) map.get(CLIENT_AUTHORITIES);
	Collection<GrantedAuthority> grantedAuthorities = authorities.stream().map(a -> new SimpleGrantedAuthority(a)).collect(Collectors.toList());

	OAuth2Authentication authentication = super.extractAuthentication(map);
	OAuth2Request request = authentication.getOAuth2Request();
	OAuth2Request enhancedRequest = new OAuth2Request(request.getRequestParameters(), request.getClientId(), grantedAuthorities, request.isApproved(), request.getScope(), request.getResourceIds(), request.getRedirectUri(), request.getResponseTypes(), request.getExtensions());

	return new OAuth2Authentication(enhancedRequest, authentication.getUserAuthentication());
}
 
开发者ID:PatternFM,项目名称:tokamak,代码行数:12,代码来源:JWTTokenConverter.java

示例5: getClientIdOrFail

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
@Override
public String getClientIdOrFail() {
    String clientId = null;

    OAuth2Request oAuth2Request = getAuthentication().getOAuth2Request();
    if (oAuth2Request != null) {
        clientId = oAuth2Request.getClientId();
    }
    if (clientId == null) {
        throw new InvalidACSRequestException("Authetication clientId cannot be null");
    }

    return clientId;
}
 
开发者ID:eclipse,项目名称:keti,代码行数:15,代码来源:SpringSecurityPolicyContextResolver.java

示例6: preHandle

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (!(authentication instanceof OAuth2Authentication)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        setErrorInResponse("Authorization without OAuth2 protocol.", response);
        return false;
    }

    OAuth2Authentication oauth2Authentication = (OAuth2Authentication) authentication;
    OAuth2Request clientAuthentication = oauth2Authentication.getOAuth2Request();
    String clientId = clientAuthentication.getClientId();
    Long userId = ((User) oauth2Authentication.getUserAuthentication().getPrincipal()).getId();

    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Integer hash = StaticUtls.getHashFrom(handlerMethod);

    Boolean permitted = permissionService.isPermitted(clientId, userId, hash);
    if (Objects.isNull(permitted)) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        setErrorInResponse(
                "Client and/or user haven't permission to access "
                + handlerMethod.getBeanType().getSimpleName().replace("RestControllerImpl", "")
                + "["
                + handlerMethod.getMethod().getName()
                + "]"
                + " method.", response);
        return false;
    }

    return permitted;
}
 
开发者ID:imCodePartnerAB,项目名称:iVIS,代码行数:35,代码来源:AccessApiInterceptor.java

示例7: getClientId

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
public String getClientId(String tokenValue) {
	OAuth2Authentication authentication = tokenStore
			.readAuthentication(tokenValue);
	if (authentication == null) {
		throw new InvalidTokenException("Invalid access token: "
				+ tokenValue);
	}
	OAuth2Request clientAuth = authentication.getOAuth2Request();
	if (clientAuth == null) {
		throw new InvalidTokenException(
				"Invalid access token (no client id): " + tokenValue);
	}
	return clientAuth.getClientId();
}
 
开发者ID:jungyang,项目名称:oauth-client-master,代码行数:15,代码来源:DefaultTokenServices.java

示例8: createUserContext

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
public UserContext createUserContext(OAuth2Authentication authentication, String token) {
  OAuth2Request oauth2Request = authentication.getOAuth2Request();
  String clientId = oauth2Request.getClientId();
  String grantType = oauth2Request.getGrantType();
  String userId = null;
  String userName = null;
  String issuer = null;
  long validFrom = 0;
  long validUntil = 0;
  String scope = null;

  if (token == null) {
    OAuth2AuthenticationDetails authDetails = (OAuth2AuthenticationDetails) authentication
        .getDetails();
    token = authDetails.getTokenValue();
  }

  OAuth2AccessToken accessToken;
  accessToken = resourceServerTokenServices.readAccessToken(token);


  if (accessToken != null) {
    Set<String> scopes = accessToken.getScope();
    scope = scopes == null ? null : String.join(",", scopes);

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    userName = (String) additionalInformation.get("user_name");
    userId = (String) additionalInformation.get("user_id");
    issuer = (String) additionalInformation.get("iss");
    validFrom = claimValueAsLong(additionalInformation);
    validUntil = accessToken.getExpiration().toInstant().getEpochSecond();
  }

  return new UserContext(
      userId,
      userName,
      issuer,
      validFrom,
      validUntil,
      clientId,
      scope,
      grantType,
      UserContext.AUTH_METHOD_UAA
  );
}
 
开发者ID:cloudfoundry-incubator,项目名称:credhub,代码行数:46,代码来源:UserContextFactory.java

示例9: getOAuth2Authentication

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

    Map<String, String> parameters = tokenRequest.getRequestParameters();
    String authorizationCode = parameters.get("code");
    String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);

    if (authorizationCode == null) {
        throw new InvalidRequestException("An authorization code must be supplied.");
    }

    OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }

    OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request();
    // https://jira.springsource.org/browse/SECOAUTH-333
    // This might be null, if the authorization was done without the redirect_uri parameter
    String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);

    if (redirectUriApprovalParameter != null && redirectUri == null
            || redirectUriApprovalParameter != null
            && !pendingOAuth2Request.getRedirectUri().startsWith(redirectUri)) {
        throw new RedirectMismatchException("Redirect URI mismatch.");
    }

    String pendingClientId = pendingOAuth2Request.getClientId();
    String clientId = tokenRequest.getClientId();
    if (clientId != null && !clientId.equals(pendingClientId)) {
        // just a sanity check.
        throw new InvalidClientException("Client ID mismatch");
    }

    // Secret is not required in the authorization request, so it won't be available
    // in the pendingAuthorizationRequest. We do want to check that a secret is provided
    // in the token request, but that happens elsewhere.

    Map<String, String> combinedParameters = new HashMap<>(pendingOAuth2Request.getRequestParameters());
    // Combine the parameters adding the new ones last so they override if there are any clashes
    combinedParameters.putAll(parameters);

    // Make a new stored request with the combined parameters
    OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters);

    Authentication userAuth = storedAuth.getUserAuthentication();

    return new OAuth2Authentication(finalStoredOAuth2Request, userAuth);
}
 
开发者ID:osiam,项目名称:auth-server,代码行数:50,代码来源:LessStrictRedirectUriAuthorizationCodeTokenGranter.java

示例10: getOAuth2Authentication

import org.springframework.security.oauth2.provider.OAuth2Request; //导入方法依赖的package包/类
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

	Map<String, String> parameters = tokenRequest.getRequestParameters();
	String authorizationCode = parameters.get("code");
	String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);

	if (authorizationCode == null) {
		throw new InvalidRequestException("An authorization code must be supplied.");
	}

	OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
	if (storedAuth == null) {
		throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
	}

	OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request();
	// https://jira.springsource.org/browse/SECOAUTH-333
	// This might be null, if the authorization was done without the redirect_uri parameter
	String redirectUriApprovalParameter = pendingOAuth2Request.getRequestParameters().get(
			OAuth2Utils.REDIRECT_URI);

	if ((redirectUri != null || redirectUriApprovalParameter != null)
			&& !pendingOAuth2Request.getRedirectUri().equals(redirectUri)) {
		throw new RedirectMismatchException("Redirect URI mismatch.");
	}

	String pendingClientId = pendingOAuth2Request.getClientId();
	String clientId = tokenRequest.getClientId();
	if (clientId != null && !clientId.equals(pendingClientId)) {
		// just a sanity check.
		throw new InvalidClientException("Client ID mismatch");
	}

	// Secret is not required in the authorization request, so it won't be available
	// in the pendingAuthorizationRequest. We do want to check that a secret is provided
	// in the token request, but that happens elsewhere.

	Map<String, String> combinedParameters = new HashMap<String, String>(pendingOAuth2Request
			.getRequestParameters());
	// Combine the parameters adding the new ones last so they override if there are any clashes
	combinedParameters.putAll(parameters);
	
	// Make a new stored request with the combined parameters
	OAuth2Request finalStoredOAuth2Request = pendingOAuth2Request.createOAuth2Request(combinedParameters);
	
	Authentication userAuth = storedAuth.getUserAuthentication();
	
	return new OAuth2Authentication(finalStoredOAuth2Request, userAuth);

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


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