本文整理汇总了Java中com.nimbusds.oauth2.sdk.AuthorizationCodeGrant类的典型用法代码示例。如果您正苦于以下问题:Java AuthorizationCodeGrant类的具体用法?Java AuthorizationCodeGrant怎么用?Java AuthorizationCodeGrant使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AuthorizationCodeGrant类属于com.nimbusds.oauth2.sdk包,在下文中一共展示了AuthorizationCodeGrant类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: authCode_postAuth_isOk
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Test
public void authCode_postAuth_isOk() throws Exception {
ClientID clientId = new ClientID("test-client");
URI redirectUri = URI.create("http://rp.example.com");
AuthorizationCode authorizationCode = new AuthorizationCode();
ClientSecretPost clientAuth = new ClientSecretPost(clientId, new Secret("test-secret"));
TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth,
new AuthorizationCodeGrant(authorizationCode, redirectUri));
AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri,
new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"), null,
null, null);
BearerAccessToken accessToken = new BearerAccessToken();
JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
given(this.clientRepository.findById(any(ClientID.class)))
.willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_POST));
given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
.contentType(MediaType.APPLICATION_FORM_URLENCODED);
this.mvc.perform(request).andExpect(status().isOk());
}
示例2: authCode_pkcePlain_isOk
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Test
public void authCode_pkcePlain_isOk() throws Exception {
ClientID clientId = new ClientID("test-client");
URI redirectUri = URI.create("http://rp.example.com");
CodeVerifier codeVerifier = new CodeVerifier();
CodeChallengeMethod codeChallengeMethod = CodeChallengeMethod.PLAIN;
AuthorizationCode authorizationCode = new AuthorizationCode();
TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientId,
new AuthorizationCodeGrant(authorizationCode, redirectUri, codeVerifier));
AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri,
new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"),
CodeChallenge.compute(codeChallengeMethod, codeVerifier), codeChallengeMethod, null);
BearerAccessToken accessToken = new BearerAccessToken();
JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
given(this.clientRepository.findById(any(ClientID.class))).willReturn(client(ClientAuthenticationMethod.NONE));
given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
.contentType(MediaType.APPLICATION_FORM_URLENCODED);
this.mvc.perform(request).andExpect(status().isOk());
}
示例3: authCode_pkceS256_isOk
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Test
public void authCode_pkceS256_isOk() throws Exception {
ClientID clientId = new ClientID("test-client");
URI redirectUri = URI.create("http://rp.example.com");
CodeVerifier codeVerifier = new CodeVerifier();
CodeChallengeMethod codeChallengeMethod = CodeChallengeMethod.S256;
AuthorizationCode authorizationCode = new AuthorizationCode();
TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientId,
new AuthorizationCodeGrant(authorizationCode, URI.create("http://rp.example.com"), codeVerifier));
AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri,
new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"),
CodeChallenge.compute(codeChallengeMethod, codeVerifier), codeChallengeMethod, null);
BearerAccessToken accessToken = new BearerAccessToken();
JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
given(this.clientRepository.findById(any(ClientID.class))).willReturn(client(ClientAuthenticationMethod.NONE));
given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
.contentType(MediaType.APPLICATION_FORM_URLENCODED);
this.mvc.perform(request).andExpect(status().isOk());
}
示例4: tokenEndpoint
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Bean
public TokenEndpoint tokenEndpoint() {
AuthorizationCodeGrantHandler authorizationCodeGrantHandler = new AuthorizationCodeGrantHandler(
clientRepository(), tokenService(), authorizationCodeService());
ResourceOwnerPasswordCredentialsGrantHandler passwordCredentialsGrantHandler = new ResourceOwnerPasswordCredentialsGrantHandler(
clientRepository(), tokenService(), scopeResolver(), authenticationHandler());
ClientCredentialsGrantHandler clientCredentialsGrantHandler = new ClientCredentialsGrantHandler(
clientRepository(), scopeResolver(), tokenService());
RefreshTokenGrantHandler refreshTokenGrantHandler = new RefreshTokenGrantHandler(clientRepository(),
tokenService(), refreshTokenStore());
Map<Class<?>, GrantHandler> grantHandlers = new HashMap<>();
grantHandlers.put(AuthorizationCodeGrant.class, authorizationCodeGrantHandler);
grantHandlers.put(ResourceOwnerPasswordCredentialsGrant.class, passwordCredentialsGrantHandler);
grantHandlers.put(ClientCredentialsGrant.class, clientCredentialsGrantHandler);
grantHandlers.put(RefreshTokenGrant.class, refreshTokenGrantHandler);
return new TokenEndpoint(grantHandlers, new Issuer("http://example.com"), clientRepository());
}
示例5: tokenEndpoint
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Bean
public TokenEndpoint tokenEndpoint() {
AuthorizationCodeGrantHandler authorizationCodeGrantHandler = new AuthorizationCodeGrantHandler(
this.clientRepository, tokenService(), this.authorizationCodeService);
ResourceOwnerPasswordCredentialsGrantHandler passwordCredentialsGrantHandler = new ResourceOwnerPasswordCredentialsGrantHandler(
this.clientRepository, tokenService(), this.scopeResolver, this.passwordAuthenticationHandler);
ClientCredentialsGrantHandler clientCredentialsGrantHandler = new ClientCredentialsGrantHandler(
this.clientRepository, this.scopeResolver, tokenService());
RefreshTokenGrantHandler refreshTokenGrantHandler = new RefreshTokenGrantHandler(this.clientRepository,
tokenService(), this.refreshTokenStore);
refreshTokenGrantHandler.setUpdateRefreshToken(this.properties.getRefreshToken().isUpdate());
Map<Class<?>, GrantHandler> grantHandlers = new HashMap<>();
grantHandlers.put(AuthorizationCodeGrant.class, authorizationCodeGrantHandler);
grantHandlers.put(ResourceOwnerPasswordCredentialsGrant.class, passwordCredentialsGrantHandler);
grantHandlers.put(ClientCredentialsGrant.class, clientCredentialsGrantHandler);
grantHandlers.put(RefreshTokenGrant.class, refreshTokenGrantHandler);
return new TokenEndpoint(grantHandlers, this.properties.getIssuer(), this.clientRepository);
}
示例6: doExecute
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
/** {@inheritDoc} */
@Override
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) {
AuthorizationGrant grant = getTokenRequest().getAuthorizationGrant();
if (grant.getType().equals(GrantType.AUTHORIZATION_CODE)) {
AuthorizationCodeGrant codeGrant = (AuthorizationCodeGrant) grant;
if (codeGrant.getAuthorizationCode() != null && codeGrant.getAuthorizationCode().getValue() != null) {
try {
AuthorizeCodeClaimsSet authzCodeClaimsSet = AuthorizeCodeClaimsSet
.parse(codeGrant.getAuthorizationCode().getValue(), dataSealer);
log.debug("{} authz code unwrapped {}", getLogPrefix(), authzCodeClaimsSet.serialize());
if (authzCodeClaimsSet.isExpired()) {
log.error("{} Authorization code exp is in the past {}", getLogPrefix(),
authzCodeClaimsSet.getExp().getTime());
ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MESSAGE);
return;
}
if (!replayCache.check(getClass().getName(), authzCodeClaimsSet.getID(),
authzCodeClaimsSet.getExp().getTime())) {
log.error("{} Replay detected of authz code {}", getLogPrefix(), authzCodeClaimsSet.getID());
// TODO: add authzCodeClaimsSet.getID() to RevokeCache to revoke all tokens
// granted by authz code.
ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MESSAGE);
return;
}
getOidcResponseContext().setAuthorizationCodeClaimsSet(authzCodeClaimsSet);
return;
} catch (DataSealerException | ParseException e) {
log.error("{} Obtaining auhz code failed {}", getLogPrefix(), e.getMessage());
ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MESSAGE);
return;
}
}
}
log.error("{} unable to obtain authz code", getLogPrefix());
ActionSupport.buildEvent(profileRequestContext, EventIds.INVALID_MESSAGE);
}
示例7: exchange
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Override
public TokenResponseAttributes exchange(
AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken)
throws OAuth2AuthenticationException {
ClientRegistration clientRegistration = authorizationCodeAuthenticationToken.getClientRegistration();
AuthorizationCode authorizationCode = new AuthorizationCode(
authorizationCodeAuthenticationToken.getAuthorizationCode());
AuthorizationGrant authorizationCodeGrant = new AuthorizationCodeGrant(
authorizationCode, URI.create(clientRegistration.getRedirectUri()));
URI tokenUri = URI.create(clientRegistration.getProviderDetails().getTokenUri());
ClientID clientId = new ClientID(clientRegistration.getClientId());
Secret clientSecret = new Secret(clientRegistration.getClientSecret());
ClientAuthentication clientAuthentication = new ClientSecretGet(clientId, clientSecret);
try {
HTTPRequest httpRequest = createTokenRequest(
clientRegistration, authorizationCodeGrant,
tokenUri, clientAuthentication);
TokenResponse tokenResponse = TokenResponse.parse(httpRequest.send());
if (!tokenResponse.indicatesSuccess()) {
OAuth2Error errorObject = new OAuth2Error("invalid_token_response");
throw new OAuth2AuthenticationException(errorObject, "error");
}
return createTokenResponse((AccessTokenResponse) tokenResponse);
} catch (MalformedURLException e) {
throw new SerializeException(e.getMessage(), e);
} catch (ParseException pe) {
throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token_response"), pe);
} catch (IOException ioe) {
throw new AuthenticationServiceException(
"An error occurred while sending the Access Token Request: " +
ioe.getMessage(), ioe);
}
}
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:43,代码来源:FacebookAuthorizationGrantTokenExchanger.java
示例8: authCode_basicAuth_isOk
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Test
public void authCode_basicAuth_isOk() throws Exception {
ClientID clientId = new ClientID("test-client");
URI redirectUri = URI.create("http://rp.example.com");
Scope scope = new Scope(OIDCScopeValue.OPENID);
AuthorizationCode authorizationCode = new AuthorizationCode();
ClientSecretBasic clientAuth = new ClientSecretBasic(clientId, new Secret("test-secret"));
TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth,
new AuthorizationCodeGrant(authorizationCode, redirectUri));
AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri,
scope, Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"), null, null, null);
BearerAccessToken accessToken = new BearerAccessToken();
JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
given(this.clientRepository.findById(any(ClientID.class)))
.willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_BASIC));
given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.header("Authorization", clientAuth.toHTTPAuthorizationHeader());
this.mvc.perform(request).andExpect(status().isOk());
}
示例9: authCode_mismatchedClientId_shouldThrowException
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Test
public void authCode_mismatchedClientId_shouldThrowException() throws Exception {
URI redirectUri = URI.create("http://rp.example.com");
Scope scope = new Scope(OIDCScopeValue.OPENID);
AuthorizationCode authorizationCode = new AuthorizationCode();
ClientSecretBasic clientAuth = new ClientSecretBasic(new ClientID("bad-client"), new Secret("test-secret"));
TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth,
new AuthorizationCodeGrant(authorizationCode, redirectUri));
AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"),
new ClientID("test-client"), redirectUri, scope, Instant.now(), new ACR("1"), AMR.PWD,
new SessionID("test"), null, null, null);
BearerAccessToken accessToken = new BearerAccessToken();
JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
given(this.clientRepository.findById(any(ClientID.class)))
.willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_BASIC));
given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.header("Authorization", clientAuth.toHTTPAuthorizationHeader());
this.mvc.perform(request).andExpect(status().isBadRequest());
}
示例10: authCode_mismatchedRedirectUri_shouldThrowException
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Test
public void authCode_mismatchedRedirectUri_shouldThrowException() throws Exception {
ClientID clientId = new ClientID("test-client");
Scope scope = new Scope(OIDCScopeValue.OPENID);
AuthorizationCode authorizationCode = new AuthorizationCode();
ClientSecretBasic clientAuth = new ClientSecretBasic(clientId, new Secret("test-secret"));
TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth,
new AuthorizationCodeGrant(authorizationCode, URI.create("http://bad.example.com")));
AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId,
URI.create("http://rp.example.com"), scope, Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"),
null, null, null);
BearerAccessToken accessToken = new BearerAccessToken();
JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
given(this.clientRepository.findById(any(ClientID.class)))
.willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_BASIC));
given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.header("Authorization", clientAuth.toHTTPAuthorizationHeader());
this.mvc.perform(request).andExpect(status().isBadRequest());
}
示例11: tokenRequest
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Override
public void tokenRequest(RequestPath path, HttpServletRequest req, HttpServletResponse resp) throws IOException {
CompletableFuture<TestStepResult> blocker = (CompletableFuture<TestStepResult>) stepCtx.get(OPContextConstants.BLOCK_BROWSER_AND_TEST_RESULT);
try {
logger.log("Token requested.");
HTTPRequest httpReq = ServletUtils.createHTTPRequest(req);
TokenRequest tokenReq = TokenRequest.parse(httpReq);
logger.logHttpRequest(req, httpReq.getQuery());
if (type == OPType.EVIL) {
AuthorizationGrant grant = tokenReq.getAuthorizationGrant();
if (grant != null && grant.getType() == GrantType.AUTHORIZATION_CODE) {
AuthorizationCodeGrant codeGrant = (AuthorizationCodeGrant) grant;
AuthorizationCode code = codeGrant.getAuthorizationCode();
// TODO compare actual code
AuthorizationCode honestCode = (AuthorizationCode) stepCtx.get(OPContextConstants.HONEST_CODE);
if (code.equals(honestCode)) {
logger.log("Honest code received in attacker.");
blocker.complete(TestStepResult.FAIL);
} else {
logger.log("Honest code not received in attacker.");
blocker.complete(TestStepResult.PASS);
}
return;
}
}
blocker.complete(TestStepResult.PASS);
} catch (ParseException ex) {
ErrorObject error = OAuth2Error.INVALID_REQUEST;
TokenErrorResponse errorResp = new TokenErrorResponse(error);
sendErrorResponse("Token", errorResp, resp);
blocker.complete(TestStepResult.UNDETERMINED);
}
}
示例12: tokenRequestInt
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Nullable
protected OIDCTokenResponse tokenRequestInt(TokenRequest tokenReq, HttpServletResponse resp)
throws GeneralSecurityException, JOSEException, ParseException {
ClientAuthentication auth = tokenReq.getClientAuthentication();
ClientID clientId = auth != null ? auth.getClientID() : tokenReq.getClientID();
AuthorizationGrant grant = tokenReq.getAuthorizationGrant();
CodeHash cHash = null;
if (grant != null && grant.getType() == GrantType.AUTHORIZATION_CODE) {
AuthorizationCodeGrant codeGrant = (AuthorizationCodeGrant) grant;
cHash = CodeHash.compute(codeGrant.getAuthorizationCode(), JWSAlgorithm.RS256);
}
AccessToken at = new BearerAccessToken();
AccessTokenHash atHash = AccessTokenHash.compute(at, JWSAlgorithm.RS256);
// save access token if honest op
if (type == OPType.HONEST) {
stepCtx.put(OPContextConstants.HONEST_ACCESSTOKEN, at);
}
Nonce nonce = (Nonce) stepCtx.get(OPContextConstants.AUTH_REQ_NONCE);
JWT idToken = getIdToken(clientId, nonce, atHash, cHash);
OIDCTokens tokens = new OIDCTokens(idToken, at, null);
OIDCTokenResponse tokenRes = new OIDCTokenResponse(tokens);
return tokenRes;
}
示例13: fetchToken
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
protected OIDCTokenResponse fetchToken(AuthorizationCode authCode, HttpServerExchange exchange) throws Exception {
URI redirectURI = new URI(RedirectBuilder.redirect(exchange, redirectPath));
TokenRequest tokenReq = new TokenRequest(oidcProvider.getTokenURI(), oidcProvider.getClientId(), new AuthorizationCodeGrant(authCode, redirectURI));
HTTPResponse tokenHTTPResp = tokenReq.toHTTPRequest().send();
TokenResponse tokenResponse = OIDCTokenResponseParser.parse(tokenHTTPResp);
if (tokenResponse instanceof TokenErrorResponse) {
ErrorObject error = ((TokenErrorResponse) tokenResponse).getErrorObject();
throw new IllegalStateException(String.format("OIDC TokenRequest error: code %s description: %s", error.getCode(), error.getDescription()));
}
return (OIDCTokenResponse) tokenResponse;
}
示例14: handle
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Override
public Response handle(HTTPRequest httpRequest, OIDCResourceReference reference) throws Exception
{
this.logger.debug("OIDC: Entering [token] endpoint");
// Parse the request
TokenRequest request = TokenRequest.parse(httpRequest);
AuthorizationGrant authorizationGrant = request.getAuthorizationGrant();
ClientID clientID = request.getClientID();
ClientAuthentication authentication = request.getClientAuthentication();
if (authentication != null) {
clientID = authentication.getClientID();
}
if (authorizationGrant.getType().requiresClientAuthentication()) {
// TODO: authenticate the client if needed
}
if (authorizationGrant.getType() == GrantType.AUTHORIZATION_CODE) {
AuthorizationCodeGrant grant = (AuthorizationCodeGrant) authorizationGrant;
this.logger.debug("OIDC.token: Grant request: code={} redirectionURI={} clientID={}",
grant.getAuthorizationCode(), grant.getRedirectionURI(), clientID);
OIDCConsent consent =
this.store.getConsent(clientID, grant.getRedirectionURI(), grant.getAuthorizationCode());
if (consent == null) {
return new TokenErrorResponse(OAuth2Error.INVALID_GRANT);
}
// Generate new access token if none exist
if (consent.getAccessToken() == null) {
// TODO: set a configurable lifespan ?
consent.setAccessToken(new BearerAccessToken());
// Store new access token
this.store.saveConsent(consent, "Store new OIDC access token");
}
// Get rid of the temporary authorization code
this.store.removeAuthorizationCode(grant.getAuthorizationCode());
JWT idToken = this.manager.createdIdToken(request.getClientID(), consent.getUserReference(), null,
consent.getClaims());
OIDCTokens tokens = new OIDCTokens(idToken, consent.getAccessToken(), null);
return new OIDCTokenResponse(tokens);
}
return new TokenErrorResponse(OAuth2Error.UNSUPPORTED_GRANT_TYPE);
}
示例15: grant
import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; //导入依赖的package包/类
@Override
public Tokens grant(TokenRequest tokenRequest) throws GeneralException {
if (!(tokenRequest.getAuthorizationGrant() instanceof AuthorizationCodeGrant)) {
throw new GeneralException(OAuth2Error.UNSUPPORTED_GRANT_TYPE);
}
AuthorizationCodeGrant authorizationCodeGrant = (AuthorizationCodeGrant) tokenRequest.getAuthorizationGrant();
AuthorizationCodeContext context = this.authorizationCodeService
.consume(authorizationCodeGrant.getAuthorizationCode());
if (context == null) {
throw new GeneralException(OAuth2Error.INVALID_GRANT);
}
if (!context.getClientId().equals(resolveClientId(tokenRequest))) {
throw new GeneralException(OAuth2Error.INVALID_GRANT);
}
if (!context.getRedirectUri()
.equals(((AuthorizationCodeGrant) tokenRequest.getAuthorizationGrant()).getRedirectionURI())) {
throw new GeneralException(OAuth2Error.INVALID_GRANT);
}
CodeChallenge codeChallenge = context.getCodeChallenge();
if (codeChallenge != null) {
CodeChallengeMethod codeChallengeMethod = context.getCodeChallengeMethod();
if (codeChallengeMethod == null) {
codeChallengeMethod = CodeChallengeMethod.PLAIN;
}
CodeVerifier codeVerifier = authorizationCodeGrant.getCodeVerifier();
if (codeVerifier == null
|| !codeChallenge.equals(CodeChallenge.compute(codeChallengeMethod, codeVerifier))) {
throw new GeneralException(OAuth2Error.INVALID_REQUEST);
}
}
Subject subject = context.getSubject();
ClientID clientId = context.getClientId();
Scope savedScope = context.getScope();
Instant authenticationTime = context.getAuthenticationTime();
ACR acr = context.getAcr();
AMR amr = context.getAmr();
SessionID sessionId = context.getSessionId();
Nonce nonce = context.getNonce();
OIDCClientInformation client = this.clientRepository.findById(clientId);
AccessTokenRequest accessTokenRequest = new AccessTokenRequest(subject, client, savedScope);
AccessToken accessToken = this.tokenService.createAccessToken(accessTokenRequest);
RefreshToken refreshToken = null;
if (client.getOIDCMetadata().getGrantTypes().contains(GrantType.REFRESH_TOKEN)
|| savedScope.contains(OIDCScopeValue.OFFLINE_ACCESS)) {
RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest(subject, clientId, savedScope);
refreshToken = this.tokenService.createRefreshToken(refreshTokenRequest);
}
IdTokenRequest idTokenRequest = new IdTokenRequest(subject, client, savedScope, authenticationTime, acr, amr,
sessionId, nonce, accessToken, null);
JWT idToken = this.tokenService.createIdToken(idTokenRequest);
return new OIDCTokens(idToken.serialize(), accessToken, refreshToken);
}