Android AWS Cognito与S3

Android AWS Cognito与S3,android,amazon-web-services,amazon-s3,amazon-cognito,Android,Amazon Web Services,Amazon S3,Amazon Cognito,我正在开发Android应用程序,用户可以从AmazonS3上传和下载文件。我已经为我的应用程序开发了身份验证。目前,每当用户想要上传几个文件时,对于每个文件,用户都可以通过ping我的后端来获取IdentityID和Token 我有几个问题 我如何知道令牌是否过期 AWS API是否保存令牌和标识本身?如果是,如何检索它们 在我的项目中使用IdentityId和令牌的最佳方式是什么?为每个文件调用后端以获取令牌?或者当用户想要上传一堆(选定的)文件时调用一次?或者保存令牌并在令牌未过期时重用它

我正在开发Android应用程序,用户可以从
AmazonS3
上传和下载文件。我已经为我的应用程序开发了身份验证。目前,每当用户想要上传几个文件时,对于每个文件,用户都可以通过ping我的后端来获取
IdentityID
Token

我有几个问题

  • 我如何知道令牌是否过期

  • AWS API
    是否保存令牌和标识本身?如果是,如何检索它们

  • 在我的项目中使用
    IdentityId
    和令牌的最佳方式是什么?为每个文件调用后端以获取令牌?或者当用户想要上传一堆(选定的)文件时调用一次?或者保存令牌并在令牌未过期时重用它

  • 代码:

    Auth.java:

    public class Auth extends AWSAbstractCognitoDeveloperIdentityProvider {
    
    
    
    private Context ctx;
    public Auth(String accountId, String identityPoolId, Regions region,Context ctx) {
        super(accountId, identityPoolId, region);
          this.ctx=ctx;
    
    }
    
    @Override
    public String getProviderName() {
       return "cognito-identity.amazonaws.com";
    
    }
    
    @Override
    public String refresh() {
        setToken(null);
    
        if (getProviderName() != null &&
                !this.loginsMap.isEmpty() &&
                this.loginsMap.containsKey(getProviderName())&& internetchek.connectGoogle()) {
    
            Log.d("Refreshing..","Loading..");
            Idtoken();
    
            update(identityId, token);
    
            return token;
    
    
    
        } else {
    
            this.getIdentityId();
            return null;
        }
    
    }
    @Override
    public String getToken() {
        return token;
    }
    
    public void Idtoken(){
    
    
    
        String serverurl = constants.IP_ADDRESS_CREDENTIALS;
        try {
            save s = new save(this.ctx, constants.USER_DETAILS);
            String phonenumber = s.read(constants.PHONE_NUMBER);
    
            if (phonenumber != null) {
    
    
                URL url = new URL(serverurl);
                HttpURLConnection http = (HttpURLConnection) url.openConnection();
                http.setRequestMethod("POST");
                http.setDoInput(true);
                http.setDoOutput(true);
    
                OutputStream OS = http.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
                String data = URLEncoder.encode("number", "UTF-8") + "=" + URLEncoder.encode(phonenumber, "UTF-8");
                bufferedWriter.write(data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS = http.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
                String line = "";
                String response="";
    
                while ((line= bufferedReader.readLine()) != null) {
                    response = response+line;
    
                }
                bufferedReader.close();
                IS.close();
                http.disconnect();
    
                response = response.replaceAll("\\s+", "");
    
                Log.d("RESPONCE", response);
    
                String[] splitter = response.split("==");
                if (splitter[0] != null) {
    
                    if (splitter[1] != null) {
    
                        identityId = splitter[0];
                        token = splitter[1];
    
                    }
    
                }
            }
                Log.d("IDENTITYID",identityId);
                Log.d("TOKEN",token);
    
            }catch(MalformedURLException e){
                e.printStackTrace();
            }catch(UnknownHostException e)
            {
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }
    
    }}
    
    上传文件

    private class Uploadfile extends AsyncTask<Void,Void,Void>{
    
        Context ctx;
        String remotepath;
        File file;
        ProgressBar progressBar;
    
        private Uploadfile(Context ctx,File file,String remotepath,ProgressBar progressBar){
            this.ctx =ctx;
            this.file=file;
            this.remotepath=remotepath;
            this.progressBar =progressBar;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    
        @Override
        protected Void doInBackground(Void... params) {
            if(!internetchek.isNetworkAvailable(this.ctx)||!internetchek.connectGoogle()){
                Log.d("NETWORK","TRUE");
            }else {
                Auth developerProvider = new Auth(
                        null,
                        "ap-northeast-1:a871fa5fxxxxxxxxxxxxx1437244",
                        Regions.AP_NORTHEAST_1, this.ctx);
                CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
                        this.ctx.getApplicationContext(),
                        developerProvider,
                        Regions.AP_NORTHEAST_1);
    
    
                HashMap<String, String> loginsMap = new HashMap<String, String>();
                loginsMap.put("cognito-identity.amazonaws.com", credentialsProvider.getToken());
                credentialsProvider.setLogins(loginsMap);
                credentialsProvider.refresh();
    
                ClientConfiguration configuration = new ClientConfiguration();
                configuration.setProtocol(Protocol.HTTP);
                configuration.setSocketTimeout(5 * 10000);
                configuration.setConnectionTimeout(5 * 10000);
                configuration.setMaxErrorRetry(3);
                configuration.setMaxConnections(100);
    
                if (sS3Client == null) {
    
                    sS3Client = new AmazonS3Client(credentialsProvider, configuration);
    
                }
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
    
            if(sS3Client!=null){
    
                sTransferUtility = new TransferUtility(sS3Client, this.ctx);
    
                observer = sTransferUtility.upload(remotepath, file.getName(), file);
                transferObservers.add(observer);
    
                observer.setTransferListener(new UploadListener(this.progressBar,observer,file.getPath()));
    
            }
    
        }
    }
    
    私有类上载文件扩展了异步任务{
    上下文ctx;
    字符串远程路径;
    文件;
    ProgressBar ProgressBar;
    私有上传文件(上下文ctx、文件文件、字符串远程路径、ProgressBar ProgressBar){
    this.ctx=ctx;
    this.file=file;
    this.remotepath=remotepath;
    this.progressBar=progressBar;
    }
    @凌驾
    受保护的void onPreExecute(){
    super.onPreExecute();
    }
    @凌驾
    受保护的Void doInBackground(Void…参数){
    如果(!internetchek.isNetworkAvailable(this.ctx)| |!internetchek.connectGoogle()){
    Log.d(“网络”、“真实”);
    }否则{
    Auth developerProvider=new Auth(
    无效的
    “ap-northeast-1:a871fa5fxxxxxxxxxxxxx1437244”,
    Regions.AP_东北_1,this.ctx);
    CognitoCachingCredentialsProvider credentialsProvider=新CognitoCachingCredentialsProvider(
    this.ctx.getApplicationContext(),
    developerProvider,
    地区:亚太地区(东北地区1);
    HashMap loginsMap=新建HashMap();
    loginsMap.put(“cognito identity.amazonaws.com”,credentialsProvider.getToken());
    credentialsProvider.setLogins(loginsMap);
    credentialsProvider.refresh();
    ClientConfiguration=新的ClientConfiguration();
    setProtocol(Protocol.HTTP);
    配置:setSocketTimeout(5*10000);
    配置。setConnectionTimeout(5*10000);
    setMaxErrorRetry(3);
    配置。setMaxConnections(100);
    如果(sS3Client==null){
    sS3Client=新的AmazonS3Client(credentialsProvider,配置);
    }
    }
    返回null;
    }
    @凌驾
    受保护的void onPostExecute(void避免){
    super.onPostExecute(避免);
    如果(sS3Client!=null){
    sTransferUtility=新的TransferUtility(sS3Client,this.ctx);
    observer=sTransferUtility.upload(remotepath,file.getName(),file);
    转让观察员。添加(观察员);
    setTransferListener(新的UploadListener(this.progressBar,observer,file.getPath());
    }
    }
    }
    
  • 我可以马上想到两种方法:

    a。使用令牌的简单try/catch-around代码。如果它抛出一个适当的异常,请获取一个新异常并重试

    b。使用开发人员身份验证标识,可以配置令牌的有效长度。你可以很容易地在应用程序中跟踪它,并在它过期时采取适当的行动。这是我推荐的路线

  • 我不知道你这是什么意思。SDK会在检索它们之后存储它们。您可以使用getIdentityId()或getCachedIdentityId()获取id,为什么需要令牌


  • 理想/推荐的流程是您不必手动处理它们。一旦SDK拥有了它们,您就应该能够使用凭据提供程序来获取可以访问S3的凭据。这将有助于保存令牌并重用它,但同样,这不应该是您的额外工作

  • 编辑:

    您不应该每次都在新线程中重新创建凭据提供程序。它将失去状态,您将不得不不断联系后端。它应该是一个单例,如和示例中所示(链接到该博客文章)

    您还应该向提供者提供您在控制台上配置的提供者的密钥,而不是cognito-identity.amazonaws.com

    你设置令牌的方式看起来也不太对劲。此示例设置如下所示的登录:

    CognitoSyncClientManager
                .addLogins(
                        ((DeveloperAuthenticationProvider) CognitoSyncClientManager.provider
                                .getIdentityProvider()).getProviderName(),
                        userName);
    
    我建议再看一下这个示例,在实现上似乎有一些差异

  • 我可以马上想到两种方法:

    a。使用令牌的简单try/catch-around代码。如果它抛出一个适当的异常,请获取一个新异常并重试

    b。使用开发人员身份验证标识,可以配置令牌的有效长度。你可以很容易地在应用程序中跟踪它,并在它过期时采取适当的行动。这是我推荐的路线

  • 我不知道你这是什么意思。SDK会在检索它们之后存储它们。您可以使用getIdentityId()或getCachedIdentityId()获取id,为什么需要令牌


  • 理想/推荐的流程是您不必手动处理它们。一旦SDK拥有了它们,您就应该能够使用凭据提供程序来获取可以访问S3的凭据。这将有助于保存令牌并重用它,但同样,这不应该是您的额外工作

  • 编辑:

    您不应该每次都在新线程中重新创建凭据提供程序。它将失去状态,您将不得不不断联系后端。它应该是一个单例,如和示例中所示(链接到该博客文章)

    您还应该向提供者提供您在控制台上配置的提供者的密钥,而不是cognito-identity.amazonaws.com

    你的生活方式