use of org.apache.amber.oauth2.common.exception.OAuthProblemException 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.common.exception.OAuthProblemException 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.common.exception.OAuthProblemException in project tesla by linking12.
the class OauthTokenController method authorize.
@RequestMapping("token")
public void authorize(HttpServletRequest request, HttpServletResponse response) throws OAuthSystemException {
try {
OAuthTokenxRequest tokenRequest = new OAuthTokenxRequest(request);
OAuthTokenHandleDispatcher tokenHandleDispatcher = new OAuthTokenHandleDispatcher(tokenRequest, response);
tokenHandleDispatcher.dispatch();
} catch (OAuthProblemException e) {
LOG.debug(e.getMessage(), e);
OAuthResponse oAuthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).location(e.getRedirectUri()).error(e).buildJSONMessage();
WebUtils.writeOAuthJsonResponse(response, oAuthResponse);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthProblemException 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);
}
}
use of org.apache.amber.oauth2.common.exception.OAuthProblemException in project entando-core by entando.
the class ApiRestServer method extractOAuthParameters.
protected void extractOAuthParameters(HttpServletRequest request, String permission) throws ApiException {
try {
_logger.info("Permission required: {}", permission);
OAuthAccessResourceRequest requestMessage = new OAuthAccessResourceRequest(request, ParameterStyle.HEADER);
// Get the access token
String accessToken = requestMessage.getAccessToken();
IApiOAuth2TokenManager tokenManager = (IApiOAuth2TokenManager) ApsWebApplicationUtils.getBean(IApiOAuth2TokenManager.BEAN_NAME, request);
final OAuth2Token token = tokenManager.getApiOAuth2Token(accessToken);
if (token != null) {
// Validate the access token
if (!token.getAccessToken().equals(accessToken)) {
throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Token does not match", Response.Status.UNAUTHORIZED);
} else // check if access token is expired
if (token.getExpiresIn().getTime() < System.currentTimeMillis()) {
throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Token expired", Response.Status.UNAUTHORIZED);
}
String username = token.getClientId();
IUserManager userManager = (IUserManager) ApsWebApplicationUtils.getBean(SystemConstants.USER_MANAGER, request);
UserDetails user = userManager.getUser(username);
if (user != null) {
_logger.info("User {} requesting resource that requires {} permission ", username, permission);
request.getSession().setAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER, user);
if (permission != null) {
IAuthorizationManager authManager = (IAuthorizationManager) ApsWebApplicationUtils.getBean(SystemConstants.AUTHORIZATION_SERVICE, request);
user.addAuthorizations(authManager.getUserAuthorizations(username));
if (!authManager.isAuthOnPermission(user, permission)) {
List<Role> roles = authManager.getUserRoles(user);
for (Role role : roles) {
_logger.info("User {} requesting resource has {} permission ", username, role.getPermissions().toArray()[0]);
}
_logger.info("User {} requesting resource has {} permission ", username, "none");
throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Authentication Required", Response.Status.UNAUTHORIZED);
}
}
}
} else {
if (accessToken != null) {
throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Token not found, request new one", Response.Status.UNAUTHORIZED);
}
throw new ApiException(IApiErrorCodes.API_AUTHENTICATION_REQUIRED, "Authentication Required", Response.Status.UNAUTHORIZED);
}
} catch (OAuthSystemException | ApsSystemException | OAuthProblemException ex) {
_logger.error("System exception {}", ex);
throw new ApiException(IApiErrorCodes.SERVER_ERROR, ex.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
}
}
Aggregations