Search in sources :

Example 46 with TokenResponse

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;
}
Also used : Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) User(io.dockstore.webservice.core.User) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) Token(io.dockstore.webservice.core.Token) BearerToken(com.google.api.client.auth.oauth2.BearerToken) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) JsonElement(com.google.gson.JsonElement) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) POST(javax.ws.rs.POST) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) JsonView(com.fasterxml.jackson.annotation.JsonView) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 47 with TokenResponse

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);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) JsonView(com.fasterxml.jackson.annotation.JsonView) Produces(javax.ws.rs.Produces) URL(java.net.URL) Date(java.util.Date) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) ApiParam(io.swagger.annotations.ApiParam) HttpStatus(org.apache.http.HttpStatus) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) GitHubBuilder(org.kohsuke.github.GitHubBuilder) SecureRandom(java.security.SecureRandom) SourceCodeRepoFactory(io.dockstore.webservice.helpers.SourceCodeRepoFactory) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) TokenScope(io.dockstore.webservice.core.TokenScope) Gson(com.google.gson.Gson) Map(java.util.Map) GenericUrl(com.google.api.client.http.GenericUrl) TokenType(io.dockstore.webservice.core.TokenType) OPENAPI_JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME) User(io.dockstore.webservice.core.User) GitHub(org.kohsuke.github.GitHub) DELETE(javax.ws.rs.DELETE) SecurityRequirement(io.swagger.v3.oas.annotations.security.SecurityRequirement) TokenViews(io.dockstore.webservice.core.TokenViews) GitHubHelper(io.dockstore.webservice.helpers.GitHubHelper) HttpTransport(com.google.api.client.http.HttpTransport) Instant(java.time.Instant) Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) GoogleHelper(io.dockstore.webservice.helpers.GoogleHelper) Parameter(io.swagger.v3.oas.annotations.Parameter) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Tag(io.swagger.v3.oas.annotations.tags.Tag) Optional(java.util.Optional) TOSVersion(io.dockstore.webservice.core.TOSVersion) PathParam(javax.ws.rs.PathParam) CachingAuthenticator(io.dropwizard.auth.CachingAuthenticator) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) HashMap(java.util.HashMap) Hashing(com.google.common.hash.Hashing) JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME) ApiResponses(io.swagger.annotations.ApiResponses) MessageFormat(java.text.MessageFormat) JsonElement(com.google.gson.JsonElement) JacksonFactory(com.google.api.client.json.jackson.JacksonFactory) Operation(io.swagger.v3.oas.annotations.Operation) HttpClient(org.apache.http.client.HttpClient) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) Api(io.swagger.annotations.Api) Token(io.dockstore.webservice.core.Token) UserDAO(io.dockstore.webservice.jdbi.UserDAO) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Charsets(com.google.common.base.Charsets) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) DeletedUserHelper(io.dockstore.webservice.helpers.DeletedUserHelper) MalformedURLException(java.net.MalformedURLException) BaseEncoding(com.google.common.io.BaseEncoding) BearerToken(com.google.api.client.auth.oauth2.BearerToken) DeletedUsernameDAO(io.dockstore.webservice.jdbi.DeletedUsernameDAO) IOException(java.io.IOException) PrivacyPolicyVersion(io.dockstore.webservice.core.PrivacyPolicyVersion) JsonFactory(com.google.api.client.json.JsonFactory) ApiResponse(io.swagger.annotations.ApiResponse) GitHubSourceCodeRepo(io.dockstore.webservice.helpers.GitHubSourceCodeRepo) TokenDAO(io.dockstore.webservice.jdbi.TokenDAO) Collections(java.util.Collections) Authorization(io.swagger.annotations.Authorization) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) Token(io.dockstore.webservice.core.Token) BearerToken(com.google.api.client.auth.oauth2.BearerToken) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) JsonView(com.fasterxml.jackson.annotation.JsonView) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 48 with TokenResponse

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();
    });
}
Also used : GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) Logger(org.slf4j.Logger) BearerToken(com.google.api.client.auth.oauth2.BearerToken) Tokeninfo(com.google.api.services.oauth2.model.Tokeninfo) LoggerFactory(org.slf4j.LoggerFactory) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) HttpStatus(org.apache.http.HttpStatus) IOException(java.io.IOException) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) MessageFormat(java.text.MessageFormat) TokenResource(io.dockstore.webservice.resources.TokenResource) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) Map(java.util.Map) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) GenericUrl(com.google.api.client.http.GenericUrl) Optional(java.util.Optional) TokenType(io.dockstore.webservice.core.TokenType) User(io.dockstore.webservice.core.User) Oauth2(com.google.api.services.oauth2.Oauth2) Token(io.dockstore.webservice.core.Token) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) IOException(java.io.IOException)

Example 49 with TokenResponse

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;
}
Also used : LoginFailureException(ch.cyberduck.core.exception.LoginFailureException) InteroperabilityException(ch.cyberduck.core.exception.InteroperabilityException) OAuthTokens(ch.cyberduck.core.OAuthTokens) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) LoginCanceledException(ch.cyberduck.core.exception.LoginCanceledException) Credentials(ch.cyberduck.core.Credentials)

Example 50 with TokenResponse

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");
}
Also used : RefreshTokenRequest(com.google.api.client.auth.oauth2.RefreshTokenRequest) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) RefreshTokenRequest(com.google.api.client.auth.oauth2.RefreshTokenRequest) TokenRequest(com.google.api.client.auth.oauth2.TokenRequest) GenericUrl(com.google.api.client.http.GenericUrl)

Aggregations

TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)48 IOException (java.io.IOException)23 GenericUrl (com.google.api.client.http.GenericUrl)22 Credential (com.google.api.client.auth.oauth2.Credential)20 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)16 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)15 Map (java.util.Map)13 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)12 TokenResponse (com.microsoft.identity.common.internal.providers.oauth2.TokenResponse)11 BearerToken (com.google.api.client.auth.oauth2.BearerToken)9 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)8 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 Test (org.junit.Test)7 URL (java.net.URL)6 HashMap (java.util.HashMap)6 List (java.util.List)6 Timed (com.codahale.metrics.annotation.Timed)5 AuthorizationCodeRequestUrl (com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl)5 Collections (java.util.Collections)5