Android c#应用程序登录最佳实践
本文关键字:最佳 登录 应用程序 Android | 更新日期: 2023-09-27 18:06:47
我正在用c#制作一个android应用程序,它以登录页面开始。当应用程序关闭时,用户必须重新登录。
自动登录、存储凭证并检索它们的最佳实践是什么?(如果这是最好的方法)
感谢里卡多。
您可以按照以下步骤操作
- 登录成功后,将凭证保存在SQlite db或您正在使用的任何其他数据库中。
- 注销时,使用DeleteAll<>()方法清除这些凭证。
- 在启动/启动屏幕,首先检查凭据是否存在。 显示用户登录界面
- 如果你不希望删除凭据,在用户对象中使用布尔标志并相应地标记。
- 在更改密码时,请确保将旧凭据替换为新凭据,否则用户可以使用旧凭据登录应用程序
首先应该使用ISharedPreferences
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using Android.Preferences;
namespace App
{
[Activity(Label = "App", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
//to get data that already stored in Shared Preferences use prefs.get----
//to put new data in Shared Preferences Editor use editor.put----
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor editor = prefs.Edit();
if (prefs.GetBoolean("is_login",false))
{
//prefs.GetBoolean("key",defualt value)
//here use is logged in alread now open main page but note
//you need for exmaple his id to make some opration in main page after login
Intent x = new Intent(this,typeof(Activity2));
StartActivity(x);
}
else
{
//here user is not logged in now to can show login page and after that you need to put
//in local setting login=true like that
editor.PutBoolean("is_login", true);
editor.Apply();
}
}
}
}
这个问题的答案在stackoverflow中(在理解了sharedpreference是实现这个目标的最佳方法之后):
这里带类的例子工作得很好。
答案的最后一部分(作为最佳实践)是检查令牌时,据我所知,是每次应用程序联系服务器,检查令牌是否正确或过期,或更改(由于密码更新或用户删除)。
所以这个最佳实践应该是一个全局行为,例如在需要时更新令牌,并在应用程序与服务器交互时检查它。
谢谢大家的回答