use of org.apache.oltu.oauth2.common.OAuth in project SeriesGuide by UweTrottmann.
the class AnalyticsTree method log.
@Override
protected void log(int priority, String tag, String message, Throwable t) {
if (priority == Log.ERROR) {
// remove any stack trace attached by Timber
if (message != null) {
int newLine = message.indexOf('\n');
if (newLine > 0) {
message = message.substring(0, newLine);
}
}
// special treatment for some exceptions
if (t instanceof TvdbException) {
TvdbException e = (TvdbException) t;
Utils.trackCustomEvent(context, CATEGORY_THETVDB_ERROR, tag + ": " + message, e.getMessage());
return;
} else if (t instanceof OAuthProblemException) {
// log trakt OAuth failures
OAuthProblemException e = (OAuthProblemException) t;
StringBuilder exceptionMessage = new StringBuilder();
if (!TextUtils.isEmpty(e.getError())) {
exceptionMessage.append(e.getError());
}
if (!TextUtils.isEmpty(e.getDescription())) {
exceptionMessage.append(", ").append(e.getDescription());
}
if (!TextUtils.isEmpty(e.getUri())) {
exceptionMessage.append(", ").append(e.getUri());
}
Utils.trackCustomEvent(context, "OAuth Error", tag + ": " + message, exceptionMessage.toString());
return;
} else if (t instanceof OAuthSystemException) {
// log trakt OAuth failures
OAuthSystemException e = (OAuthSystemException) t;
Utils.trackCustomEvent(context, "OAuth Error", tag + ": " + message, e.getMessage());
return;
}
}
// drop empty messages
if (message == null) {
return;
}
// drop debug and verbose logs
if (priority == Log.DEBUG || priority == Log.VERBOSE) {
return;
}
// transform priority into string
String level = null;
switch(priority) {
case Log.INFO:
level = "INFO";
break;
case Log.WARN:
level = "WARN";
break;
case Log.ERROR:
level = "ERROR";
break;
}
// finally log to crashlytics
Crashlytics.log(level + "/" + tag + ": " + message);
// track some non-fatal exceptions with crashlytics
if (priority == Log.ERROR) {
if (t instanceof SQLiteException) {
Crashlytics.logException(t);
}
}
}
use of org.apache.oltu.oauth2.common.OAuth in project entando-core by entando.
the class EntandoOauth2Interceptor method extractOAuthParameters.
protected void extractOAuthParameters(HttpServletRequest request, String permission) {
try {
logger.info("Permission required: {}", permission);
OAuthAccessResourceRequest requestMessage = new OAuthAccessResourceRequest(request, ParameterStyle.HEADER);
String accessToken = requestMessage.getAccessToken();
if (StringUtils.isBlank(accessToken)) {
throw new EntandoTokenException("no access token found", request, null);
}
final OAuth2Token token = oAuth2TokenManager.getApiOAuth2Token(accessToken);
this.validateToken(request, accessToken, token);
String username = token.getClientId();
this.checkAuthorization(username, permission, request);
} catch (OAuthSystemException | ApsSystemException | OAuthProblemException ex) {
logger.error("System exception {}", ex.getMessage());
throw new EntandoTokenException("error parsing OAuth parameters", request, "guest");
}
}
use of org.apache.oltu.oauth2.common.OAuth 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.OAuth 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();
}
}
use of org.apache.oltu.oauth2.common.OAuth in project irida by phac-nml.
the class RemoteAPITokenServiceImpl method createTokenFromAuthCode.
/**
* Get a new token from the given auth code
* @param authcode the auth code to create a token for
* @param remoteAPI the remote api to get a token for
* @param tokenRedirect a redirect url to get the token from
* @return a new token
* @throws OAuthSystemException If building the token request fails
* @throws OAuthProblemException If the token request fails
*/
@Transactional
public RemoteAPIToken createTokenFromAuthCode(String authcode, RemoteAPI remoteAPI, String tokenRedirect) throws OAuthSystemException, OAuthProblemException {
String serviceURI = remoteAPI.getServiceURI();
// Build the token location for this service
URI serviceTokenLocation = UriBuilder.fromUri(serviceURI).path("oauth").path("token").build();
logger.debug("Remote token location: " + serviceTokenLocation);
// Create the token request form the given auth code
OAuthClientRequest tokenRequest = OAuthClientRequest.tokenLocation(serviceTokenLocation.toString()).setClientId(remoteAPI.getClientId()).setClientSecret(remoteAPI.getClientSecret()).setRedirectURI(tokenRedirect).setCode(authcode).setGrantType(GrantType.AUTHORIZATION_CODE).buildBodyMessage();
// execute the request
OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequest);
// read the response for the access token
String accessToken = accessTokenResponse.getAccessToken();
// Handle Refresh Tokens
String refreshToken = accessTokenResponse.getRefreshToken();
// check the token expiry
Long expiresIn = accessTokenResponse.getExpiresIn();
Long currentTime = System.currentTimeMillis();
Date expiry = new Date(currentTime + (expiresIn * ONE_SECOND_IN_MS));
logger.debug("Token expiry: " + expiry);
// create the OAuth2 token and store it
RemoteAPIToken token = new RemoteAPIToken(accessToken, refreshToken, remoteAPI, expiry);
return create(token);
}
Aggregations