AWS Cognito和S3

时间:2016-05-03 18:15:39

标签: android amazon-web-services amazon-s3 amazon-cognito

我正在开发Android应用,其中用户从Amazon S3上传和下载文件。我为我的应用程序开发了身份验证。目前,每当用户想要上传少量文件时,每个文件用户都可以通过ping后端来获取IdentityIDToken

我的问题很少

  1. 我如何知道令牌是否已过期?

  2. AWS API是否会保存令牌和身份?如果是,如何检索它们?

  3. 对我的项目使用IdentityId和令牌的最佳方法是什么?为每个文件调用后端来获取令牌?或者当用户想要上传一堆(选定)文件时要求一次?或者如果令牌未过期,保存令牌并重新使用它?

  4. CODE:

    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();
            }
    
    }}
    

    Uploadfile

    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()));
    
            }
    
        }
    }
    

1 个答案:

答案 0 :(得分:0)

  1. 我可以想到两种方法:

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

    湾使用开发人员身份验证身份,您可以配置令牌的有效长度。您可以轻松跟踪应用内部的内容,并在到期时采取相应的措施。这是我推荐的路线。

  2. 我不确定你的意思。 SDK会在检索后存储它们。您可以使用getIdentityId()或getCachedIdentityId()获取id,为什么需要令牌?

  3. 理想/推荐的流程是您无需手动执行任何操作。 SDK拥有它们后,您应该只能使用凭据提供程序获取可以访问S3的凭据。这样可以保存令牌并重复使用它,但同样,这不应该是你的额外工作。

  4. 编辑:

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

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

    您设置令牌的方式也会关闭。该示例设置如下登录:

    CognitoSyncClientManager
                .addLogins(
                        ((DeveloperAuthenticationProvider) CognitoSyncClientManager.provider
                                .getIdentityProvider()).getProviderName(),
                        userName);
    

    我建议再给一个样本,实现中似乎有一些差异。