• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java HTTPRequest类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: createTokenRequest

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
private HTTPRequest createTokenRequest(ClientRegistration clientRegistration,
       AuthorizationGrant authorizationCodeGrant, URI tokenUri,
       ClientAuthentication clientAuthentication) throws MalformedURLException {

    HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.GET, tokenUri.toURL());
    httpRequest.setContentType(CommonContentTypes.APPLICATION_URLENCODED);
    clientAuthentication.applyTo(httpRequest);
    Map<String,String> params = httpRequest.getQueryParameters();
    params.putAll(authorizationCodeGrant.toParameters());
    if (clientRegistration.getScope() != null && !clientRegistration.getScope().isEmpty()) {
        params.put("scope", clientRegistration.getScope().stream().reduce((a, b) -> a + " " + b).get());
    }
    if (clientRegistration.getClientId() != null) {
        params.put("client_id", clientRegistration.getClientId());
    }
    httpRequest.setQuery(URLUtils.serializeParameters(params));
    httpRequest.setAccept(MediaType.APPLICATION_JSON_VALUE);
    httpRequest.setConnectTimeout(30000);
    httpRequest.setReadTimeout(30000);
    return httpRequest;
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:22,代码来源:FacebookAuthorizationGrantTokenExchanger.java


示例2: applyTo

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@Override
public void applyTo(final HTTPRequest httpRequest) {
    if (httpRequest.getMethod() != HTTPRequest.Method.GET)
        throw new SerializeException("The HTTP request method must be GET");

    ContentType ct = httpRequest.getContentType();
    if (ct == null)
        throw new SerializeException("Missing HTTP Content-Type header");

    if (! ct.match(CommonContentTypes.APPLICATION_URLENCODED))
        throw new SerializeException("The HTTP Content-Type header must be "
        + CommonContentTypes.APPLICATION_URLENCODED);

    Map<String,String> params = httpRequest.getQueryParameters();
    params.putAll(toParameters());
    String queryString = URLUtils.serializeParameters(params);
    httpRequest.setQuery(queryString);
}
 
开发者ID:PacktPublishing,项目名称:OAuth-2.0-Cookbook,代码行数:19,代码来源:ClientSecretGet.java


示例3: getClientRegistrations

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@GetMapping
public void getClientRegistrations(HttpServletRequest request, HttpServletResponse response) throws Exception {
	HTTPRequest httpRequest = ServletUtils.createHTTPRequest(request);

	try {
		String authorizationHeader = httpRequest.getAuthorization();

		if (authorizationHeader == null) {
			throw new GeneralException(BearerTokenError.INVALID_TOKEN);
		}

		BearerAccessToken requestAccessToken = BearerAccessToken.parse(authorizationHeader);
		validateAccessToken(requestAccessToken);
		List<OIDCClientInformation> clients = this.clientRepository.findAll();

		response.setContentType("application/json; charset=UTF-8");

		PrintWriter writer = response.getWriter();
		writer.print(toJsonObject(clients).toJSONString());
		writer.close();
	}
	catch (GeneralException e) {
		ClientRegistrationResponse registrationResponse = new ClientRegistrationErrorResponse(e.getErrorObject());
		ServletUtils.applyHTTPResponse(registrationResponse.toHTTPResponse(), response);
	}
}
 
开发者ID:vpavic,项目名称:simple-openid-provider,代码行数:27,代码来源:ClientRegistrationEndpoint.java


示例4: deleteClientConfiguration

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@DeleteMapping(path = "/{id:.*}")
public void deleteClientConfiguration(HttpServletRequest request, HttpServletResponse response,
		@PathVariable ClientID id) throws IOException {
	HTTPRequest httpRequest = ServletUtils.createHTTPRequest(request);

	try {
		ClientDeleteRequest clientDeleteRequest = ClientDeleteRequest.parse(httpRequest);
		resolveAndValidateClient(id, clientDeleteRequest);

		this.clientRepository.deleteById(id);

		response.setStatus(HttpServletResponse.SC_NO_CONTENT);
	}
	catch (GeneralException e) {
		ClientRegistrationResponse registrationResponse = new ClientRegistrationErrorResponse(e.getErrorObject());
		ServletUtils.applyHTTPResponse(registrationResponse.toHTTPResponse(), response);
	}
}
 
开发者ID:vpavic,项目名称:simple-openid-provider,代码行数:19,代码来源:ClientRegistrationEndpoint.java


示例5: getLogoutPrompt

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@GetMapping
public void getLogoutPrompt(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
	if (request.getQueryString() != null) {
		HTTPRequest httpRequest = ServletUtils.createHTTPRequest(request);

		try {
			LogoutRequest logoutRequest = LogoutRequest.parse(httpRequest.getQuery());
			request.setAttribute("redirectUri", logoutRequest.getPostLogoutRedirectionURI());
			request.setAttribute("state", logoutRequest.getState());
		}
		catch (ParseException ignored) {
		}
	}

	request.getRequestDispatcher("/logout").forward(request, response);
}
 
开发者ID:vpavic,项目名称:simple-openid-provider,代码行数:18,代码来源:EndSessionEndpoint.java


示例6: userInfoRequest

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@Override
public void userInfoRequest(RequestPath path, HttpServletRequest req, HttpServletResponse resp) throws IOException {
	try {
		logger.log("User Info requested.");

		HTTPRequest httpReq = ServletUtils.createHTTPRequest(req);
		UserInfoRequest userReq = UserInfoRequest.parse(httpReq);
		logger.logHttpRequest(req, httpReq.getQuery());
		
		UserInfoSuccessResponse uiResp = userInfoRequestInt(userReq, resp);
		if (uiResp != null) {
			sendResponse("User Info", uiResp, resp);
		}
	} catch (ParseException ex) {
		logger.log("Error parsing User Info Request.", ex);
		ErrorObject error = ex.getErrorObject();
		BearerTokenError be = new BearerTokenError(error.getCode(), error.getDescription(), error.getHTTPStatusCode());
		UserInfoErrorResponse errorResp = new UserInfoErrorResponse(be);
		sendErrorResponse("User Info", errorResp, resp);
	}
}
 
开发者ID:RUB-NDS,项目名称:PrOfESSOS,代码行数:22,代码来源:DefaultOP.java


示例7: handle

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@Override
public Response handle(HTTPRequest httpRequest, OIDCResourceReference reference) throws Exception
{
    Issuer issuer = this.manager.getIssuer();
    List<SubjectType> subjectTypes = Arrays.asList(SubjectType.PUBLIC);
    URI jwkSetURI = this.manager.createEndPointURI(JWKOIDCEndpoint.HINT);

    OIDCProviderMetadata metadata = new OIDCProviderMetadata(issuer, subjectTypes, jwkSetURI);

    metadata.setAuthorizationEndpointURI(this.manager.createEndPointURI(AuthorizationOIDCEndpoint.HINT));
    metadata.setTokenEndpointURI(this.manager.createEndPointURI(TokenOIDCEndpoint.HINT));
    metadata.setUserInfoEndpointURI(this.manager.createEndPointURI(UserInfoOIDCEndpoint.HINT));

    return new ContentResponse(CommonContentTypes.APPLICATION_JSON, metadata.toJSONObject().toString(),
        HTTPResponse.SC_OK);
}
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:17,代码来源:ConfigurationOIDCEnpoint.java


示例8: getConsent

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
private Boolean getConsent(HTTPRequest httpRequest)
{
    Map<String, String> parameters = httpRequest.getQueryParameters();

    // The user explicitly refused access to the client
    if (parameters.get("consent_refuse") != null) {
        return false;
    }

    // Check if user explicitly gave consent to the client
    if (parameters.get("consent_accept") != null) {
        String token = parameters.get("form_token");
        if (this.csrf.isTokenValid(token)) {
            return true;
        } else {
            // Looks like some client tried to hack consent
            // TODO: log something ? ban the client ?
        }
    }

    // Ask for user consent
    return null;
}
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:24,代码来源:AuthorizationOIDCEndpoint.java


示例9: updateUserInfo

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
public Principal updateUserInfo(URI userInfoEndpoint, IDTokenClaimsSet idToken, BearerAccessToken accessToken)
    throws IOException, ParseException, OIDCException, XWikiException, QueryException
{
    // Get OIDC user info
    UserInfoRequest userinfoRequest = new UserInfoRequest(userInfoEndpoint, accessToken);
    HTTPRequest userinfoHTTP = userinfoRequest.toHTTPRequest();
    userinfoHTTP.setHeader("User-Agent", this.getClass().getPackage().getImplementationTitle() + '/'
        + this.getClass().getPackage().getImplementationVersion());
    HTTPResponse httpResponse = userinfoHTTP.send();
    UserInfoResponse userinfoResponse = UserInfoResponse.parse(httpResponse);

    if (!userinfoResponse.indicatesSuccess()) {
        UserInfoErrorResponse error = (UserInfoErrorResponse) userinfoResponse;
        throw new OIDCException("Failed to get user info", error.getErrorObject());
    }

    UserInfoSuccessResponse userinfoSuccessResponse = (UserInfoSuccessResponse) userinfoResponse;
    UserInfo userInfo = userinfoSuccessResponse.getUserInfo();

    // Update/Create XWiki user
    return updateUser(idToken, userInfo);
}
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:23,代码来源:OIDCUserManager.java


示例10: exchange

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的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


示例11: validate

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@Override
public void validate(final OidcCredentials credentials, final WebContext context) throws HttpAction {
    init(context);

    final AuthorizationCode code = credentials.getCode();
    // if we have a code
    if (code != null) {
        try {
            // Token request
            final TokenRequest request = new TokenRequest(configuration.getProviderMetadata().getTokenEndpointURI(), this.clientAuthentication,
                    new AuthorizationCodeGrant(code, new URI(configuration.getCallbackUrl())));
            HTTPRequest tokenHttpRequest = request.toHTTPRequest();
            tokenHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
            tokenHttpRequest.setReadTimeout(configuration.getReadTimeout());

            final HTTPResponse httpResponse = tokenHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(),
                    httpResponse.getContent());

            final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
            if (response instanceof TokenErrorResponse) {
                throw new TechnicalException("Bad token response, error=" + ((TokenErrorResponse) response).getErrorObject());
            }
            logger.debug("Token response successful");
            final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;

            // save tokens in credentials
            final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens();
            credentials.setAccessToken(oidcTokens.getAccessToken());
            credentials.setRefreshToken(oidcTokens.getRefreshToken());
            credentials.setIdToken(oidcTokens.getIDToken());

        } catch (final URISyntaxException | IOException | ParseException e) {
            throw new TechnicalException(e);
        }
    }
}
 
开发者ID:yaochi,项目名称:pac4j-plus,代码行数:38,代码来源:OidcAuthenticator.java


示例12: tokenRequest

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的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);
	}

}
 
开发者ID:RUB-NDS,项目名称:PrOfESSOS,代码行数:40,代码来源:IdPConfusionOP.java


示例13: handle

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@Override
public Response handle(HTTPRequest httpRequest, OIDCResourceReference reference) throws Exception
{
    // Parse the request
    UserInfoRequest request = UserInfoRequest.parse(httpRequest);

    // Get the token associated to the user
    AccessToken accessToken = request.getAccessToken();

    // UserInfoSuccessResponse
    return null;
}
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:13,代码来源:JWKOIDCEndpoint.java


示例14: handle

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的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);
}
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:56,代码来源:TokenOIDCEndpoint.java


示例15: askConsent

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
private Response askConsent(AuthorizationRequest request, HTTPRequest httpRequest, ClaimsRequest resolvedClaims)
    throws Exception
{
    // Set various information in the script context
    Map<String, Object> oidc = new HashMap<>();
    oidc.put("request", request);
    oidc.put("httprequest", httpRequest);
    oidc.put("resolvedClaims", resolvedClaims);
    this.scripts.getScriptContext().setAttribute("oidc", oidc, ScriptContext.ENGINE_SCOPE);

    return this.manager.executeTemplate("oidc/provider/consent.vm", request);
}
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:13,代码来源:AuthorizationOIDCEndpoint.java


示例16: fetchOidcProviderConfig

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
/**
 * Fetches Open ID Connect provider configuration, according to the OpenID Connect discovery specification (cf.
 * http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig)
 * 
 * @param providerURI
 * @return
 * @throws IOException
 */
private JSONObject fetchOidcProviderConfig(String providerURI) throws IOException {
	JSONObject result = new JSONObject();

	// send Open ID Provider Config request
	// (cf. http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig)
	URL pConfigDocUri = new URL(providerURI + "/.well-known/openid-configuration");
	HTTPRequest pConfigRequest = new HTTPRequest(Method.GET, pConfigDocUri);

	// parse JSON result
	try {
		String configStr = pConfigRequest.send().getContent();
		JSONObject config = (JSONObject) JSONValue.parseWithException(configStr);
		// put JSON result in result table
		result.put("config", config);
	} catch (Exception e) {
		System.out.println("OpenID Connect Provider " + providerURI + " unreachable!");
		System.err
				.println("Make sure to set a correct OpenID Connect Provider URL in your las2peer Web Connector config!");
		System.out.println("WebConnector will now run in OIDC agnostic mode.");
		logError("Could not retrieve a valid OIDC provider config from " + providerURI + "!");

		return null;
	}

	return result;
}
 
开发者ID:rwth-acis,项目名称:las2peer-WebConnector,代码行数:35,代码来源:WebConnector.java


示例17: create

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@Override
@SuppressWarnings("unchecked")
public U create(final OidcCredentials credentials, final WebContext context) throws HttpAction {
    init(context);

    final AccessToken accessToken = credentials.getAccessToken();

    // Create profile
    final U profile = getProfileFactory().get();
    profile.setAccessToken(accessToken);
    final JWT idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    // Check if there is a refresh token
    final RefreshToken refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        logger.debug("Refresh Token successful retrieved");
    }

    try {

        // check idToken
        final Nonce nonce;
        if (configuration.isUseNonce()) {
            nonce = new Nonce((String) context.getSessionAttribute(OidcConfiguration.NONCE_SESSION_ATTRIBUTE));
        } else {
            nonce = null;
        }
        // Check ID Token
        final IDTokenClaimsSet claimsSet = this.idTokenValidator.validate(idToken, nonce);
        assertNotNull("claimsSet", claimsSet);
        profile.setId(claimsSet.getSubject());

        // User Info request
        if (configuration.getProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
            final UserInfoRequest userInfoRequest = new UserInfoRequest(configuration.getProviderMetadata().getUserInfoEndpointURI(), (BearerAccessToken) accessToken);
            final HTTPRequest userInfoHttpRequest = userInfoRequest.toHTTPRequest();
            userInfoHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
            userInfoHttpRequest.setReadTimeout(configuration.getReadTimeout());
            final HTTPResponse httpResponse = userInfoHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(),
                    httpResponse.getContent());

            final UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoErrorResponse) {
                logger.error("Bad User Info response, error={}",
                        ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
            } else {
                final UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
                final UserInfo userInfo = userInfoSuccessResponse.getUserInfo();
                if (userInfo != null) {
                    profile.addAttributes(userInfo.toJWTClaimsSet().getClaims());
                }
            }
        }

        // add attributes of the ID token if they don't already exist
        for (final Map.Entry<String, Object> entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            if (profile.getAttribute(key) == null) {
                profile.addAttribute(key, value);
            }
        }

        return profile;

    } catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
        throw new TechnicalException(e);
    }
}
 
开发者ID:yaochi,项目名称:pac4j-plus,代码行数:72,代码来源:OidcProfileCreator.java


示例18: handle

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@Override
public Response handle(HTTPRequest httpRequest, OIDCResourceReference reference) throws Exception
{
    return new ContentResponse(ContentResponse.CONTENTTYPE_PLAIN, "", 404);
}
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:6,代码来源:UnknownOIDCEndpoint.java


示例19: handle

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
@Override
public Response handle(HTTPRequest httpRequest, OIDCResourceReference reference) throws Exception
{
    // Parse the request
    AuthorizationResponse authorizationResponse = AuthorizationResponse.parse(httpRequest);

    // Validate state
    State state = authorizationResponse.getState();
    if (!Objects.equal(state, this.configuration.getSessionState())) {
        throw new OIDCException("Invalid state [" + state + "]");
    }
    // TODO: remove the state from the session ?

    // Deal with errors
    if (!authorizationResponse.indicatesSuccess()) {
        // Cast to error response
        AuthorizationErrorResponse errorResponse = (AuthorizationErrorResponse) authorizationResponse;

        // If impossible to authenticate without prompt, just ignore and redirect
        if (OIDCError.INTERACTION_REQUIRED.getCode().equals(errorResponse.getErrorObject().getCode())
            || OIDCError.LOGIN_REQUIRED.getCode().equals(errorResponse.getErrorObject().getCode())) {
            // Redirect to original request
            return new RedirectResponse(new URI(authorizationResponse.getState().getValue()));
        }
    }

    // Cast to success response
    AuthorizationSuccessResponse successResponse = (AuthorizationSuccessResponse) authorizationResponse;

    // Get authorization code
    AuthorizationCode code = successResponse.getAuthorizationCode();

    // Generate callback URL
    URI callback = this.oidc.createEndPointURI(CallbackOIDCEndpoint.HINT);

    // Get access token
    AuthorizationGrant authorizationGrant = new AuthorizationCodeGrant(code, callback);
    // TODO: setup some client authentication, secret, all that
    TokenRequest tokeRequest = new TokenRequest(this.configuration.getTokenOIDCEndpoint(),
        this.configuration.getClientID(), authorizationGrant);
    HTTPRequest tokenHTTP = tokeRequest.toHTTPRequest();
    tokenHTTP.setHeader("User-Agent", this.getClass().getPackage().getImplementationTitle() + '/'
        + this.getClass().getPackage().getImplementationVersion());
    HTTPResponse httpResponse = tokenHTTP.send();

    if (httpResponse.getStatusCode() != HTTPResponse.SC_OK) {
        TokenErrorResponse error = TokenErrorResponse.parse(httpResponse);
        throw new OIDCException("Failed to get access token", error.getErrorObject());
    }

    OIDCTokenResponse tokenResponse = OIDCTokenResponse.parse(httpResponse);

    IDTokenClaimsSet idToken = new IDTokenClaimsSet(tokenResponse.getOIDCTokens().getIDToken().getJWTClaimsSet());
    BearerAccessToken accessToken = tokenResponse.getTokens().getBearerAccessToken();

    HttpSession session = ((ServletSession) this.container.getSession()).getHttpSession();

    // Store the access token in the session
    this.configuration.setIdToken(idToken);
    this.configuration.setAccessToken(accessToken);

    // Update/Create XWiki user
    Principal principal = this.users.updateUserInfo(accessToken);

    // Remember user in the session
    session.setAttribute(SecurityRequestWrapper.PRINCIPAL_SESSION_KEY, principal);

    // TODO: put enough information in the cookie to automatically authenticate when coming back

    // Redirect to original request
    return new RedirectResponse(this.configuration.getSuccessRedirectURI());
}
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:73,代码来源:CallbackOIDCEndpoint.java


示例20: handle

import com.nimbusds.oauth2.sdk.http.HTTPRequest; //导入依赖的package包/类
/**
 * Handle the request and return a {@link Response}.
 * 
 * @param httpRequest the HTTP request
 * @param reference the reference generated from the request
 * @return the {@link Response}
 * @throws Exception when failing to handle the request
 */
Response handle(HTTPRequest httpRequest, OIDCResourceReference reference) throws Exception;
 
开发者ID:xwiki-contrib,项目名称:oidc,代码行数:10,代码来源:OIDCEndpoint.java



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java Specialization类代码示例发布时间:2022-05-23
下一篇:
Java BoundingBox类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap