use of org.apache.oltu.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.oltu.oauth2.common.exception.OAuthProblemException in project dq-easy-cloud by dq-open-cloud.
the class EcAuthorizeController method token.
@RequestMapping("/accessToken")
public HttpEntity token(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
// http://localhost:8100/authorize/accessToken?code=4d9e143db54db03d215161f207346cb6&grant_type=authorization_code&redirect_uri=https://www.baidu.com&client_secret=1&client_id=2
try {
// 构建OAuth请求
OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
boolean checkClient = false;
// 检查提交的客户端id是否正确
if (checkClient) {
OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_CLIENT).setErrorDescription("异常").buildJSONMessage();
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
// 检查客户端安全KEY是否正确
// checkClient = !oAuthService.checkClientSecret(oauthRequest.getClientSecret())
String clientSecret = oauthRequest.getClientSecret();
if ("".equals(clientSecret)) {
OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT).setErrorDescription("secret有误").buildJSONMessage();
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
// 检查验证类型,此处只检查AUTHORIZATION_CODE类型,其他的还有PASSWORD或REFRESH_TOKEN
if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
// if (!oAuthService.checkAuthCode(authCode)) {
if (!codeCache.containsKey(authCode)) {
OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(OAuthError.TokenResponse.INVALID_GRANT).setErrorDescription("错误的授权码").buildJSONMessage();
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
}
// 生成Access Token
OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
final String accessToken = oauthIssuerImpl.accessToken();
final String refreshToken = oauthIssuerImpl.refreshToken();
// oAuthService.addAccessToken(accessToken, oAuthService.getUsernameByAuthCode(authCode));
tokenCache.put(accessToken, codeCache.get(authCode));
// 生成OAuth响应
OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(accessToken).setRefreshToken(refreshToken).setExpiresIn(String.valueOf(7200)).setTokenType(TokenType.BEARER.toString()).buildJSONMessage();
// 根据OAuthResponse生成ResponseEntity
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
} catch (OAuthProblemException e) {
logger.error(e.getMessage(), e);
// 构建错误响应
OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e).buildJSONMessage();
return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
}
}
use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project BIMserver by opensourceBIM.
the class OAuthAccessTokenServlet method service.
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OAuthTokenRequest oauthRequest = null;
OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
if (!request.getContentType().equals("application/x-www-form-urlencoded")) {
response.setStatus(405);
PrintWriter pw = response.getWriter();
pw.print("ContentType must be application/x-www-form-urlencoded");
pw.flush();
pw.close();
return;
}
try {
oauthRequest = new OAuthTokenRequest(request);
OAuthAuthorizationCode code = null;
try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.READ_ONLY)) {
String codeAsString = oauthRequest.getCode();
code = session.querySingle(StorePackage.eINSTANCE.getOAuthAuthorizationCode_Code(), codeAsString);
validateClient(oauthRequest);
String resourceUrl = "";
Authorization auth = code.getAuthorization();
org.bimserver.webservices.authorization.Authorization authorization = null;
if (auth instanceof SingleProjectAuthorization) {
SingleProjectAuthorization singleProjectAuthorization = (SingleProjectAuthorization) auth;
authorization = new org.bimserver.webservices.authorization.SingleProjectAuthorization(getBimServer(), code.getUser().getOid(), singleProjectAuthorization.getProject().getOid());
} else if (auth instanceof RunServiceAuthorization) {
RunServiceAuthorization runServiceAuthorization = (RunServiceAuthorization) auth;
authorization = new org.bimserver.webservices.authorization.RunServiceAuthorization(getBimServer(), code.getUser().getOid(), runServiceAuthorization.getService().getOid());
resourceUrl = getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress() + "/services/" + runServiceAuthorization.getService().getOid();
} else {
throw new Exception("Unknown auth");
}
String accessToken = authorization.asHexToken(getBimServer().getEncryptionKey());
String refreshToken = oauthIssuerImpl.refreshToken();
OAuthTokenResponseBuilder builder = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK).setAccessToken(accessToken).setExpiresIn("3600").setRefreshToken(refreshToken);
builder.setParam("resource_url", resourceUrl);
if (auth instanceof SingleProjectAuthorization) {
builder.setParam("poid", "" + ((SingleProjectAuthorization) code.getAuthorization()).getProject().getOid());
} else if (auth instanceof RunServiceAuthorization) {
builder.setParam("soid", "" + ((RunServiceAuthorization) code.getAuthorization()).getService().getOid());
}
OAuthResponse r = builder.buildJSONMessage();
response.setStatus(r.getResponseStatus());
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
pw.print(r.getBody());
pw.flush();
pw.close();
} catch (BimserverDatabaseException e) {
LOGGER.error("", e);
}
} catch (OAuthProblemException ex) {
LOGGER.error("", ex);
try {
OAuthResponse r = OAuthResponse.errorResponse(401).error(ex).buildJSONMessage();
response.setStatus(r.getResponseStatus());
PrintWriter pw = response.getWriter();
pw.print(r.getBody());
pw.flush();
pw.close();
} catch (OAuthSystemException e) {
LOGGER.error("", ex);
}
} catch (Exception e) {
LOGGER.error("", e);
}
}
use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project BIMserver by opensourceBIM.
the class OAuthRegistrationServlet method service.
@Override
public void service(HttpServletRequest request, HttpServletResponse httpResponse) throws ServletException, IOException {
OAuthServerRegistrationRequest oauthRequest = null;
try {
oauthRequest = new OAuthServerRegistrationRequest(new JSONHttpServletRequestWrapper(request));
oauthRequest.discover();
oauthRequest.getClientUrl();
oauthRequest.getClientDescription();
oauthRequest.getRedirectURI();
try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.POSSIBLY_WRITE)) {
OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_RedirectUrl(), oauthRequest.getRedirectURI());
GregorianCalendar now = new GregorianCalendar();
if (oAuthServer == null) {
oAuthServer = session.create(OAuthServer.class);
oAuthServer.setClientName(oauthRequest.getClientName());
oAuthServer.setClientUrl(oauthRequest.getClientUrl());
oAuthServer.setClientDescription(oauthRequest.getClientDescription());
if (oauthRequest.getClientIcon() != null) {
try {
byte[] icon = NetUtils.getContentAsBytes(new URL(oauthRequest.getClientIcon()), 5000);
oAuthServer.setClientIcon(icon);
} catch (Exception e) {
//
}
}
oAuthServer.setRedirectUrl(oauthRequest.getRedirectURI());
// DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
GregorianCalendar expires = new GregorianCalendar();
expires.add(Calendar.YEAR, 1);
String secret = new MD5Generator().generateValue();
oAuthServer.setIssuedAt(now.getTime());
oAuthServer.setExpiresAt(expires.getTime());
oAuthServer.setClientSecret(secret);
oAuthServer.setClientId(oauthRequest.getClientName().replace(" ", "").toLowerCase());
oAuthServer.setIncoming(true);
session.commit();
}
OAuthResponse response = OAuthServerRegistrationResponse.status(HttpServletResponse.SC_OK).setClientId(oAuthServer.getClientId()).setClientSecret(oAuthServer.getClientSecret()).setIssuedAt("" + oAuthServer.getIssuedAt().getTime()).setExpiresIn(oAuthServer.getExpiresAt().getTime() - now.getTimeInMillis()).setParam("message", "OK").buildJSONMessage();
httpResponse.setStatus(response.getResponseStatus());
httpResponse.setContentType(response.getHeaders().get("Content-Type"));
httpResponse.getWriter().write(response.getBody());
} catch (BimserverDatabaseException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
} catch (OAuthProblemException e) {
OAuthResponse response;
try {
response = OAuthServerRegistrationResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e).buildJSONMessage();
httpResponse.setStatus(response.getResponseStatus());
httpResponse.getWriter().write(response.getBody());
} catch (OAuthSystemException e1) {
e1.printStackTrace();
}
} catch (OAuthSystemException e) {
e.printStackTrace();
}
}
use of org.apache.oltu.oauth2.common.exception.OAuthProblemException in project BIMserver by opensourceBIM.
the class OAuthAuthorizationServlet method service.
@Override
public void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
OAuthAuthzRequest oauthRequest = null;
String authType = request.getParameter("auth_type");
if (request.getParameter("token") == null) {
String location = "/apps/bimviews/?page=OAuth&auth_type=" + authType + "&client_id=" + request.getParameter("client_id") + "&response_type=" + request.getParameter("response_type") + "&redirect_uri=" + request.getParameter("redirect_uri");
if (request.getParameter("state") != null) {
String state = request.getParameter("state");
LOGGER.info("Incoming state: " + state);
String encodedState = UrlEscapers.urlFragmentEscaper().escape(state);
LOGGER.info("Encoded state: " + encodedState);
location += "&state=" + encodedState;
}
LOGGER.info("Redirecting to " + location);
httpServletResponse.sendRedirect(location);
return;
}
OAuthAuthorizationCode oauthCode = null;
String token = request.getParameter("token");
try (DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.READ_ONLY)) {
OAuthServer oAuthServer = session.querySingle(StorePackage.eINSTANCE.getOAuthServer_ClientId(), request.getParameter("client_id"));
org.bimserver.webservices.authorization.Authorization realAuth = org.bimserver.webservices.authorization.Authorization.fromToken(getBimServer().getEncryptionKey(), token);
long uoid = realAuth.getUoid();
User user = session.get(uoid, OldQuery.getDefault());
for (OAuthAuthorizationCode oAuthAuthorizationCode : user.getOAuthIssuedAuthorizationCodes()) {
if (oAuthAuthorizationCode.getOauthServer() == oAuthServer) {
if (oAuthAuthorizationCode.getAuthorization() != null) {
oauthCode = oAuthAuthorizationCode;
}
}
}
try {
if (oauthCode == null) {
throw new ServletException("No auth found for token " + token);
}
oauthRequest = new OAuthAuthzRequest(request);
String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
if (responseType.equals(ResponseType.CODE.toString())) {
builder.setCode(oauthCode.getCode());
// } else if (responseType.equals(ResponseType.TOKEN))) {
// builder.setAccessToken(oauthCode.get)
}
// if (responseType.equals(ResponseType.TOKEN.toString())) {
// builder.setAccessToken(oauthIssuerImpl.accessToken());
// // builder.setTokenType(OAuth.DEFAULT_TOKEN_TYPE.toString());
// builder.setExpiresIn(3600l);
// }
String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
if (redirectURI != null && !redirectURI.equals("")) {
if (redirectURI.equals("SHOW_CODE")) {
httpServletResponse.getWriter().write("Service token (copy&paste this into your application): <br/><br/><input type=\"text\" style=\"width: 1000px\" value=\"" + oauthCode.getCode() + "\"/><br/><br/>");
RunServiceAuthorization auth = (RunServiceAuthorization) oauthCode.getAuthorization();
String siteAddress = getBimServer().getServerSettingsCache().getServerSettings().getSiteAddress();
httpServletResponse.getWriter().write("Service address: <br/><br/><input type=\"text\" style=\"width: 1000px\" value=\"" + siteAddress + "/services/" + auth.getService().getOid() + "\"/><br/><br/>");
} else {
URI uri = makeUrl(redirectURI, oauthCode, builder);
LOGGER.info("Redirecting to " + uri);
httpServletResponse.sendRedirect(uri.toString());
}
} else {
URI uri = makeUrl("http://fakeaddress", oauthCode, builder);
httpServletResponse.getWriter().println("No redirectURI provided");
httpServletResponse.getWriter().println("Would have redirected to: " + uri);
}
} catch (OAuthProblemException e) {
final Response.ResponseBuilder responseBuilder = Response.status(HttpServletResponse.SC_FOUND);
String redirectUri = e.getRedirectUri();
if (OAuthUtils.isEmpty(redirectUri)) {
throw new WebApplicationException(responseBuilder.entity("OAuth callback url needs to be provided by client!!!").build());
}
try {
OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e).location(redirectUri).buildQueryMessage();
// final URI location = new URI(response.getLocationUri());
httpServletResponse.sendRedirect(response.getLocationUri());
} catch (OAuthSystemException e1) {
e1.printStackTrace();
}
}
} catch (OAuthSystemException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (BimserverLockConflictException e2) {
e2.printStackTrace();
} catch (BimserverDatabaseException e2) {
e2.printStackTrace();
} catch (AuthenticationException e2) {
e2.printStackTrace();
}
}
Aggregations