Search in sources :

Example 36 with TokenResponse

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

the class MAuthorizationAccount method refresh.

/**
 * Refresh access token ( if has expire )
 * @throws GeneralSecurityException
 * @throws IOException
 */
public synchronized void refresh() throws GeneralSecurityException, IOException {
    Timestamp ts = getAccessTokenTimestamp();
    long seconds = getExpireInSeconds().longValue();
    long expire = ts.getTime() + (seconds * 1000);
    if (System.currentTimeMillis() >= expire) {
        ts = new Timestamp(System.currentTimeMillis());
        MAuthorizationCredential credential = new MAuthorizationCredential(getCtx(), getAD_AuthorizationCredential_ID(), get_TrxName());
        MAuthorizationProvider provider = new MAuthorizationProvider(getCtx(), credential.getAD_AuthorizationProvider_ID(), get_TrxName());
        GenericUrl url = new GenericUrl(provider.getTokenEndpoint());
        RefreshTokenRequest request = new RefreshTokenRequest(new NetHttpTransport(), GsonFactory.getDefaultInstance(), url, getRefreshToken());
        String clientId = credential.getAuthorizationClientId();
        String clientSecret = credential.getAuthorizationClientSecret();
        request.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
        TokenResponse response = request.execute();
        if (response.getRefreshToken() != null) {
            // OAuth2 Spec -> The authorization server MAY issue a new refresh token, in which case
            // the client MUST discard the old refresh token and replace it with the
            // new refresh token
            setRefreshToken(response.getRefreshToken());
        }
        setAccessToken(response.getAccessToken());
        setAccessTokenTimestamp(ts);
        setExpireInSeconds(new BigDecimal(response.getExpiresInSeconds()));
        saveEx();
    }
}
Also used : RefreshTokenRequest(com.google.api.client.auth.oauth2.RefreshTokenRequest) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) GenericUrl(com.google.api.client.http.GenericUrl) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal)

Example 37 with TokenResponse

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

the class MAuthorizationCredential method processToken.

/**
 * Create or Update an Account based on the token received
 * @param ctx
 * @param code
 * @param paramScope
 * @param pilog       MPInstanceLog to set the log message and record_ID, it is not saved, the caller must save it
 * @return String message indicating success
 */
public String processToken(Properties ctx, String code, String paramScope, MPInstanceLog pilog) {
    String msg = null;
    try {
        String clientId = getAuthorizationClientId();
        String clientSecret = getAuthorizationClientSecret();
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        MAuthorizationProvider ap = new MAuthorizationProvider(ctx, getAD_AuthorizationProvider_ID(), get_TrxName());
        AuthorizationCodeTokenRequest request = new AuthorizationCodeTokenRequest(new NetHttpTransport(), GsonFactory.getDefaultInstance(), new GenericUrl(ap.getTokenEndpoint()), code);
        request.setRedirectUri(getAuthorizationRedirectURL());
        request.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret));
        TokenResponse tokenResponse = request.execute();
        Object id_token = tokenResponse.get("id_token");
        String email = null;
        if (id_token != null && id_token instanceof String) {
            IdToken idtoken = IdToken.parse(tokenResponse.getFactory(), (String) tokenResponse.get("id_token"));
            email = (String) idtoken.getPayload().get("email");
        }
        if (email == null) {
            msg = Msg.parseTranslation(ctx, "@Error@ @OAuthProcessToken_CouldNotGetEMail@");
            return msg;
        }
        boolean newAccount = false;
        MAuthorizationAccount account = null;
        Query query = new Query(ctx, MAuthorizationAccount.Table_Name, "AD_Client_ID=? AND AD_User_ID=? AND EMail=? AND AD_AuthorizationCredential_ID=?", get_TrxName());
        query.setParameters(Env.getAD_Client_ID(ctx), Env.getAD_User_ID(ctx), email, getAD_AuthorizationCredential_ID());
        account = query.setOnlyActiveRecords(true).first();
        if (account == null) {
            account = new MAuthorizationAccount(ctx, 0, get_TrxName());
            account.setEMail(email);
            account.setAD_AuthorizationCredential_ID(getAD_AuthorizationCredential_ID());
            account.setAD_User_ID(Env.getAD_User_ID(ctx));
            newAccount = true;
        }
        account.setAD_AuthorizationScopes(paramScope);
        account.setAccessToken(tokenResponse.getAccessToken());
        account.setAccessTokenTimestamp(ts);
        account.setExpireInSeconds(BigDecimal.valueOf(tokenResponse.getExpiresInSeconds()));
        account.setIsAuthorized(true);
        account.setIsActive(true);
        if (tokenResponse.getRefreshToken() == null && account.getRefreshToken() == null) {
            String refreshToken = account.findRefreshToken();
            if (refreshToken != null) {
                account.setRefreshToken(refreshToken);
            }
        }
        if (tokenResponse.getRefreshToken() == null && account.getRefreshToken() == null) {
            // revoke access and ask for retry
            MAuthorizationProvider provider = new MAuthorizationProvider(ctx, getAD_AuthorizationProvider_ID(), get_TrxName());
            String revokeEndPoint = provider.getRevokeEndpoint();
            if (revokeEndPoint != null) {
                HttpRequestFactory factory = new NetHttpTransport().createRequestFactory();
                GenericUrl url = new GenericUrl(revokeEndPoint + "?token=" + account.getAccessToken());
                HttpRequest revokeRequest = factory.buildGetRequest(url);
                revokeRequest.execute();
            }
            msg = Msg.parseTranslation(ctx, "@Error@ @OAuthProcessToken_NoRefreshToken@");
            return msg;
        }
        if (tokenResponse.getRefreshToken() != null) {
            account.setRefreshToken(tokenResponse.getRefreshToken());
        }
        account.saveEx();
        if (pilog != null) {
            String logmsg = Msg.parseTranslation(ctx, (newAccount ? "@Created@" : "@Updated@") + " @AD_AuthorizationAccount_ID@ for ") + account.getEMail();
            pilog.setP_Msg(logmsg);
            pilog.setRecord_ID(account.getAD_AuthorizationAccount_ID());
        }
        account.syncOthers();
        if (newAccount)
            msg = Msg.getMsg(ctx, "Authorization_Access_OK", new Object[] { account.getEMail(), paramScope });
        else
            msg = Msg.getMsg(ctx, "Authorization_Access_Previous", new Object[] { account.getEMail(), paramScope });
    } catch (Exception ex) {
        ex.printStackTrace();
        msg = Msg.getMsg(ctx, "Error") + ex.getLocalizedMessage();
        return msg;
    }
    return msg;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) IdToken(com.google.api.client.auth.openidconnect.IdToken) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) GenericUrl(com.google.api.client.http.GenericUrl) Timestamp(java.sql.Timestamp) AdempiereException(org.adempiere.exceptions.AdempiereException) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeTokenRequest(com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport)

Example 38 with TokenResponse

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

the class ServiceAccountTokenGcpCredentialFactory method doCreate.

@Override
protected ProjectCredentials doCreate() {
    try {
        this.httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(apiToken);
        return new ProjectCredentials(new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(httpTransport).setJsonFactory(GSON_FACTORY).setTokenServerUrl(new GenericUrl("https://www.googleapis.com/auth/cloud-platform")).build().setFromTokenResponse(tokenResponse), projectId, "");
    } catch (IOException | GeneralSecurityException e) {
        throw new IllegalArgumentException(String.format("Cannot use credentials from Token : %s", apiToken), e);
    }
}
Also used : TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) GeneralSecurityException(java.security.GeneralSecurityException) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException)

Example 39 with TokenResponse

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

the class OAuth2CallbackServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    StringBuffer buf = req.getRequestURL();
    if (req.getQueryString() != null) {
        buf.append('?').append(req.getQueryString());
    }
    AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(buf.toString().replaceFirst("^http://", "https://"));
    if (responseUrl.getError() != null) {
        logAndPrintError(req, resp, HttpStatus.SC_INTERNAL_SERVER_ERROR, responseUrl.getError());
        return;
    }
    String code = responseUrl.getCode();
    String state = responseUrl.getState();
    if (code == null || state == null) {
        logAndPrintError(req, resp, HttpStatus.SC_BAD_REQUEST, "Missing authorization code");
        return;
    }
    String nextUrl = "/";
    try {
        AuthState authState = JsonUtils.fromJson(StringHelper.decrypt(state), AuthState.class);
        if (authState.getNextUrl() != null) {
            nextUrl = authState.getNextUrl();
        }
        String sessionId = authState.getSessionId();
        if (!sessionId.equals(req.getSession().getId())) {
            // Invalid session ID
            log.warning(String.format("Different session ID: expected %s, got %s", sessionId, req.getSession().getId()));
            logAndPrintError(req, resp, HttpStatus.SC_BAD_REQUEST, "Invalid authorization code");
            return;
        }
    } catch (JsonParseException | InvalidParametersException e) {
        log.warning("Failed to parse state object", e);
        logAndPrintError(req, resp, HttpStatus.SC_BAD_REQUEST, "Bad state object");
        return;
    }
    String redirectUri = getRedirectUri(req);
    TokenResponse token = getAuthorizationFlow().newTokenRequest(code).setRedirectUri(redirectUri).execute();
    String googleId = null;
    try {
        String userInfoResponse = HttpRequest.executeGetRequest(new URI("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + token.getAccessToken()));
        Map<String, Object> parsedResponse = JsonUtils.fromJson(userInfoResponse, new TypeToken<Map<String, Object>>() {
        }.getType());
        if (parsedResponse.containsKey("email")) {
            String email = String.valueOf(parsedResponse.get("email"));
            googleId = email.replaceFirst("@gmail\\.com$", "");
        }
    } catch (URISyntaxException | IOException | JsonSyntaxException e) {
        // if any of the operation fail, googleId is kept at null
        log.warning("Failed to get Google ID", e);
    }
    Cookie cookie;
    if (googleId == null) {
        // invalid google ID
        req.getSession().invalidate();
        cookie = getLoginInvalidationCookie();
    } else {
        UserInfoCookie uic = new UserInfoCookie(googleId);
        cookie = getLoginCookie(uic);
    }
    log.info("Going to redirect to: " + nextUrl);
    log.request(req, HttpStatus.SC_MOVED_TEMPORARILY, "Login successful");
    resp.addCookie(cookie);
    resp.sendRedirect(nextUrl);
}
Also used : UserInfoCookie(teammates.common.datatransfer.UserInfoCookie) Cookie(javax.servlet.http.Cookie) InvalidParametersException(teammates.common.exception.InvalidParametersException) UserInfoCookie(teammates.common.datatransfer.UserInfoCookie) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) URI(java.net.URI) JsonSyntaxException(com.google.gson.JsonSyntaxException) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) TypeToken(com.google.gson.reflect.TypeToken) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl)

Example 40 with TokenResponse

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

the class CloudShellCredential method executeRefreshToken.

@Override
protected TokenResponse executeRefreshToken() throws IOException {
    Socket socket = new Socket("localhost", this.getAuthPort());
    socket.setSoTimeout(READ_TIMEOUT_MS);
    TokenResponse token = new TokenResponse();
    try {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println(GET_AUTH_TOKEN_REQUEST);
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        // Ignore the size line
        input.readLine();
        Collection<Object> messageArray = jsonFactory.createJsonParser(input).parseArray(LinkedList.class, Object.class);
        String accessToken = ((List<Object>) messageArray).get(ACCESS_TOKEN_INDEX).toString();
        token.setAccessToken(accessToken);
    } finally {
        socket.close();
    }
    return token;
}
Also used : TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) Socket(java.net.Socket) PrintWriter(java.io.PrintWriter)

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