繁体   English   中英

AWS Cognito和S3

[英]AWS Cognito and S3

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

我几乎没有问题

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

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

  3. 对我的项目使用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()));

        }

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

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

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

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

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

编辑:

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

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

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

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

我建议再给一个样本,看起来在实现上有一些差异。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM