How do I protect my API that was built using Google Cloud Endpoints?

前端 未结 3 594
迷失自我
迷失自我 2020-12-02 16:21

The API is a backend to a mobile app. I don\'t need user authentication. I simply need a way to secure access to this API. Currently, my backend is exposed.

The docu

3条回答
  •  爱一瞬间的悲伤
    2020-12-02 16:42

    Yes, you can do that: use authentication to secure your endpoints without doing user authentication.

    I have found that this way of doing it is not well documented, and I haven't actually done it myself, but I intend to so I paid attention when I saw it being discussed on some of the IO13 videos (I think that's where I saw it):

    Here's my understanding of what's involved:

    • Create a Google API project (though this doesn't really involve their API's, other than authentication itself).
    • Create OATH client ID's that are tied to your app via its package name and the SHA1 fingerprint of the certificate that you will sign the app with.

    You will add these client ID's to the list of acceptable ID's for your endpoints. You will add the User parameter to your endpoints, but it will be null since no user is specified.

    @ApiMethod(
       name = "sendInfo",
       clientIds = { Config.WEB_CLIENT_ID, Config.MY_APP_CLIENT_ID, Config.MY_DEBUG_CLIENT_ID },
       audiences = { Config.WEB_CLIENT_ID } 
       // Yes, you specify a 'web' ID even if this isn't a Web client.
    )
    public void sendInfo(User user, Info greeting) {
    

    There is some decent documentation about the above, here: https://developers.google.com/appengine/docs/java/endpoints/auth

    Your client app will specify these client ID's when formulating the endpoint service call. All the OATH details will get taken care of behind the scenes on your client device such that your client ID's are translated into authentication tokens.

    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    GoogleAccountCredential credential = GoogleAccountCredential.usingAudience( ctx, Config.WEB_CLIENT_ID );
    //credential.setSelectedAccountName( user );  // not specify a user
    Myendpoint.Builder builder = new Myendpoint.Builder( transport, jsonFactory, credential );  
    

    This client code is just my best guess - sorry. If anyone else has a reference for exactly what the client code should look like then I too would be interested.

提交回复
热议问题