use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dockstore by dockstore.
the class TokenResource method addGoogleToken.
/**
* Adds a Google token to the existing user if user is authenticated already.
* Otherwise, below table indicates what happens when the "Login with Google" button in the UI2 is clicked
* <table border="1">
* <tr>
* <td></td> <td><b> Have GitHub account no Google Token (no GitHub account)</b></td> <td><b>Have GitHub account with Google token</b></td>
* </tr>
* <tr>
* <td> <b>Have Google Account no Google token</b></td> <td>Login with Google account (1)</td> <td>Login with GitHub account(2)</td>
* </tr>
* <tr>
* <td> <b>Have Google Account with Google token</b></td> <td>Login with Google account (3)</td> <td> Login with Google account (4)</td>
* </tr>
* <tr>
* <td> <b>No Google Account</b></td> <td> Create Google account (5)</td> <td>Login with GitHub account (6)</td>
* </tr>
* </table>
*
* @param authUser The optional Dockstore-authenticated user
* @param satellizerJson Satellizer object returned by satellizer
* @return The user's Dockstore token
*/
@POST
@Timed
@UnitOfWork
@Path("/google")
@JsonView(TokenViews.Auth.class)
@Operation(operationId = "addGoogleToken", description = "Allow satellizer to post a new Google token to Dockstore.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
@ApiOperation(value = "Allow satellizer to post a new Google token to Dockstore.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = "A post method is required by satellizer to send the Google token", response = Token.class)
public Token addGoogleToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth Optional<User> authUser, @ApiParam("code") String satellizerJson) {
Gson gson = new Gson();
JsonElement element = gson.fromJson(satellizerJson, JsonElement.class);
JsonObject satellizerObject = element.getAsJsonObject();
final String code = getCodeFromSatellizerObject(satellizerObject);
final String redirectUri = getRedirectURIFromSatellizerObject(satellizerObject);
final boolean registerUser = getRegisterFromSatellizerObject(satellizerObject);
TokenResponse tokenResponse = GoogleHelper.getTokenResponse(googleClientID, googleClientSecret, code, redirectUri);
String accessToken = tokenResponse.getAccessToken();
String refreshToken = tokenResponse.getRefreshToken();
LOG.info("Token expires in " + tokenResponse.getExpiresInSeconds().toString() + " seconds.");
Userinfoplus userinfo = getUserInfo(accessToken);
long userID;
Token dockstoreToken = null;
Token googleToken = null;
String googleLoginName = userinfo.getEmail();
String googleOnlineProfileId = userinfo.getId();
// We will not be able to get everyone's Google profile ID so check if we can match a user by id first, and then by username if that fails.
User user = userDAO.findByGoogleOnlineProfileId(googleOnlineProfileId);
if (user == null) {
user = userDAO.findByGoogleEmail(googleLoginName);
}
if (registerUser && authUser.isEmpty()) {
if (user == null) {
String googleLogin = userinfo.getEmail();
String username = googleLogin;
int count = 1;
while (userDAO.findByUsername(username) != null || DeletedUserHelper.nonReusableUsernameFound(username, deletedUsernameDAO)) {
username = googleLogin + count++;
}
user = new User();
user.setUsername(username);
userID = userDAO.create(user);
} else {
throw new CustomWebApplicationException("User already exists, cannot register new user", HttpStatus.SC_FORBIDDEN);
}
} else {
if (authUser.isPresent()) {
userID = authUser.get().getId();
} else if (user != null) {
if (user.isCurator() || user.getIsAdmin()) {
throw new CustomWebApplicationException(ADMINS_AND_CURATORS_MAY_NOT_LOGIN_WITH_GOOGLE, HttpStatus.SC_UNAUTHORIZED);
}
userID = user.getId();
} else {
throw new CustomWebApplicationException("Login failed, you may need to register an account", HttpStatus.SC_UNAUTHORIZED);
}
List<Token> tokens = tokenDAO.findDockstoreByUserId(userID);
if (!tokens.isEmpty()) {
dockstoreToken = tokens.get(0);
}
tokens = tokenDAO.findGoogleByUserId(userID);
if (!tokens.isEmpty()) {
googleToken = tokens.get(0);
}
}
user = userDAO.findById(userID);
acceptTOSAndPrivacyPolicy(user);
if (dockstoreToken == null) {
LOG.info("Could not find user's dockstore token. Making new one...");
dockstoreToken = createDockstoreToken(userID, user.getUsername());
}
if (googleToken == null) {
LOG.info("Could not find user's Google token. Making new one...");
// CREATE GOOGLE TOKEN
googleToken = new Token(accessToken, refreshToken, userID, googleLoginName, TokenType.GOOGLE_COM, googleOnlineProfileId);
checkIfAccountHasBeenLinked(googleToken, TokenType.GOOGLE_COM);
tokenDAO.create(googleToken);
// Update user profile too
user = userDAO.findById(userID);
GoogleHelper.updateUserFromGoogleUserinfoplus(userinfo, user);
LOG.info("Google token created for {}", googleLoginName);
} else {
// Update tokens if exists
googleToken.setContent(accessToken);
googleToken.setRefreshToken(refreshToken);
googleToken.setUsername(googleLoginName);
googleToken.setOnlineProfileId(googleOnlineProfileId);
tokenDAO.update(googleToken);
}
return dockstoreToken;
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dockstore by dockstore.
the class TokenResource method addZenodoToken.
@GET
@Timed
@UnitOfWork
@Path("/zenodo.org")
@JsonView(TokenViews.User.class)
@Operation(operationId = "addZenodoToken", description = "Add a new zenodo.org token, used by accounts page.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
@ApiOperation(value = "Add a new zenodo.org token, used by accounts page.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = "This is used as part of the OAuth 2 web flow. " + "Once a user has approved permissions for Collaboratory" + "Their browser will load the redirect URI which should resolve here", response = Token.class)
public Token addZenodoToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @QueryParam("code") String code) {
if (code.isEmpty()) {
throw new CustomWebApplicationException("Please provide a Zenodo access code", HttpStatus.SC_BAD_REQUEST);
}
final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(zenodoUrl + "/oauth/token"), new ClientParametersAuthentication(zenodoClientID, zenodoClientSecret), zenodoClientID, zenodoAuthUrl).build();
LOG.info("About to request zenodo access token");
String accessToken;
String refreshToken;
try {
TokenResponse tokenResponse = flow.newTokenRequest(code).setRequestInitializer(request -> request.getHeaders().setAccept("application/json")).setGrantType("authorization_code").setRedirectUri(zenodoRedirectUri).execute();
accessToken = tokenResponse.getAccessToken();
refreshToken = tokenResponse.getRefreshToken();
} catch (IOException e) {
LOG.error("Retrieving zenodo access token was unsuccessful.", e);
throw new CustomWebApplicationException("Could not retrieve zenodo token based on code " + e.getMessage(), HttpStatus.SC_BAD_REQUEST);
}
if (user != null) {
Token token = new Token();
token.setTokenSource(TokenType.ZENODO_ORG);
token.setContent(accessToken);
token.setRefreshToken(refreshToken);
token.setUserId(user.getId());
// Zenodo does not return a user name in the token response
// so set the token user name to the Dockstore user name
// otherwise we will get a DB error when trying to
// link another user's Zenodo credentials
token.setUsername(user.getUsername());
checkIfAccountHasBeenLinked(token, TokenType.ZENODO_ORG);
long create = tokenDAO.create(token);
LOG.info("Zenodo token created for {}", user.getUsername());
return tokenDAO.findById(create);
} else {
LOG.info("Could not find user");
throw new CustomWebApplicationException("User not found", HttpStatus.SC_NOT_FOUND);
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dockstore by dockstore.
the class GoogleHelper method getValidAccessToken.
/**
* Gets a non-expired access token.
*
* Google access tokens expire. This method returns
* an active access token, either returning the one
* that is in <code>token</code>, or generating a new
* one with the refresh token, if necessary.
*
* This method does NOT update the <code>token</code> with the new token,
* if there is one. It is the responsibility of the caller to update
* the token if they want the new token to be persisted.
*
* @param token
* @return
*/
public static Optional<String> getValidAccessToken(Token token) {
final String googleToken = token.getToken();
return tokenInfoFromToken(googleToken).map(tokenInfo -> {
// The user has a non-expired Google token -- also make sure that the audience is valid.
return isValidAudience(tokenInfo) ? Optional.of(googleToken) : Optional.<String>empty();
}).orElseGet(() -> {
// The token expired; try to refresh it
if (token.getRefreshToken() != null) {
TokenResponse tokenResponse = new TokenResponse();
try {
tokenResponse.setRefreshToken(token.getRefreshToken());
GoogleCredential credential = new GoogleCredential.Builder().setTransport(TokenResource.HTTP_TRANSPORT).setJsonFactory(TokenResource.JSON_FACTORY).setClientSecrets(config.getGoogleClientID(), config.getGoogleClientSecret()).build().setFromTokenResponse(tokenResponse);
credential.refreshToken();
return Optional.ofNullable(credential.getAccessToken());
} catch (IOException e) {
LOG.error("Error refreshing token", e);
}
}
return Optional.empty();
});
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project cyberduck by iterate-ch.
the class OAuth2AuthorizationService method authorize.
public OAuthTokens authorize(final Host bookmark, final LoginCallback prompt, final CancelCallback cancel, final FlowType type) throws BackgroundException {
final Credentials credentials = bookmark.getCredentials();
final OAuthTokens saved = credentials.getOauth();
if (saved.validate()) {
// Found existing tokens
if (saved.isExpired()) {
log.warn(String.format("Refresh expired access tokens %s", saved));
// Refresh expired access key
try {
credentials.setSaved(true);
return this.refresh(saved);
} catch (LoginFailureException | InteroperabilityException e) {
log.warn(String.format("Failure refreshing tokens from %s for %s", saved, bookmark));
// Continue with new OAuth 2 flow
}
} else {
if (log.isDebugEnabled()) {
log.debug(String.format("Returned saved OAuth tokens %s for %s", saved, bookmark));
}
return saved;
}
}
if (log.isDebugEnabled()) {
log.debug(String.format("Start new OAuth flow for %s with missing access token", bookmark));
}
final TokenResponse response;
switch(type) {
case AuthorizationCode:
response = this.authorizeWithCode(bookmark, prompt, cancel, credentials);
break;
case PasswordGrant:
response = this.authorizeWithPassword(credentials);
break;
default:
throw new LoginCanceledException();
}
// Save access key and refresh key
final OAuthTokens tokens = new OAuthTokens(response.getAccessToken(), response.getRefreshToken(), null == response.getExpiresInSeconds() ? System.currentTimeMillis() : System.currentTimeMillis() + response.getExpiresInSeconds() * 1000);
credentials.setOauth(tokens);
return tokens;
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project styx by spotify.
the class GoogleIdTokenAuth method getUserToken.
private String getUserToken(UserCredentials credentials) throws IOException {
log.debug("Fetching user id token");
final TokenRequest request = new RefreshTokenRequest(this.httpTransport, JSON_FACTORY, new GenericUrl(credentials.toBuilder().getTokenServerUri()), credentials.getRefreshToken()).setClientAuthentication(new ClientParametersAuthentication(credentials.getClientId(), credentials.getClientSecret())).setRequestInitializer(new HttpCredentialsAdapter(credentials));
final TokenResponse response = request.execute();
return (String) response.get("id_token");
}
Aggregations