use of org.apache.amber.oauth2.client.OAuthClient in project irida by phac-nml.
the class OltuAuthorizationControllerTest method setUp.
@Before
public void setUp() {
apiService = mock(RemoteAPIService.class);
tokenService = mock(RemoteAPITokenService.class);
oauthClient = mock(OAuthClient.class);
controller = new OltuAuthorizationController(tokenService, apiService);
controller.setServerBase(serverBase);
}
use of org.apache.amber.oauth2.client.OAuthClient in project structr by structr.
the class StructrOAuthClient method getUserResponse.
protected OAuthResourceResponse getUserResponse(final HttpServletRequest request) {
if (userResponse != null) {
return userResponse;
}
try {
String accessToken = getAccessToken(request);
if (accessToken != null) {
final String accessTokenParameterKey = this.getAccessTokenParameterKey();
OAuthClientRequest clientReq = new OAuthBearerClientRequest(getUserResourceUri()) {
@Override
public OAuthBearerClientRequest setAccessToken(String accessToken) {
this.parameters.put(accessTokenParameterKey, accessToken);
return this;
}
}.setAccessToken(accessToken).buildQueryMessage();
// needed for LinkedIn
clientReq.setHeader("x-li-format", "json");
logger.info("User info request: {}", clientReq.getLocationUri());
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
userResponse = oAuthClient.resource(clientReq, "GET", OAuthResourceResponse.class);
logger.info("User info response: {}", userResponse);
return userResponse;
}
} catch (Throwable t) {
logger.error("Could not get user response", t);
}
return null;
}
use of org.apache.amber.oauth2.client.OAuthClient in project identity-test-integration by wso2-incubator.
the class LoginProxy method handleCallback.
/**
* this is the method, which gets fired when the identity server returns back the authorization code, after
* authenticating the user. in addition to the authorization code, the response from the identity server must also
* include the state parameter, which contains the value we set when we initiate the authorization grant.
*
* @param code the authorization code generated by the identity server. the proxy application will exchange this
* token to get an access token from the identity server.
* @param state this is the same value we set as state, when we initiate the authorization grant request to the
* identity server.
* @return
*/
@Path("callback")
@GET
public Response handleCallback(@QueryParam("code") String code, @QueryParam("state") String state) {
if (code == null || code.isEmpty()) {
return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "The value of the code cannot be null.");
}
if (state == null || state.isEmpty()) {
return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "The value of the state cannot be null.");
}
HttpServletResponse resp = context.getHttpServletResponse();
HttpServletRequest req = context.getHttpServletRequest();
Cookie[] cookies = req.getCookies();
String spaName = null;
// try to load the cookie corresponding to the value of the state.
if (cookies != null && cookies.length > 0) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(state)) {
spaName = cookies[i].getValue();
break;
}
}
}
if (spaName == null) {
return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.BAD_REQUEST, ProxyFaultCodes.ERROR_002, ProxyFaultCodes.Name.INVALID_INPUTS, "No valid cookie found.");
}
// loads the client key corresponding to the SPA. you do not need to have SPA specific consumer keys, rather
// can use one client key for all the SPAs. you get the consumer key from the identity server, at the time you
// register the service provider, and configure it in oauth_proxy.properties file.
String consumerKey = ProxyUtils.getConsumerKey(spaName);
// loads the client secret corresponding to the SPA. you do not need to have SPA specific client secret, rather
// can use one client secret for all the SPAs. you get the client secret from the identity server, at the time
// you register the service provider, and configure it in oauth_proxy.properties file.
String consumerSecret = ProxyUtils.getConsumerSecret(spaName);
// this is the OAuth 2.0 token end-point of the identity server.
String tokenEndpoint = ProxyUtils.getTokenEp();
// load the callback URL of the proxy. there is only one callback URL. even when you create multiple service
// providers in identity server to get multiple client key/client secret pairs, the callback URL would be the
// same.
String callbackUrl = ProxyUtils.getCallbackUrl();
OAuthClientRequest accessRequest = null;
try {
// create an OAuth 2.0 token request.
accessRequest = OAuthClientRequest.tokenLocation(tokenEndpoint).setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(consumerKey).setClientSecret(consumerSecret).setRedirectURI(callbackUrl).setCode(code).buildBodyMessage();
} catch (OAuthSystemException e) {
log.error(e);
return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
}
// create an OAuth 2.0 client that uses custom HTTP client under the hood
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthClientResponse oAuthResponse = null;
try {
// talk to the OAuth token end-point of identity server to get the OAuth access token, refresh token and id
// token.
oAuthResponse = oAuthClient.accessToken(accessRequest);
} catch (OAuthSystemException e) {
log.error(e);
return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
} catch (OAuthProblemException e) {
log.error(e);
return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
}
// read the access token from the OAuth token end-point response.
String accessToken = oAuthResponse.getParam(ProxyUtils.ACCESS_TOKEN);
// read the refresh token from the OAuth token end-point response.
String refreshToken = oAuthResponse.getParam(ProxyUtils.REFRESH_TOKEN);
// read the expiration from the OAuth token endpoint response.
long expiration = Long.parseLong(oAuthResponse.getParam(ProxyUtils.EXPIRATION));
// read the id token from the OAuth token end-point response.
String idToken = oAuthResponse.getParam(ProxyUtils.ID_TOKEN);
if (idToken != null) {
// extract out the content of the JWT, which comes in the id token.
String[] idTkElements = idToken.split(Pattern.quote("."));
idToken = idTkElements[1];
}
// create a JSON object aggregating OAuth access token, refresh token and id token
JSONObject json = new JSONObject();
try {
json.put(ProxyUtils.ID_TOKEN, idToken);
json.put(ProxyUtils.ACCESS_TOKEN, accessToken);
json.put(ProxyUtils.REFRESH_TOKEN, refreshToken);
json.put(ProxyUtils.SPA_NAME, spaName);
json.put(ProxyUtils.EXPIRATION, new Long(expiration));
} catch (JSONException e) {
return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
}
try {
// encrypt the JSON message.
String encryptedCookieValue = ProxyUtils.encrypt(json.toString());
// create a cookie under the proxy domain with the encrypted message. cookie name is set to the value of the
// code, initially passed by the SPA.
Cookie cookie = new Cookie(state, encryptedCookieValue);
// the cookie is only accessible by the HTTPS transport.
cookie.setSecure(true);
// add cookie to the response.
resp.addCookie(cookie);
// get the SPA callback URL. each SPA has its own callback URL, which is defined in the
// oauth_proxy.properties file
resp.sendRedirect(ProxyUtils.getSpaCallbackUrl(spaName));
return null;
} catch (Exception e) {
return ProxyUtils.handleResponse(ProxyUtils.OperationStatus.INTERNAL_SERVER_ERROR, ProxyFaultCodes.ERROR_003, ProxyFaultCodes.Name.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
use of org.apache.amber.oauth2.client.OAuthClient in project incubator-gobblin by apache.
the class SalesforceRestWriter method onConnect.
/**
* Retrieve access token, if needed, retrieve instance url, and set server host URL
* {@inheritDoc}
* @see org.apache.gobblin.writer.http.HttpWriter#onConnect(org.apache.http.HttpHost)
*/
@Override
public void onConnect(URI serverHost) throws IOException {
if (!StringUtils.isEmpty(accessToken)) {
// No need to be called if accessToken is active.
return;
}
try {
getLog().info("Getting Oauth2 access token.");
OAuthClientRequest request = OAuthClientRequest.tokenLocation(serverHost.toString()).setGrantType(GrantType.PASSWORD).setClientId(clientId).setClientSecret(clientSecret).setUsername(userId).setPassword(password + securityToken).buildQueryMessage();
OAuthClient client = new OAuthClient(new URLConnectionClient());
OAuthJSONAccessTokenResponse response = client.accessToken(request, OAuth.HttpMethod.POST);
accessToken = response.getAccessToken();
setCurServerHost(new URI(response.getParam("instance_url")));
} catch (OAuthProblemException e) {
throw new NonTransientException("Error while authenticating with Oauth2", e);
} catch (OAuthSystemException e) {
throw new RuntimeException("Failed getting access token", e);
} catch (URISyntaxException e) {
throw new RuntimeException("Failed due to invalid instance url", e);
}
}
use of org.apache.amber.oauth2.client.OAuthClient in project components by Talend.
the class Oauth2ImplicitClient method getToken.
public <T extends OAuthAccessTokenResponse> T getToken(Class<T> tokenResponseClass) {
try {
TokenRequestBuilder builder = //
OAuthClientRequest.tokenLocation(//
tokenLocation.toString()).setGrantType(//
grantType).setClientId(//
clientID).setClientSecret(clientSecret);
if (GrantType.AUTHORIZATION_CODE == grantType) {
builder = //
builder.setRedirectURI(callbackURL.toString()).setCode(getAuthorizationCode());
} else if (GrantType.REFRESH_TOKEN == grantType) {
builder = builder.setRefreshToken(refreshToken);
}
OAuthClientRequest request = builder.buildQueryMessage();
OAuthClient oauthClient = new OAuthClient(new URLConnectionClient());
return oauthClient.accessToken(request, tokenResponseClass);
} catch (OAuthSystemException e) {
throw new RuntimeException(e);
} catch (OAuthProblemException e) {
throw new RuntimeException(e);
}
}
Aggregations