Search in sources :

Example 41 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dishevelled by heuermh.

the class GoogleGenomicsFactory method createGenomics.

Genomics createGenomics(final GenomicsKey genomicsKey) throws IOException {
    final String rootUrl = genomicsKey.rootUrl();
    final String authorizationCode = genomicsKey.authorizationCode();
    final GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = genomicsKey.googleAuthorizationCodeFlow();
    if (logger.isInfoEnabled()) {
        logger.info("creating new google genomics api for root url {} authorization code {}", rootUrl, abbrev(authorizationCode));
    }
    TokenResponse tokenResponse = googleAuthorizationCodeFlow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
    if (logger.isInfoEnabled()) {
        logger.info("received token response {}", abbrev(tokenResponse.getAccessToken()));
    }
    final Credential credential = googleAuthorizationCodeFlow.createAndStoreCredential(tokenResponse, "user");
    if (logger.isInfoEnabled()) {
        logger.info("received credential {} expires in {} s", abbrev(credential.getAccessToken()), credential.getExpiresInSeconds());
    }
    Genomics genomics = new Genomics.Builder(httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME).setRootUrl(rootUrl).setServicePath("/").setHttpRequestInitializer(new HttpRequestInitializer() {

        @Override
        public void initialize(final HttpRequest httpRequest) throws IOException {
            credential.initialize(httpRequest);
            // 60 seconds
            httpRequest.setReadTimeout(60000);
        }
    }).build();
    if (logger.isInfoEnabled()) {
        logger.info("created new google genomics api for root URL {} authorization code {} application name {}", rootUrl, abbrev(authorizationCode), genomics.getApplicationName() == null ? "null" : genomics.getApplicationName());
    }
    return genomics;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) Genomics(com.google.api.services.genomics.Genomics) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 42 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project hub-alert by blackducksoftware.

the class AzureBoardsProperties method requestTokens.

public Optional<Credential> requestTokens(AuthorizationCodeFlow authorizationCodeFlow, String authorizationCode) throws IOException {
    AuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(authorizationCode);
    TokenResponse tokenResponse = tokenRequest.execute();
    Credential credential = authorizationCodeFlow.createAndStoreCredential(tokenResponse, oauthUserId);
    return Optional.ofNullable(credential);
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeTokenRequest(com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest)

Example 43 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project isaac-api by isaacphysics.

the class FacebookAuthenticator method exchangeCode.

@Override
public String exchangeCode(final String authorizationCode) throws CodeExchangeException {
    try {
        AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest(httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), authorizationCode);
        request.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
        request.setRedirectUri(callbackUri);
        TokenResponse response = request.execute();
        String accessToken;
        Long expires;
        if (response.get("error") != null) {
            throw new CodeExchangeException("Server responded with the following error" + response.get("error") + " given the request" + request.toString());
        }
        if (response.getAccessToken() != null && response.getExpiresInSeconds() != null) {
            accessToken = response.getAccessToken();
            expires = response.getExpiresInSeconds();
        } else {
            throw new IOException("access_token or expires_in values were not found");
        }
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setExpiresInSeconds(expires);
        // I don't really want to use the flow storage but it seems to be
        // easier to get credentials this way.
        Builder builder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(TOKEN_EXCHANGE_URL), new ClientParametersAuthentication(clientId, clientSecret), clientId, AUTH_URL);
        builder.setScopes(requestedScopes);
        AuthorizationCodeFlow flow = builder.setDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance()).build();
        Credential credential = flow.createAndStoreCredential(tokenResponse, authorizationCode);
        String internalReferenceToken = UUID.randomUUID().toString();
        credentialStore.put(internalReferenceToken, credential);
        flow.getCredentialDataStore().clear();
        return internalReferenceToken;
    } catch (IOException e) {
        String message = "An error occurred during code exchange";
        throw new CodeExchangeException(message, e);
    }
}
Also used : ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeTokenRequest(com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest) Builder(com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder) CodeExchangeException(uk.ac.cam.cl.dtg.segue.auth.exceptions.CodeExchangeException) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow)

Example 44 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project google-oauth-java-client by googleapis.

the class AuthorizationCodeInstalledApp method authorize.

/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param userId user ID or {@code null} if not using a persisted credential store
 * @return credential
 * @throws IOException
 */
public Credential authorize(String userId) throws IOException {
    try {
        Credential credential = flow.loadCredential(userId);
        if (credential != null && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() > 60)) {
            return credential;
        }
        // open in browser
        String redirectUri = receiver.getRedirectUri();
        AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri);
        onAuthorization(authorizationUrl);
        // receive authorization code and exchange it for an access token
        String code = receiver.waitForCode();
        TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
        // store credential and return it
        return flow.createAndStoreCredential(response, userId);
    } finally {
        receiver.stop();
    }
}
Also used : AuthorizationCodeRequestUrl(com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl) Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse)

Example 45 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dockstore by dockstore.

the class TokenResource method addOrcidToken.

@POST
@Timed
@UnitOfWork
@Path("/orcid.org")
@JsonView(TokenViews.User.class)
@ApiOperation(value = orcidSummary, authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = orcidDescription, response = Token.class)
@Operation(operationId = "addOrcidToken", summary = orcidSummary, description = orcidDescription, security = @SecurityRequirement(name = "bearer"))
public Token addOrcidToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth final User user, @QueryParam("code") final String code) {
    String accessToken;
    String refreshToken;
    String username;
    String orcid;
    String scope;
    long expirationTime;
    if (code == null || code.isEmpty()) {
        throw new CustomWebApplicationException("Please provide an access code", HttpStatus.SC_BAD_REQUEST);
    }
    final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(orcidUrl + "oauth/token"), new ClientParametersAuthentication(orcidClientID, orcidClientSecret), orcidClientID, orcidUrl + "/authorize").build();
    try {
        TokenResponse tokenResponse = flow.newTokenRequest(code).setScopes(Collections.singletonList(orcidScope)).setRequestInitializer(request -> request.getHeaders().setAccept(MediaType.APPLICATION_JSON)).execute();
        accessToken = tokenResponse.getAccessToken();
        refreshToken = tokenResponse.getRefreshToken();
        // ORCID API returns the username and orcid id along with the tokens
        // get them to store in the token and user tables
        username = tokenResponse.get("name").toString();
        orcid = tokenResponse.get("orcid").toString();
        scope = tokenResponse.getScope();
        Instant instant = Instant.now();
        instant.plusSeconds(tokenResponse.getExpiresInSeconds());
        expirationTime = instant.getEpochSecond();
    } catch (IOException e) {
        LOG.error("Retrieving accessToken was unsuccessful" + e.getMessage(), e);
        throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_BAD_REQUEST);
    }
    if (user != null) {
        // save the ORCID to the enduser table
        User byId = userDAO.findById(user.getId());
        byId.setOrcid(orcid);
        Token token = new Token();
        token.setTokenSource(TokenType.ORCID_ORG);
        token.setContent(accessToken);
        token.setRefreshToken(refreshToken);
        token.setUserId(user.getId());
        token.setUsername(username);
        TokenScope tokenScope = TokenScope.getEnumByString(scope);
        if (tokenScope == null) {
            LOG.error("Could not convert scope string to enum: " + scope);
            throw new CustomWebApplicationException("Could not save ORCID token, contact Dockstore team", HttpStatus.SC_INTERNAL_SERVER_ERROR);
        }
        token.setScope(tokenScope);
        token.setExpirationTime(expirationTime);
        checkIfAccountHasBeenLinked(token, TokenType.ORCID_ORG);
        long create = tokenDAO.create(token);
        LOG.info("ORCID token created for {}", user.getUsername());
        return tokenDAO.findById(create);
    } else {
        LOG.info("Could not find user");
        throw new CustomWebApplicationException("User not found", HttpStatus.SC_CONFLICT);
    }
}
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) User(io.dockstore.webservice.core.User) Instant(java.time.Instant) 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) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) TokenScope(io.dockstore.webservice.core.TokenScope) 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)

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