如何保存Dropbox用户详细信息,以便每次Android应用程序启动时都不进行身份验证?

时间:2017-03-16 12:56:14

标签: android dropbox-api

我正在构建一个Android应用程序,用户必须从Dropbox下载图片。然而,每次用户都必须验证自己。我希望应用程序第一次保存详细信息,之后不需要身份验证。代码如下:

protected void initialize_session(){
    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
    AndroidAuthSession session = new AndroidAuthSession(appKeys);
    mDBApi = new DropboxAPI<AndroidAuthSession>(session);
    mDBApi.getSession().startOAuth2Authentication(Control_Gate.this);
}


protected void onResume() {
    if (mDBApi.getSession().authenticationSuccessful()) {
        try {
            // Required to complete auth, sets the access token on the session
            mDBApi.getSession().finishAuthentication();;
            String accessToken = mDBApi.getSession().getOAuth2AccessToken();
        } catch (IllegalStateException e) {
            Log.i("DbAuthLog", "Error authenticating", e);
        }
    }
    super.onResume();
}

这是为了将用户返回到应用程序。我知道解决方案必须在这两个中,但我无法想出如何保存凭据。

2 个答案:

答案 0 :(得分:1)

在共享偏好/ SQLite中保存 accessToken

代表

SharedPreferences sp = getSharedPreferences(
                                            "First_share_memory", Activity.MODE_APPEND);
                                    // save in cache memory
                                    sp.edit().putString("accesstoken", accessToken).commit();

并在getDropboxAPI方法中使用它:

private DropboxAPI <AndroidAuthSession> getDropboxAPI() {
    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
    AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE);
    mDBApi = new DropboxAPI<AndroidAuthSession>(session);

SharedPreferences  sharedpreferences = getSharedPreferences("First_share_memory", Activity.MODE_APPEND);
String savedAccessToken = sharedpreferences.getString("accesstoken", "");// get previously saved accessToken

if (!TextUtils.isEmpty(savedAccessToken)) {
    mDBApi.getSession().setOAuth2AccessToken(savedAccessToken);
}

return mDBApi;
}

有关详细信息,请参阅参考:

link

答案 1 :(得分:1)

将您的令牌保存到SharedPrefernce,然后相应地使用它。下面是相同的示例代码。 在onResume函数中进行以下更改:

<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk.Web" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <PropertyGroup>
    <TargetFramework>net452</TargetFramework>
    <PreserveCompilationContext>false</PreserveCompilationContext>
    <AssemblyName>code</AssemblyName>
    <OutputType>Exe</OutputType>
    <PackageId>code</PackageId>
  </PropertyGroup>

  <!--<ItemGroup>
    <None Update="wwwroot\**\*">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
  </ItemGroup>-->

  <ItemGroup>
    <ProjectReference Include="..\..\legacyCommerce\Plugin.Sample.Habitat\Plugin.Sample.Habitat.csproj" />
    <ProjectReference Include="..\..\legacyCommerce\Plugin.Sample.Payments.Braintree\Plugin.Sample.Payments.Braintree.csproj" />
    <ProjectReference Include="..\..\legacyCommerce\Sitecore.Commerce.Plugin.AdventureWorks\Sitecore.Commerce.Plugin.AdventureWorks.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.0.3" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.OData" Version="6.0.0-alpha1-rtm-121216" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.1.0" />
    <PackageReference Include="Serilog" Version="2.4.0" />
    <PackageReference Include="Sitecore.Commerce.Core" Version="1.0.2301" />
    <PackageReference Include="Serilog.Sinks.Literate" Version="2.1.0" />
    <PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Filter" Version="1.1.1" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="1.4.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="1.0.2" />
    <PackageReference Include="Sitecore.Commerce.Provider.FileSystem" Version="1.0.2301" />
    <PackageReference Include="Sitecore.Framework.Rules" Version="1.1.12" />
    <PackageReference Include="Sitecore.Framework.Rules.Serialization" Version="1.1.12" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Sitecore.Framework.Diagnostics" Version="1.1.4" />
  </ItemGroup>

  <ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
    <Reference Include="System" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>

</Project>

添加storeKeys和clearKeys函数以在SharedPreferences中保存值

protected void onResume() {
        AndroidAuthSession session = mApi.getSession();
        setLoggedIn(mApi.getSession().authenticationSuccessful());
        if (session.authenticationSuccessful()) {
            try {
                // Mandatory call to complete the auth
                session.finishAuthentication();

                // Store it locally in our app for later use
                TokenPair tokens = session.getAccessTokenPair();
                storeKeys(tokens.key, tokens.secret);
                setLoggedIn(true);
            } catch (IllegalStateException e) {
                showToast(getString(R.string.could_not_authenticate_with_dropbox)
                        + e.getLocalizedMessage());
            }
        }
        super.onResume();
    }

并按如下所示初始化您的会话:

private void storeKeys(String key, String secret) {
        // Save the access key for later
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
        Editor edit = prefs.edit();
        edit.putString(ACCESS_KEY_NAME, key);
        edit.putString(ACCESS_SECRET_NAME, secret);
        edit.commit();
    }

    private void clearKeys() {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
        Editor edit = prefs.edit();
        edit.clear();
        edit.commit();
    }
private String[] getKeys() {
        SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
        String key = prefs.getString(ACCESS_KEY_NAME, null);
        String secret = prefs.getString(ACCESS_SECRET_NAME, null);
        if (key != null && secret != null) {
            String[] ret = new String[2];
            ret[0] = key;
            ret[1] = secret;
            return ret;
        } else {
            return null;
        }
    }

编辑:添加这三个常量,您可以注释setLoggedIn(true);

的调用
public AndroidAuthSession buildSession() {
        AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
        AndroidAuthSession session;

        String[] stored = getKeys();
        if (stored != null) {
            AccessTokenPair accessToken = new AccessTokenPair(stored[0],
                    stored[1]);
            session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE,
                    accessToken);
        } else {
            session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
        }
        return session;
    }
相关问题