有没有OAuth2 java 官方的httpclient java

Java Code Example org.apache.oltu.oauth2.client.request.OAuthClientRequest
Java Code Examples for org.apache.oltu.oauth2.client.request.OAuthClientRequest
The following are top voted examples for showing how to use
org.apache.oltu.oauth2.client.request.OAuthClientRequest. These examples are extracted from open source projects.
You can vote up the examples you like and your votes will be used in our system to product
more good examples.
+ Save this class to your library
public static URL getOAuth2URL(OAuth2Provider provider, String returnUrl) {
log.trace(&getOAuth2URL {}&, provider);
String oAuth2Location = provider.getAuthLocation();
String oAuth2ClientId = provider.getClientId();
String scopes = Utils.toCsv(provider.getPermissionScopes(), false);
String state = toState(provider.getProviderId(), returnUrl);
OAuthClientRequest oAuthRequest = OAuthClientRequest
.authorizationLocation(oAuth2Location)
.setClientId(oAuth2ClientId)
.setResponseType(&code&)
.setScope(scopes)
.setState(state)
.setRedirectURI(provider.getRedirectURI())
.buildQueryMessage();
return new URL(oAuthRequest.getLocationUri());
} catch (OAuthSystemException oAuthSystemException) {
throw new RuntimeException(oAuthSystemException);
} catch (MalformedURLException malformedURLException) {
throw new RuntimeException(malformedURLException);
public OAuthAccessTokenResponse obtainAuth2Token(OAuth2Provider provider, String accessCode) throws OAuthSystemException, OAuthProblemException {
log.trace(&obtainAuth2Token code={}, provider={}&, accessCode, provider);
String oAuth2ClientId = provider.getClientId();
String oAuth2TokenLocation = provider.getTokenLocation();
String oAuth2ClientSecret = provider.getClientSecret();
String oAuth2RedirectURI = provider.getRedirectURI();
OAuthClientRequest oAuthRequest = OAuthClientRequest
.tokenLocation(oAuth2TokenLocation)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setRedirectURI(oAuth2RedirectURI)
.setCode(accessCode)
.setClientId(oAuth2ClientId)
.setClientSecret(oAuth2ClientSecret)
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
// This works for facebook
OAuthAccessTokenResponse oAuth2Response2 = oAuthClient.accessToken(oAuthRequest, OAuth2TokenResponse.class);
//return oAuth2R
// This might work for google
OAuthJSONAccessTokenR
//OAuthAccessTokenResponse oAuth2Response2 = oAuthClient.accessToken(oAuthRequest, OAuth2TokenResponse.class);
return oAuth2Response2;
private OAuthResourceResponse validateAccessToken(String ticket) {
OAuthResourceResponse resourceResponse =
Map&String, String& headers = Utils.getBasicAuthorizationHeader(userdetails_key, userdetails_secret);
OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(userdetails_location)
.setAccessToken(ticket).buildQueryMessage();
bearerClientRequest.setHeaders(headers);
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
resourceResponse = oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
} catch (OAuthSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new AuthenticationServiceException(e.getMessage());
}catch (OAuthProblemException e){
e.printStackTrace();
throw new AuthenticationServiceException(e.getMessage());
return resourceR
private String exchangeRefreshTokenForAccessToken(String refreshToken) {
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthClientRequest accesstoken_
accesstoken_request = OAuthClientRequest.tokenLocation(token_location)
.setGrantType(GrantType.REFRESH_TOKEN).setClientId(client_id)
.setClientSecret(clientsecret).setRedirectURI(redirecturl).setRefreshToken(refreshToken).buildBodyMessage();
(&Creating oAuthClient object.&);
(&Access token url being used: & + accesstoken_request.getLocationUri());
Map&String, String& headers = Utils.getBasicAuthorizationHeader(client_id, clientsecret);
//headers.put(&Content-Type&, &application/x-www-form-urlencoded&);
accesstoken_request.setHeaders(headers);
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accesstoken_request, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class);
(&accesstoken retreived: & + oAuthResponse.getAccessToken());
hSession.setAttribute(&accessToken&, oAuthResponse.getAccessToken());
hSession.setAttribute(&refreshToken&, oAuthResponse.getRefreshToken());
return oAuthResponse.getAccessToken();
} catch (OAuthSystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
hSession.removeAttribute(&refreshToken&);
hSession.removeAttribute(&accessToken&);
} catch (OAuthProblemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
hSession.removeAttribute(&refreshToken&);
hSession.removeAttribute(&accessToken&);
public &T extends OAuthClientResponse& T execute(OAuthClientRequest request, Map&String, String& headers,
String requestMethod, Class&T& responseClass)
throws OAuthSystemException, OAuthProblemException {
MediaType mediaType = MediaType.parse(&application/json&);
Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
if(headers != null) {
for (Entry&String, String& entry : headers.entrySet()) {
if (entry.getKey().equalsIgnoreCase(&Content-Type&)) {
mediaType = MediaType.parse(entry.getValue());
requestBuilder.addHeader(entry.getKey(), entry.getValue());
RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) :
requestBuilder.method(requestMethod, body);
Response response = client.newCall(requestBuilder.build()).execute();
return OAuthClientResponseFactory.createCustomResponse(
response.body().string(),
response.body().contentType().toString(),
response.code(),
responseClass);
} catch (IOException e) {
throw new OAuthSystemException(e);
public Response intercept(Chain chain)
throws IOException {
Request request = chain.request();
// If the request already have an authorization (eg. Basic auth), do nothing
if (request.header(&Authorization&) != null) {
return chain.proceed(request);
// If first time, get the token
OAuthClientRequest oAuthR
if (getAccessToken() == null) {
updateAccessToken(null);
// Build the request
Builder rb = request.newBuilder();
String requestAccessToken = new String(getAccessToken());
oAuthRequest = new OAuthBearerClientRequest(request.urlString())
.setAccessToken(requestAccessToken)
.buildHeaderMessage();
} catch (OAuthSystemException e) {
throw new IOException(e);
for ( Map.Entry&String, String& header : oAuthRequest.getHeaders().entrySet() ) {
rb.addHeader(header.getKey(), header.getValue());
rb.url( oAuthRequest.getLocationUri());
//Execute the request
Response response = chain.proceed(rb.build());
// 401 most likely indicates that access token has expired.
// Time to refresh and resend the request
if ( response.code() == HTTP_UNAUTHORIZED ) {
updateAccessToken(requestAccessToken);
return intercept( chain );
public &T extends OAuthAccessTokenResponse& T accessToken(
OAuthClientRequest request,
Class&T& responseClass)
throws OAuthSystemException, OAuthProblemException {
return accessToken(request, OAuth.HttpMethod.POST, responseClass);
public &T extends OAuthAccessTokenResponse& T accessToken(
OAuthClientRequest request, String requestMethod, Class&T& responseClass)
throws OAuthSystemException, OAuthProblemException {
Map&String, String& headers = new HashMap&String, String&();
headers.put(OAuth.HeaderType.CONTENT_TYPE, OAuth.ContentType.URL_ENCODED);
return httpClient.execute(request, headers, requestMethod, responseClass);
private OAuthClientRequest getaccessRequest(String tokenEndPoint,
String clientId,
String code,
String clientSecret,
String callbackurl)
throws AuthenticationFailedException {
OAuthClientRequest accessRequest =
accessRequest = OAuthClientRequest.tokenLocation(tokenEndPoint)
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId)
.setClientSecret(clientSecret).setRedirectURI(callbackurl).setCode(code)
.buildBodyMessage();
} catch (OAuthSystemException e) {
if (log.isDebugEnabled()) {
log.debug(&Exception while building request for request access token&, e);
throw new AuthenticationFailedException(e.getMessage(), e);
return accessR
Example 10
private OAuthClientResponse getOauthResponse(OAuthClient oAuthClient, OAuthClientRequest accessRequest)
throws AuthenticationFailedException {
OAuthClientResponse oAuthResponse =
oAuthResponse = oAuthClient.accessToken(accessRequest);
} catch (OAuthSystemException e) {
if (log.isDebugEnabled()) {
log.debug(&Exception while requesting access token&, e);
throw new AuthenticationFailedException(e.getMessage(), e);
} catch (OAuthProblemException e) {
if (log.isDebugEnabled()) {
log.debug(&Exception while requesting access token&, e);
return oAuthR
Example 11
protected String getAuthorizationUrl() {
state = new BigInteger(130, new SecureRandom()).toString(32);
OAuthClientRequest request = TraktV2.getAuthorizationRequest(
BuildConfig.TRAKT_CLIENT_ID,
BaseOAuthActivity.OAUTH_CALLBACK_URL_LOCALHOST,
return request.getLocationUri();
} catch (OAuthSystemException e) {
Timber.e(e, &Building auth request failed&);
Example 12
public void createAccessTokens() {
OAuthClientRequest tokenRequest =
if (!Role.EVERYONE.name().equals(role)) {
tokenRequest = OAuthClientRequest.tokenLocation(&https://dev.pyramus.fi:8443/1/oauth/token&)
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(mon.CLIENT_ID)
.setClientSecret(mon.CLIENT_SECRET).setRedirectURI(mon.REDIRECT_URL)
.setCode(mon.getRoleAuth(Common.strToRole(role))).buildBodyMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
Response response = given().contentType(&application/x-www-form-urlencoded&).body(tokenRequest.getBody())
.post(&/oauth/token&);
String accessToken = response.body().jsonPath().getString(&access_token&);
setAccessToken(accessToken);
setAccessToken(&&);
* AdminAccessToken
if (!Role.ADMINISTRATOR.name().equals(role)) {
tokenRequest =
tokenRequest = OAuthClientRequest.tokenLocation(&https://dev.pyramus.fi:8443/1/oauth/token&)
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(mon.CLIENT_ID)
.setClientSecret(mon.CLIENT_SECRET).setRedirectURI(mon.REDIRECT_URL)
.setCode(mon.getRoleAuth(Role.ADMINISTRATOR)).buildBodyMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
Response response = given().contentType(&application/x-www-form-urlencoded&).body(tokenRequest.getBody())
.post(&/oauth/token&);
String adminAccessToken = response.body().jsonPath().getString(&access_token&);
setAdminAccessToken(adminAccessToken);
setAdminAccessToken(accessToken);
Example 13
public Map&String, String& getAuthHeaders() {
OAuthClientRequest bearerClientRequest =
bearerClientRequest = new OAuthBearerClientRequest(&https://dev.pyramus.fi&)
.setAccessToken(this.getAccessToken()).buildHeaderMessage();
} catch (OAuthSystemException e) {
return bearerClientRequest.getHeaders();
Example 14
public void authorize(OAuthParams oauthParams, HttpServletRequest req,
HttpServletResponse res) throws OAuthSystemException, IOException{
Utils.validateAuthorizationParams(oauthParams, req.getServerName());
res.addCookie(new Cookie(&clientId&, oauthParams.getClientId()));
res.addCookie(new Cookie(&clientSecret&, oauthParams.getClientSecret()));
res.addCookie(new Cookie(&authzEndpoint&, oauthParams.getAuthzEndpoint()));
res.addCookie(new Cookie(&tokenEndpoint&, oauthParams.getTokenEndpoint()));
res.addCookie(new Cookie(&redirectUri&, oauthParams.getRedirectUri()));
res.addCookie(new Cookie(&scope&, oauthParams.getScope()));
res.addCookie(new Cookie(&state&, oauthParams.getState()));
res.addCookie(new Cookie(&app&, oauthParams.getApplication()));
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(oauthParams.getAuthzEndpoint())
.setClientId(oauthParams.getClientId())
.setRedirectURI(oauthParams.getRedirectUri())
.setResponseType(ResponseType.CODE.toString())
.setScope(oauthParams.getScope())
.setState(oauthParams.getState())
.buildQueryMessage();
res.sendRedirect(request.getLocationUri());
} catch (ApplicationException e) {
oauthParams.setErrorMessage(e.getMessage());
Example 15
public void testToken() throws RedditOAuthException, OAuthSystemException, OAuthProblemException {
// Captor for the request that is executed
ArgumentCaptor&OAuthClientRequest& clientCaptor = ArgumentCaptor.forClass(OAuthClientRequest.class);
when(mockOAuthClient.accessToken(any(OAuthClientRequest.class))).thenReturn(jsonToken);
// Run subject
RedditToken token = subject.token(code);
// Verify and capture
verify(mockOAuthClient).accessToken(clientCaptor.capture());
OAuthClientRequest request = clientCaptor.getValue();
assertNotNull(request.getHeader(&Authorization&)); // This is Base64 encoded
assertEquals(request.getHeader(&User-Agent&), userAgent);
assertEquals(accessToken, token.getAccessToken());
assertEquals(refreshToken, token.getRefreshToken());
assertEquals(tokenType, token.getTokenType());
assertEquals(expiresIn, token.getExpirationSpan());
assertTrue(token.hasScope(RedditScope.EDIT));
assertTrue(token.hasScope(RedditScope.FLAIR));
assertFalse(token.hasScope(RedditScope.PRIVATEMESSAGE));
Example 16
public void testTokenAppOnlyConfidential() throws RedditOAuthException, OAuthSystemException, OAuthProblemException {
// Captor for the request that is executed
ArgumentCaptor&OAuthClientRequest& clientCaptor = ArgumentCaptor.forClass(OAuthClientRequest.class);
when(mockOAuthClient.accessToken(any(OAuthClientRequest.class))).thenReturn(jsonTokenNonRefreshable);
// Run subject
RedditToken token = subject.tokenAppOnly(true);
// Verify and capture
verify(mockOAuthClient).accessToken(clientCaptor.capture());
OAuthClientRequest request = clientCaptor.getValue();
assertNotNull(request.getHeader(&Authorization&)); // This is Base64 encoded
assertEquals(request.getHeader(&User-Agent&), userAgent);
assertEquals(accessToken, token.getAccessToken());
assertNull(token.getRefreshToken());
assertEquals(tokenType, token.getTokenType());
assertEquals(expiresIn, token.getExpirationSpan());
assertTrue(token.hasScope(RedditScope.EDIT));
assertTrue(token.hasScope(RedditScope.FLAIR));
assertFalse(token.hasScope(RedditScope.PRIVATEMESSAGE));
Example 17
public static String requestOAuthLocationUri(final SiteContext context) {
final Company company = context.getObject(Company.class);
if (!company.isoAuthLogin()) {
OAuthClientRequest request = OAuthClientRequest
.authorizationProvider(OAuthProviderType.GITHUB)
.setClientId(company.getGitHubClientId())
.setRedirectURI(company.getUrl() + &oauthredirect&)
.setScope(&user:email&)
.buildQueryMessage();
return request.getLocationUri();
} catch (final Exception e) {
LOGGER.error(&Error in oauth.&, e);
Example 18
public void test_getAuthorizationRequest() throws OAuthSystemException {
OAuthClientRequest request = GetGlue.getAuthorizationRequest(CLIENT_ID, REDIRECT_URI);
System.out.println(&GetGlue Authorization URL: & + request.getLocationUri());
assertThat(request.getLocationUri())
.isEqualTo(&/oauth2/authorize&
+ &?scope=public+read+write&
+ &&response_type=code&
+ &&redirect_uri=http%3A%2F%2Flocalhost&
+ &&client_id=& + CLIENT_ID);
Example 19
public void test_getAccessTokenRequest() throws OAuthSystemException {
String code = &S0meRand0mS1uff&;
OAuthClientRequest request = GetGlue
.getAccessTokenRequest(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, code);
System.out.println(&GetGlue Access Token URL: & + request.getLocationUri());
assertThat(request.getLocationUri())
.isEqualTo(&/oauth2/access_token&
+ &?code=& + code
+ &&grant_type=authorization_code&
+ &&client_secret=& + CLIENT_SECRET
+ &&redirect_uri=http%3A%2F%2Flocalhost&
+ &&client_id=& + CLIENT_ID);
Example 20
* Create an end-user authorization request
* Use with {@literal response.setRedirect(request.getLocationUri());}
* @param request
* @return request URI
public String getEndUserAuthorizationRequestUri(final HttpServletRequest request) {
OAuthClientRequest oauthClientR
oauthClientRequest = OAuthClientRequest
.authorizationLocation(authorizationLocation)
.setClientId(clientId)
.setRedirectURI(getAbsoluteUrl(request, redirectUri))
.setScope(getScope())
.setResponseType(getResponseType())
.setState(getState())
.buildQueryMessage();
logger., &Authorization request location URI: {0}&, oauthClientRequest.getLocationUri());
return oauthClientRequest.getLocationUri();
} catch (OAuthSystemException ex) {
logger.log(Level.SEVERE, null, ex);
Example 21
private OAuthAccessTokenResponse getAccessTokenResponse(final HttpServletRequest request) {
if (tokenResponse != null) {
return tokenR
String code = getCode(request);
if (code == null) {
logger.log(Level.SEVERE, &Could not get code from request, cancelling authorization process&);
OAuthClientRequest clientReq = OAuthClientRequest
.tokenLocation(tokenLocation)
.setGrantType(getGrantType())
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectURI(getAbsoluteUrl(request, redirectUri))
.setCode(getCode(request))
.buildBodyMessage();
logger., &Request body: {0}&, clientReq.getBody());
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
tokenResponse = oAuthClient.accessToken(clientReq, tokenResponseClass);
logger., &Access token response: {0}&, tokenResponse.getBody());
return tokenR
} catch (Throwable t) {
logger.log(Level.SEVERE, &Could not get access token response&, t);
Example 22
public &T extends OAuthAccessTokenResponse& T accessToken(OAuthClientRequest request, Class&T& responseClass)
throws OAuthSystemException, OAuthProblemException {
oAuthClientRequest =
OAuthAccessTokenResponse response = mock(responseClass);
when(response.getOAuthToken()).thenReturn(new BasicOAuthToken(ACCESS_TOKEN, 3600L, REFRESH_TOKEN, &user&));
return (T)
Example 23
void extractAccessTokenForROPC(final OAuth2Parameters parameters) throws OAuthProblemException, OAuthSystemException {
OAuthClientRequest accessTokenRequest = getClientRequestForROPC(parameters);
OAuthClient oAuthClient = getOAuthClient();
OAuthToken oAuthToken = oAuthClient.accessToken(accessTokenRequest, OAuthJSONAccessTokenResponse.class).getOAuthToken();
parameters.applyRetrievedAccessToken(oAuthToken.getAccessToken());
parameters.setAccessTokenIssuedTimeInProfile(TimeUtils.getCurrentTimeInSeconds());
parameters.setAccessTokenExpirationTimeInProfile(oAuthToken.getExpiresIn());
parameters.setRefreshTokenInProfile(oAuthToken.getRefreshToken());
Example 24
protected void processOpenID(HttpServletRequest request, HttpServletResponse response, String provider, String returnURL, boolean isRegister) {
HttpSession session = request.getSession();
String state = generateState();
session.setAttribute(SA_REGISTRATION, isRegister);
session.setAttribute(SA_OPENID_PROVIDER, provider);
session.setAttribute(SA_STATE, state);
if (returnURL == null || returnURL.isEmpty()) {
returnURL = &/ui/admin&;
if (Oauth2Util.istUseHttps()) {
returnURL = returnURL.replaceFirst(&^/&, &&);
returnURL = uriInfo.getBaseUri().toString() + returnURL;
(String.format(&OAuth returnURL is %s&, returnURL));
String secureReturnURL = returnURL.replace(&http://&, &https://&);
session.setAttribute(SA_RETURN_URL, secureReturnURL);
session.setAttribute(SA_RETURN_URL, returnURL);
if (provider == null || provider.isEmpty()) {
provider = DEFAULT_PROVIDER;
(&Authentication request for & + provider + (isRegister ? & (registration)& : &&));
String responseURL = uriInfo.getBaseUri().toString() + &system/security/responseoa&;
if (Oauth2Util.istUseHttps()) {
responseURL = responseURL.replace(&http://&, &https://&);
(String.format(&response URL for auth request: %s&, responseURL));
session.setAttribute(SA_RESPONSE_URL, responseURL);
// obtain a AuthRequest message to be sent to the OpenID provider
OAuthClientRequest oauthRequest = OAuthClientRequest
.authorizationProvider(OAuthProviderType.GOOGLE)
.setClientId(Oauth2Util.getClientId())
.setRedirectURI(responseURL)
.setResponseType(ResponseType.CODE.toString())
.setScope(GOOGLE_SCOPE)
.setState(state)
.buildQueryMessage();
// For version2 endpoints can do a form-redirect but this is easier,
// Relies on payload being less ~ 2k, currently ~ 800 bytes
response.sendRedirect(oauthRequest.getLocationUri());
catch (Exception e)
throw new WebApiException(Status.BAD_REQUEST, &Login/registration action failed: & + e);
Example 25
public Response verifyResponse(HttpServletRequest request, HttpServletResponse httpresponse) {
OAuthParams oauthParams = new OAuthParams();
oauthParams.setClientId(Oauth2Util.getClientId());
oauthParams.setTokenEndpoint(OAuthProviderType.GOOGLE.getTokenEndpoint());
oauthParams.setResourceUrl(&/oauth2/v3/userinfo&);
HttpSession session = request.getSession();
// Create the response wrapper/o/oauth2/auth
// to the parameters from the authentication response
// (which comes in as a HTTP request from the OAuth provider)
OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
// Get Authorization Code
String code = oar.getCode();
oauthParams.setAuthzCode(code);
String responseUrl = (String) session.getAttribute(SA_RESPONSE_URL);
String accessToken = oar.getAccessToken();
OAuthClientRequest authzRequest = OAuthClientRequest
.tokenProvider(OAuthProviderType.GOOGLE)
.setClientId(Oauth2Util.getClientId())
.setClientSecret(Oauth2Util.getClientSecret())
.setRedirectURI(responseUrl)
.setCode(code)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.buildBodyMessage();
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthAccessTokenResponse oauthResponse =
Class&? extends OAuthAccessTokenResponse& cl = OAuthJSONAccessTokenResponse.
cl = OpenIdConnectResponse.
oauthResponse = client.accessToken(authzRequest, cl);
oauthParams.setAccessToken(oauthResponse.getAccessToken());
oauthParams.setExpiresIn(oauthResponse.getExpiresIn());
oauthParams.setRefreshToken(Oauth2Util.isIssued(oauthResponse.getRefreshToken()));
OpenIdConnectResponse openIdConnectResponse = ((OpenIdConnectResponse) oauthResponse);
JWT idToken = openIdConnectResponse.getIdToken();
oauthParams.setIdToken(idToken.getRawString());
oauthParams.setHeader(new JWTHeaderWriter().write(idToken.getHeader()));
oauthParams.setClaimsSet(new JWTClaimsSetWriter().write(idToken.getClaimsSet()));
URL url = new URL(oauthParams.getTokenEndpoint());
oauthParams.setIdTokenValid(openIdConnectResponse.checkId(url.getHost(), oauthParams.getClientId()));
OAuthClientRequest resRequest = new OAuthBearerClientRequest(oauthParams.getResourceUrl()).setAccessToken(oauthParams.getAccessToken()).buildHeaderMessage();
OAuthClient resClient = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse resourceResponse = resClient.resource(resRequest, oauthParams.getRequestMethod(), OAuthResourceResponse.class);
boolean verified =
if (resourceResponse.getResponseCode() == 200) {
oauthParams.setResource(resourceResponse.getBody());
verified =
oauthParams.setErrorMessage(
&Could not access resource: & + resourceResponse.getResponseCode() + & & + resourceResponse.getBody());
if (verified) {
ObjectMapper mapper = new ObjectMapper();
Map&String, Object& mapObject = mapper.readValue(oauthParams.getResource(), new TypeReference&Map&String, Object&&() {
String name = (String) mapObject.get(&name&);
String email = (String) mapObject.get(&email&);
String identifier = (String) mapObject.get(&profile&);
(String.format(&Verified identity /o/oauth2/authy %s = %s&, identifier, name));
UserStore userstore = Registry.get().getUserStore();
boolean isRegistration = ((Boolean) session.getAttribute(SA_REGISTRATION)).booleanValue();
String registrationStatus = RS_LOGIN;
if (isRegistration) {
UserInfo userinfo = new UserInfo(identifier, name);
if (userstore.register(userinfo)) {
registrationStatus = RS_NEW;
registrationStatus = RS_ALREADY_REGISTERED;
RegToken token = new RegToken(identifier, true);
Subject subject = SecurityUtils.getSubject();
subject.login(token);
session.setAttribute(VN_REGISTRATION_STATUS, registrationStatus);
String provider = (String) session.getAttribute(SA_OPENID_PROVIDER);
if (provider != null && !provider.isEmpty()) {
Cookie cookie = new Cookie(PROVIDER_COOKIE, provider);
cookie.setComment(&Records the openid provider you last used to log in to a UKGovLD registry&);
cookie.setMaxAge(60 * 60 * 24 * 30);
cookie.setHttpOnly(true);
cookie.setPath(&/&);
httpresponse.addCookie(cookie);
Login.setNocache(httpresponse);
return Login.redirectTo(session.getAttribute(SA_RETURN_URL).toString());
return RequestProcessor.render(&admin.vm&, uriInfo, servletContext, request, VN_SUBJECT, subject, VN_REGISTRATION_STATUS, registrationStatus);
} catch (Exception e) {
log.error(&Authentication failure: & + e);
return RequestProcessor.render(&error.vm&, uriInfo, servletContext, request, &message&, &Could not find a registration for you.&);
} catch (Exception e) {
throw new WebApplicationException(e);
return RequestProcessor.render(&error.vm&, uriInfo, servletContext, request, &message&, &OpenID Connect login failed&);
Example 26
private LoggedUser initToken(OAuthParams oauthParams,
HttpServletRequest req, HttpServletResponse response) throws OAuthSystemException, IOException, ServletException {
Utils.validateTokenParams(oauthParams, req.getServerName());
OAuthClientRequest request = OAuthClientRequest
.tokenLocation(oauthParams.getTokenEndpoint())
.setClientId(oauthParams.getClientId())
.setClientSecret(oauthParams.getClientSecret())
.setRedirectURI(oauthParams.getRedirectUri())
.setCode(oauthParams.getAuthzCode())
.setGrantType(GrantType.AUTHORIZATION_CODE).setParameter(OAuth.OAUTH_ACCESS_TOKEN, oauthParams.getAccessToken())
.buildBodyMessage();
URLConnectionClient httpClient = new URLConnectionClient();
OAuthClient client = new OAuthClient(httpClient);
String app = LoginUtils.findCookieValue(req, &app&);
OAuthAccessTokenResponse oauthResponse =
Class&? extends OAuthAccessTokenResponse& cl = OAuthJSONAccessTokenResponse.
if (Utils.FACEBOOK.equalsIgnoreCase(app)) {
cl = GitHubTokenResponse.
} else if (Utils.GOOGLE.equalsIgnoreCase(app)){
cl = OpenIdConnectResponse.
initCACerts(app, req);
oauthResponse = client.accessToken(request, cl);
oauthParams.setAccessToken(oauthResponse.getAccessToken());
//dirty workaround
if(Utils.FACEBOOK.equalsIgnoreCase(app)){
String[] bodySplit = oauthResponse.getBody().split(&&&);
if(bodySplit != null){
for (String line : bodySplit) {
if(line != null && line.startsWith(&expires=&)){
oauthParams.setExpiresIn(Long.parseLong(line.substring(&expires=&.length()))*1000);
oauthParams.setExpiresIn(oauthResponse.getExpiresIn());
oauthParams.setRefreshToken(Utils.isIssued(oauthResponse.getRefreshToken()));
if (Utils.GOOGLE.equalsIgnoreCase(app)){
fetchUserDataFromGoogle(oauthParams, oauthResponse);
return initOrCreateUser(req, response, oauthParams);
} catch (ApplicationException e) {
oauthParams.setErrorMessage(e.getMessage());
throw new ServletException(e);
} catch (OAuthProblemException e) {
StringBuffer sb = new StringBuffer();
sb.append(&&/br&&);
sb.append(&Error code: &).append(e.getError()).append(&&/br&&);
sb.append(&Error description: &).append(e.getDescription()).append(&&/br&&);
sb.append(&Error uri: &).append(e.getUri()).append(&&/br&&);
sb.append(&State: &).append(e.getState()).append(&&/br&&);
oauthParams.setErrorMessage(sb.toString());
throw new ServletException(sb.toString());
Example 27
public static User processOAuthRedirect(final SiteContext context, final Company company, String code) {
if (!company.isoAuthLogin()) {
final EntityManager entityManager = context.getEntityManager();
if (StringUtils.isEmpty(code)) {
LOGGER.warn(&Warning in oauth no code received in redirect.&);
final OAuthClientRequest oAuthClientRequest = OAuthClientRequest
.tokenProvider(OAuthProviderType.GITHUB)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(company.getGitHubClientId())
.setClientSecret(company.getGitHubClientSecret())
.setRedirectURI(company.getUrl() + &oauthredirect&)
.setCode(code)
.buildQueryMessage();
final OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
final GitHubTokenResponse oAuthResponse = oAuthClient.accessToken(oAuthClientRequest,
GitHubTokenResponse.class);
final String accessToken = oAuthResponse.getAccessToken();
final String primaryVerifiedEmail = getEmail(accessToken);
if (primaryVerifiedEmail == null) {
AuditService.log(context, &oauth login failed, no matching email&);
final User existingUser = UserDao.getUser(entityManager, company, primaryVerifiedEmail);
if (existingUser != null) {
if (existingUser.isLockedOut()) {
AuditService.log(context, &oauth login failed, locked user&, &User&, existingUser.getUserId(), existingUser.getEmailAddress());
AuditService.log(context, &oauth login success&, &User&, existingUser.getUserId(), existingUser.getEmailAddress());
return existingU
if (!company.isoAuthSelfRegistration()) {
final String name = primaryVerifiedEmail.split(&@&)[0];
final String[] nameParts = name.split(&\\.&);
final String firstName = capitalizeFirstLetter(nameParts[0]);
final String lastName = nameParts.length & 1 ? capitalizeFirstLetter(nameParts[nameParts.length - 1]) : &-&;
final String phoneNumber = &-&;
final User newUser = new User(company, firstName, lastName, primaryVerifiedEmail, phoneNumber, &&);
UserDao.addUser(entityManager, newUser, UserDao.getGroup(entityManager, company, &user&));
if (SiteModuleManager.isModuleInitialized(CustomerModule.class)) {
final Customer customer = new Customer(firstName, lastName, primaryVerifiedEmail, phoneNumber, false, &&, &&);
customer.setCreated(new Date());
customer.setModified(customer.getCreated());
customer.setOwner(company);
final PostalAddress invoicingAddress = new PostalAddress();
invoicingAddress.setAddressLineOne(&-&);
invoicingAddress.setAddressLineTwo(&-&);
invoicingAddress.setAddressLineThree(&-&);
invoicingAddress.setCity(&-&);
invoicingAddress.setPostalCode(&-&);
invoicingAddress.setCountry(&-&);
final PostalAddress deliveryAddress = new PostalAddress();
deliveryAddress.setAddressLineOne(&-&);
deliveryAddress.setAddressLineTwo(&-&);
deliveryAddress.setAddressLineThree(&-&);
deliveryAddress.setCity(&-&);
deliveryAddress.setPostalCode(&-&);
deliveryAddress.setCountry(&-&);
customer.setInvoicingAddress(invoicingAddress);
customer.setDeliveryAddress(deliveryAddress);
CustomerDao.addCustomer(entityManager, customer);
UserDao.addGroupMember(context.getEntityManager(), customer.getAdminGroup(), newUser);
UserDao.addGroupMember(context.getEntityManager(), customer.getMemberGroup(), newUser);
AuditService.log(context, &oauth-auto-register&, &user&, newUser.getUserId(), primaryVerifiedEmail);
return newU
} catch (final Exception e) {
LOGGER.error(&Error exchanging oauth code to access token: & + e.getMessage());
AuditService.log(context, &oauth login exception&);
Example 28
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest
&& response instanceof HttpServletResponse) {
// we're only interested in HTTP traffic
HttpServletRequest httpRequest = (HttpServletRequest)
String uid =
HttpSession session = httpRequest.getSession(false);
if (session != null) {
Object uidObject = session.getAttribute(UID_ATTRIBUTE);
if (uidObject != null && uidObject instanceof String) {
uid = (String)uidO
if (AccessTokenStorage.getInstance().containsTokenFor(uid)) {
// user is authenticated, OK
// no access token ready, need to authenticate
String uri = httpRequest.getScheme()
+ httpRequest.getServerName()
+ (&http&.equals(httpRequest.getScheme())
&& httpRequest.getServerPort() == 80
|| &https&.equals(httpRequest.getScheme())
&& httpRequest.getServerPort() == 443 ? &&
: &:& + httpRequest.getServerPort())
+ httpRequest.getRequestURI()
+ (httpRequest.getQueryString() != null ? &?&
+ httpRequest.getQueryString() : &&);
OAuthClientRequest authRequest = OAuthClientRequest
.authorizationLocation(
AuthenticationServlet.AUTHORIZATION_LOCATION)
.setResponseType(ResponseType.CODE.toString())
.setClientId(AuthenticationServlet.CLIENT_ID)
.setState(uri)
.setRedirectURI(AuthenticationServlet.REDIRECT_URI)
.buildQueryMessage();
// send the client to the authentication process
((HttpServletResponse) response).sendRedirect(authRequest
.getLocationUri());
} catch (OAuthSystemException e) {
throw new ServletException(e);
// pass the request along the filter chain
chain.doFilter(request, response);
Example 29
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter(&code&);
if (code == null) {
// WE GOT AN ERROR!
String error = request.getParameter(&error&);
String errorDescription = request.getParameter(&error_description&);
if (error != null) {
if (error.equals(&access_denied&) ||
error.equals(&unauthorized_client&)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, errorDescription);
} else if (error.equals(&invalid_request&) ||
error.equals(&unsupported_response_type&) ||
error.equals(&server_error&)) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorDescription);
} else if (error.equals(&temporiraly_unavailable&)) {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, errorDescription);
// No error indicated.
// Either this request is not a redirect from Taltioni, or there is an error in configuration.
response.sendError(HttpServletResponse.SC_FORBIDDEN);
// we got the auth code from the auth server, let's exchange it to
// the access token
OAuthClientRequest tokenR
TokenRequestB
builder = OAuthClientRequest
.tokenLocation(TOKEN_LOCATION)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setCode(code)
.setRedirectURI(REDIRECT_URI)
.setClientId(CLIENT_ID);
tokenRequest = builder.buildBodyMessage();
} catch (OAuthSystemException e) {
e.printStackTrace();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
String header = buildBasicAuth(CLIENT_ID,
TaltioniDataAccess.getInstance().getProperty(&TALTIONI_APPLICATION_ID&));
tokenRequest.addHeader(HeaderType.AUTHORIZATION, header);
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse oAuthR
oAuthResponse = oAuthClient.accessToken(tokenRequest);
} catch (OAuthSystemException e) {
e.printStackTrace();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (OAuthProblemException e) {
e.printStackTrace();
response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getDescription());
String key = AccessTokenStorage.getInstance().storeToken(oAuthResponse.getAccessToken());
HttpSession session = request.getSession(true);
session.setAttribute(&uid&, key);
String state = request.getParameter(&state&);
if (state != null) {
String redirect = URLDecoder.decode(state, &UTF-8&);
response.sendRedirect(redirect);

我要回帖

更多关于 java httpclient post 的文章

 

随机推荐