简体   繁体   English

Android + PHP-保持用户登录

[英]Android + PHP - keep user logged

I want to keep the user logged in an android app (used java no kotlin). 我想让用户保持登录Android应用程序(使用Java No Kotlin)。

The problem is: In my php code at each user specific operation (like: getting user profile, user messages, editting, ....), I check for user session id, and this id is save in android's SQLite when logged in, but this session doesn't remain in the server it gets deleted after 2 hours (if not used) and also it doesn't returns a unique id, when a session gets deleted, the next user logs in the same id returns to him so after two hour the first user will be logged in as a different user XD. 问题是:在每个用户特定操作的php代码中(例如:获取用户个人资料,用户消息,编辑等),我检查用户会话ID,并且在登录时此ID保存在android的SQLite中,但是此会话不会保留在服务器中,它会在2小时后被删除(如果未使用),并且它不会返回唯一的ID,当会话被删除时,下一个用户登录时会返回相同的ID,因此两个小时后,第一个用户将以其他用户XD的身份登录。

So what should I do ? 所以我该怎么做 ? do I instead save the username and password and at each check I login or....? 而是保存用户名和密码,并在每次检查时登录还是...?

Some part of login check: 登录检查的一部分:

PHP Code for check user is logged in: 检查用户的PHP代码已登录:

session_id($_POST['conKey']);
session_start();
//1- connect and check if connection key is correct
if (Model::connect() == false) {
    throw new Exception('error, could not connect to the database');
} else if (!isset($_SESSION['conKey'])) {
    throw new Exception('no connection found');
} else if ($_SESSION['conKey'] != $_POST['conKey']) {
    throw new Exception('no connection found');
}

This is how I return the session id in php when logged in 这是我登录时在php中返回会话ID的方式

session_start();

$conKey = session_id();
if (empty($conKey)) {
    throw new Exception('Faild to start session, please make sure your app is allowed to store sessions');
}
$_SESSION['conKey'] = $conKey;
echo json_encode(['connectionKey' => $conKey]);

Java Code Part I send conKey (saved session id when logged in) from SQLite Java代码第I部分从SQLite发送conKey(登录时保存的会话ID)

use shared preferences to store username and password of the user. 使用共享首选项存储用户名和密码。 You can also generate a JWT token for successful login and save the JWT token in SharedPreferences 您还可以生成JWT令牌以成功登录,并将JWT令牌保存在SharedPreferences中

I would suggest different approach, instead of session ID, after successful login generate token ( How to generate token in PHP ). 我建议在成功登录后生成令牌( 如何在PHP中生成令牌 )而不是会话ID。
Save this token in database, now send this generated token to android client. 将此令牌保存在数据库中,现在将此生成的令牌发送到android客户端。 For every API hit check if the token matches. 对于每个API,请检查令牌是否匹配。
Unless you delete token, android client will always be logged-in. 除非您删除令牌,否则android client将始终处于登录状态。

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

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