Home  >  Article  >  Backend Development  >  关于自动登录的疑问

关于自动登录的疑问

WBOY
WBOYOriginal
2016-06-06 20:16:331244browse

想问一下app的自动登录功能是怎么做的, 把用户名和密码存在本地?

回复内容:

想问一下app的自动登录功能是怎么做的, 把用户名和密码存在本地?

一般是先登录一次,拿到一个授权 token。客户端保存这个 token,以后每次请求时,都带上这个 token。

如果请求时发现 token 过期了,app 再让用户跳转至登录页面重新授权。

具体到token的实现,可以考虑采用 jwt

<code>private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;</code>
<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);
    editor = sharedPreferences.edit();
    //打开app时读取保存的登录信息
    String username = sharedPreferences.getString("username", "");
    String password = sharedPreferences.getString("password", "");
    if(username != "" && password != ""){
        login(username,password);
        //login就是你要登录时的代码
    }
}
</code>
<code>    登录按钮被点击时
    取得username和password内容
    editor.putString("username", username);
    editor.putString("password", password);
    editor.commit()
    //登录时,保存用户名和密码
    </code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn