9

某人可以指定(通過一些示例代碼)如何驗證谷歌雲端點中的谷歌雲端代碼?最近提出的問題根本沒有說明(How to integrate firebase authentication with google app engine endpoints將谷歌應用引擎雲端點集成的Firebase身份驗證

端點中的Google身份驗證是通過將用戶參數添加到端點來自動完成的。

@ApiMethod(name = "endpoint.addUser", httpMethod = HttpMethod.POST) 
     public ResultObject addUser(HttpServletRequest request, User pUser) throws OAuthRequestException { 
    String token = request.getHeader("Authorization"); 
    String graphUrl = "https://graph.facebook.com/v2.6/me?fields=id,name,email&access_token=" + token; 

    URL u = new URL(g); 
    URLConnection c = u.openConnection(); 
    BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); 
    String inputLine; 
    StringBuffer b = new StringBuffer(); 
    while ((inputLine = in.readLine()) != null){ 
      b.append(inputLine + "\n");    
    } 
    in.close(); 
    graph = b.toString(); 
    JSONObject json = new JSONObject(graph); 

    facebookId = json.getString("id"); 
    email = json.getString("email"); 
    //... 
} 

是對火力的標識作爲Facebook的令牌一樣簡單的驗證: Facebook的令牌可以在像這樣Facebook的圖形API的雲終端進行驗證?是否可以從Firebase令牌中檢索電子郵件?

+0

我無法準確回答Firebase,但我會說這不是整合驗證的正確方法。您應該改爲實施com.google.api.server.spi.config.Authenticator。然後在你的註釋中指定'Authenticator'。我相信Firebase身份驗證令牌是JWT,因此他們不需要發送驗證它們的請求。 – saiyr

+0

是的,這是corect。在最後的實現中,你會使用Authenticator。我只想包含演示代碼。 – SmilingM

+0

至於firebase,我想驗證令牌的原因是,我已經有一個正在運行的應用程序引擎端點。現在我想在客戶端使用Firebase身份驗證,並針對雲端點進行身份驗證。我現在不想遷移到Firebase實時數據庫。 – SmilingM

回答

2

就我所瞭解的文檔而言,您似乎需要將用戶令牌添加到您的請求中,例如作爲標題。然後,您需要根據Firebase admin sdk驗證此令牌,並以此方式獲取用戶ID。

@ApiMethod(name = "someApiCall", httpMethod = ApiMethod.HttpMethod.POST) 
public YourResponse someApiCall(YourRequestObject body, HttpServletRequest httpRequest) { 
    String userToken = httpRequest.getHeader("USER_TOKEN_HEADER"); 

    Task<FirebaseToken> authTask = FirebaseAuth.getInstance().verifyIdToken(userToken) 
     .addOnSuccessListener(new OnSuccessListener<FirebaseToken>() { 
      @Override 
      public void onSuccess(FirebaseToken firebaseToken) { 
      } 
     }); 

    try { 
     Tasks.await(authTask); 
    } catch (ExecutionException e) { 
    } catch (InterruptedException e) { 
    } 

    FirebaseToken result = authTask.getResult(); 
    String userId = result.getUid(); 

    return new YourResponse(); 
} 

我根據我的代碼上:

https://firebase.google.com/docs/auth/admin/verify-id-tokens

How do I secure my Google Cloud Endpoints APIs with Firebase token verification?

1

您可以使用CustomAuthenticator

public class CustomAuthenticator implements Authenticator { 
    private static final Logger LOG = Logger.getLogger(CustomAuthenticator.class.getName()); 
    private static final String COOKIE_FIREBASE_TOKEN = "firebase_token"; 

    static { 
     LOG.info("CustomAuthenticator: initializing"); 
     InputStream serviceAccountResourceStream = CustomAuthenticator.class.getResourceAsStream("/serviceAccountKey.json"); 
     FirebaseOptions options = new FirebaseOptions.Builder() 
       .setServiceAccount(serviceAccountResourceStream) 
       .build(); 

     FirebaseApp.initializeApp(options); 
     LOG.info("CustomAuthenticator: initialized"); 
    } 

    @Override 
    public User authenticate(HttpServletRequest httpServletRequest) { 
     User user = null; 
     if (httpServletRequest.getCookies() != null) { 
      for (Cookie cookie : httpServletRequest.getCookies()) { 
       if (cookie.getName().equals(COOKIE_FIREBASE_TOKEN)) { 
        FirebaseToken firebaseToken = FirebaseAuth.getInstance().verifyIdToken(cookie.getValue()).getResult(); 
        user = new User(firebaseToken.getUid(), firebaseToken.getEmail()); 
       } 
      } 
     } 
     return user; 
    } 
} 

在你的API實現,不要忘了啓用您的自定義驗證器:

@Api(name = "exampleWithAuth", 
     version = "v1", 
     ... 
     auth = @ApiAuth(allowCookieAuth = AnnotationBoolean.TRUE), // This is needed to process your cookie for the token 
     authenticators = {CustomAuthenticator.class} // Declare your custom authenticator 
) 
public class ExampleWithAuthEndpoint { 

    @ApiMethod(httpMethod = "GET", path = "example") 
    public Example getExample(User user /* Add User to enable API authentication */) { 
     if (user != null) { 
      // Do something 
     } 
     return null; 
    } 
} 

現在,當您調用API時,只需將Cookie firebase_token添加到您的請求。

我希望這會有所幫助。

+0

嘿尼科,這樣做可以使我們的API緩慢,因爲我們正在另一個額外的電話? – Ajeet