How do I restrict Google App Engine Endpoints API access to only my Android applications?

后端 未结 5 762
温柔的废话
温柔的废话 2020-12-02 23:53

I am an Android developer building my first Google App Engine (java) back-end for my apps. I don\'t want anybody else to access this API other than my app. (I plan to use Ap

5条回答
  •  再見小時候
    2020-12-03 00:16

    Facing the same problem than you ! Authenticate Android End point without Google User Account is just impossible !

    So here is my way to resolv this problem, without any user interaction (Maybe not the right but that works, and you've got strong authentication (SHA1 + Google Account)):

    HERE IS MY ANDROID CODE

    Get and Build Valid Credential

      //Get all accounts from my Android Phone
             String validGoogleAccount = null;
             Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
             Account[] accounts = AccountManager.get(context).getAccounts();
             for (Account account : accounts) {
                 if (emailPattern.matcher(account.name).matches()) {
                     //Just store mail if countain gmail.com
                     if (account.name.toString().contains("gmail.com")&&account.type.toString().contains("com.google")){
                         validGoogleAccount=account.name.toString();
                     }
    
                 }
             }
    
            //Build Credential with valid google account
            GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(this,"server:client_id:301991144702-5qkqclsogd0b4fnkhrja7hppshrvp4kh.apps.googleusercontent.com");
            credential.setSelectedAccountName(validGoogleAccount);
    

    Use this credential for secure calls

    Campagneendpoint.Builder endpointBuilder = new Campagneendpoint.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), credential);
    

    HERE IS MY API BACKEND CODE: API Annotation

    @Api(
            scopes=CONSTANTES.EMAIL_SCOPE,
            clientIds = {CONSTANTES.ANDROID_CLIENT_ID, 
                         CONSTANTES.WEB_CLIENT_ID,
                         com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID},
            audiences = {CONSTANTES.ANDROID_AUDIENCE},      
            name = "campagneendpoint",
            version = "v1"
         )
    

    Method code:

    public Collection getCampagnes(@Named("NumPortable")String NumPortable, User user) throws  UnauthorizedException {
            if (user == null) throw new UnauthorizedException("User is Not Valid");
    
          return CampagneCRUD.getInstance().findCampagne(NumPortable);
         }
    

    For the moment, it only works on Android (I don't know how we gonna do on IOS..)..

    Hope It will help you !

提交回复
热议问题