Search in sources :

Example 61 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project microsoft-authentication-library-common-for-android by AzureAD.

the class ConfidentialClientHelper method requestAccessTokenForAutomation.

/**
 * Yep.  Hardcoding this method to retrieve access token for MSIDLABS
 */
private String requestAccessTokenForAutomation() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException {
    String accessToken = null;
    final TokenRequest tokenRequest = this.createTokenRequest();
    tokenRequest.setGrantType(CLIENT_CREDENTIALS);
    final AccountsInOneOrganization aadAudience = new AccountsInOneOrganization(TENANT_ID);
    final AzureActiveDirectoryAuthority authority = new AzureActiveDirectoryAuthority(aadAudience);
    try {
        final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
        OAuth2Strategy<AccessToken, BaseAccount, AuthorizationRequest, AuthorizationRequest.Builder, AuthorizationStrategy, OAuth2Configuration, OAuth2StrategyParameters, AuthorizationResponse, RefreshToken, TokenRequest, TokenResponse, TokenResult, AuthorizationResult> strategy = authority.createOAuth2Strategy(strategyParameters);
        TokenResult tokenResult = strategy.requestToken(tokenRequest);
        if (tokenResult.getSuccess()) {
            accessToken = tokenResult.getTokenResponse().getAccessToken();
        } else {
            throw new RuntimeException(tokenResult.getErrorResponse().getErrorDescription());
        }
    } catch (final ClientException e) {
        e.printStackTrace();
    }
    return accessToken;
}
Also used : AuthorizationStrategy(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationStrategy) AuthorizationRequest(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationRequest) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) AuthorizationResponse(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResponse) RefreshToken(com.microsoft.identity.common.internal.providers.oauth2.RefreshToken) TokenResponse(com.microsoft.identity.common.internal.providers.oauth2.TokenResponse) AccessToken(com.microsoft.identity.common.internal.providers.oauth2.AccessToken) BaseAccount(com.microsoft.identity.common.BaseAccount) AccountsInOneOrganization(com.microsoft.identity.common.internal.authorities.AccountsInOneOrganization) TokenRequest(com.microsoft.identity.common.internal.providers.oauth2.TokenRequest) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) OAuth2Configuration(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Configuration) ClientException(com.microsoft.identity.common.exception.ClientException)

Example 62 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project bible-online by m0ver.

the class login method oAuth2callback.

public String oAuth2callback() throws ApplicationException {
    HttpServletRequest request = (HttpServletRequest) this.context.getAttribute(HTTP_REQUEST);
    HttpServletResponse response = (HttpServletResponse) this.context.getAttribute(HTTP_RESPONSE);
    Reforward reforward = new Reforward(request, response);
    TokenResponse oauth2_response;
    try {
        if (this.getVariable("google_client_secrets") == null) {
            clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(login.class.getResourceAsStream("/clients_secrets.json")));
            if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
                System.out.println("Enter Client ID and Secret from https://code.google.com/apis/console/ ");
            }
            this.setVariable(new ObjectVariable("google_client_secrets", clientSecrets), false);
        } else
            clientSecrets = (GoogleClientSecrets) this.getVariable("google_client_secrets").getValue();
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES).build();
        oauth2_response = flow.newTokenRequest(request.getParameter("code")).setRedirectUri(this.getLink("oauth2callback")).execute();
        System.out.println("Ok:" + oauth2_response.toString());
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        throw new ApplicationException(e1.getMessage(), e1);
    } catch (GeneralSecurityException e) {
        // TODO Auto-generated catch block
        throw new ApplicationException(e.getMessage(), e);
    }
    try {
        HttpClient httpClient = new DefaultHttpClient();
        String url = "https://www.google.com/m8/feeds/contacts/default/full";
        url = "https://www.googleapis.com/oauth2/v1/userinfo";
        HttpGet httpget = new HttpGet(url + "?access_token=" + oauth2_response.getAccessToken());
        httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");
        HttpResponse http_response = httpClient.execute(httpget);
        HeaderIterator iterator = http_response.headerIterator();
        while (iterator.hasNext()) {
            Header next = iterator.nextHeader();
            System.out.println(next.getName() + ":" + next.getValue());
        }
        com.google.api.client.http.HttpTransport h;
        InputStream instream = http_response.getEntity().getContent();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = instream.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        instream.close();
        out.close();
        Struct struct = new Builder();
        struct.parse(new String(out.toByteArray(), "utf-8"));
        this.usr = new User();
        this.usr.setEmail(struct.toData().getFieldInfo("email").stringValue());
        if (this.usr.findOneByKey("email", this.usr.getEmail()).size() == 0) {
            usr.setPassword("");
            usr.setUsername(usr.getEmail());
            usr.setLastloginIP(request.getRemoteAddr());
            usr.setLastloginTime(new Date());
            usr.setRegistrationTime(new Date());
            usr.append();
        }
        new passport(request, response, "waslogined").setLoginAsUser(this.usr.getId());
        reforward.setDefault(URLDecoder.decode(this.getVariable("from").getValue().toString(), "utf8"));
        reforward.forward();
        return new String(out.toByteArray(), "utf-8");
    } catch (ClientProtocolException e) {
        throw new ApplicationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new ApplicationException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new ApplicationException(e.getMessage(), e);
    }
}
Also used : User(custom.objects.User) HttpGet(org.apache.http.client.methods.HttpGet) Builder(org.tinystruct.data.component.Builder) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Struct(org.tinystruct.data.component.Struct) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ObjectVariable(org.tinystruct.system.template.variable.ObjectVariable) GoogleClientSecrets(com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets) GeneralSecurityException(java.security.GeneralSecurityException) GoogleAuthorizationCodeFlow(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpResponse(org.apache.http.HttpResponse) Date(java.util.Date) ApplicationException(org.tinystruct.ApplicationException) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) Header(org.apache.http.Header) Reforward(org.tinystruct.handler.Reforward) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HeaderIterator(org.apache.http.HeaderIterator) ParseException(org.apache.http.ParseException)

Example 63 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project blackduck-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)

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