简体   繁体   English

将firebase auth与google app引擎云端点集成

[英]Integrate firebase auth with google app engine cloud endpoints

Can someone specify (with some sample code) how to verify the firebase token in an google cloud endpoint? 有人可以指定(使用一些示例代码)如何验证google云端点中的firebase令牌? The recently asked question does not clarifiy it at all ( How to integrate firebase authentication with google app engine endpoints ) 最近提出的问题根本没有澄清( 如何将firebase身份验证与Google应用引擎端点集成

Google Authentication in endpoint is done automatically by adding the User Parameter to an endpoint. 端点中的Google身份验证是通过将用户参数添加到端点来自动完成的。 Facebook Tokens can be verified in an cloud endpoint with the facebook graph api like this: 可以使用facebook图api在云端点验证Facebook令牌,如下所示:

    @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");
    //...
}

Is the verification of the firebase token as easy as the facebook token? firebase令牌的验证是否像facebook令牌一样简单? Is it possible to retrieve the email from an firebase token? 是否可以从firebase令牌中检索电子邮件?

As far as I understand the documentation it seems you need to add user token to your request, for example as a header. 据我所知,文档似乎需要将用户令牌添加到您的请求中,例如作为标题。 Then you need to verify this token against Firebase admin sdk, and this way you'd get user id. 然后,您需要针对Firebase管理员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();
}

I based my code on: 我的代码基于:

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

How do I secure my Google Cloud Endpoints APIs with Firebase token verification? 如何使用Firebase令牌验证保护Google Cloud Endpoints API?

You can use a CustomAuthenticator : 您可以使用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;
    }
}

In your API implementation, don't forget to enable your custom authenticator: 在您的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;
    }
}

Now when you call your API, just add the cookie firebase_token to your request. 现在,当您调用API时,只需将cookie firebase_token添加到您的请求中即可。

I hope this will help. 我希望这将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将firebase身份验证与Google App引擎端点集成 - How to integrate firebase authentication with google app engine endpoints 应用引擎端点使用Google Identity Toolkit进行身份验证 - App engine endpoints auth with Google Identity Toolkit Google App Engine Cloud Endpoints userId为null - Google App Engine Cloud Endpoints userId is null Android客户端-使用Google Cloud Endpoints的Google App引擎身份验证 - Android Client - Google App engine authentication using Google Cloud Endpoints 对Google App Engine和Google Cloud端点感到困惑 - Confused about Google App Engine and Google Cloud Endpoints 使用适用于Google App Engine的Cloud Endpoints对Android App进行本地测试 - Local testing for Android App using Cloud Endpoints for Google App Engine Google Cloud端点(应用程式引擎)+与Android的oauth2整合 - Google cloud endpoints (app engine) + oauth2 integration with android Google App Engine - 云端点 - 未设置应用程序名称 - Google App Engine - Cloud Endpoints - Application name is not set App Engine如何使用Google Cloud Endpoints执行缓存 - How app engine perform caching using google cloud endpoints Google App Engine云端点Pr @ blem Marker - &gt;在干净的Android项目上生成App Engine错误 - Google App Engine Cloud Endpoints Pr@blem Marker - > Generate App Engine Error on clean Android Project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM