Laravel RESTful API与Android应用程序
作者:互联网
我正在使用Laravel 5 Framework开发一个Android应用程序和一个RESTful API.
我在登录活动时遇到了麻烦:流程是用户要求输入第8个字符的代码,并且服务器网络向他发送了一条SMS.然后,用户可以使用此代码(如密码)进行登录.
这是询问代码的代码:
private void askCode(String mobile) {
GsonRequest<String> jsObjRequest = new GsonRequest<String>(
Request.Method.GET,
WebAPIRoute.authGetCode + "/" + mobile,
String.class, null,
new Response.Listener<String>() {
@Override
public void onResponse(String code) {
txtResponse.setText("Code asked successfully.");
}
},
new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError volleyError) {
Toast.makeText(getBaseContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
this.requestQueue.add(jsObjRequest);
}
并且此方法在RESTful API中生成代码:
public function getCode($mobileNum)
{
//genero un numero casuale da mandare con l'sms
$code = mt_rand(10000000, 99999999);
Session::put('code', $code);
sendCode($mobileNum, $code); //send code by SMS
return response()->json(array("success"=>true));
}
生成的代码存储在Laravel的Session中(使用文件驱动程序配置).
当用户想要登录时,应用程序调用此方法:
private void saveUser(final String code, final String mobile, final String name) {
HashMap<String, String> params = new HashMap<String, String>();
params.put("nickname", name);
params.put("mobile", mobile);
params.put("code", code);
GsonRequest<String> jsObjRequest = new GsonRequest<String>(
Request.Method.POST,
WebAPIRoute.authValidateCode,
String.class,
params,
new Response.Listener<String>() {
@Override
public void onResponse(String authtoken) {
final Account account = new Account(accountName, mAccountType);
String authtokenType = mAuthTokenType;
// Creating the account on the device and setting the auth token we got
// (Not setting the auth token will cause another call to the server to authenticate the user)
mAccountManager.addAccountExplicitly(account, code, null);
mAccountManager.setAuthToken(account, authtokenType, authtoken);
Bundle data = new Bundle();
data.putString(AccountManager.KEY_ACCOUNT_NAME, accountName);
data.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccountType);
data.putString(AccountManager.KEY_AUTHTOKEN, authtoken);
data.putString(PARAM_USER_PASS, code);
data.putBoolean(ARG_IS_ADDING_NEW_ACCOUNT, true);
final Intent res = new Intent();
res.putExtras(data);
setAccountAuthenticatorResult(res.getExtras());
Intent i = new Intent(getBaseContext(), MyEventsActivity.class);
startActivity(i);
}
}
,
new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError volleyError) {
Log.e(TAG, volleyError.getMessage(), volleyError);
showMessage("Errore nell'autenticazione. Riprova piu` tardi.");
}
});
requestQueue.add(jsObjRequest);
}
验证代码的API的方法如下:
public function validateCode() {
$code = trim(Input::get('code'));
$nickName = trim(Input::get('nickname'));
$phoneNum = trim(Input::get('mobile'));
if (empty($phoneNum))
abort(400, 'mobile parameters not provided.');
if (empty($code))
abort(400, 'code parameters not provided.');
if (empty($nickName))
abort(400, 'nickname parameters not provided.');
$validCode = Session::get('code');
Log::info('code: ' . $code . " validCode: " . $validCode);
if($code == $validCode) {
Session::forget('code');
// Retrieve the user by the attributes, or instantiate a new instance...
$user = User::firstOrCreate(['Mobile' => $phoneNum]);
//aggiorno i campi nickname e password col nuovo codice
$user->Nickname = $nickName;
$user->password = $code;
//save!
$user->save();
//viene usata l'autenticazione di Laravel e gli serve una password
$token = JWTAuth::attempt(['Mobile' => $phoneNum, 'password' => $code]);
return response()->json($token);
} else {
//return response()->json(array('success' => false, 'error' => 'The code isn\'t correct.'));
abort(401, 'The code isn\'t correct.' . $validCode);
}
}
我已经用Chrome和Firefox测试了RESTful API,并且登录有效.随着应用程序号.实际上,问题在于Session :: get(‘code’);在validateCode中始终返回一个空值.我检查了使用Session :: put(‘code’,$code);生成的Session文件;并且是正确的.但是,当调用Session :: get(‘code’)时,Laravel会生成另一个Session文件,似乎不使用前一个文件.
我在RESTful API中禁用了CSRF中间件.
怎么了?
解决方法:
在服务器端存储会话毫无意义. API假定是无状态的,因此第二次您完成对代码的第一个请求并将其存储在服务器端的会话中时,该会话将结束,下一个请求将不记得您设置的任何内容.
如果您想保持代码登录状态并避免使用令牌,那么您将不得不从android应用发送唯一的代码来识别用户.然后在服务器端生成代码,并将其存储在具有user_identifier和generate_code的表中,并创建一个模型来访问它,例如
尝试登录
user_id | generateCode
0001 | 87392042
0032 | 83214320
然后将其添加到saveUser
params.put("user_id", user_id); // can be the android device ID or even a unique timestamp
最后,在服务器端的validateCode中,将$validCode行替换为以下内容:
$user_id = trim(Input::get('user_id'));
....
$validCode = AttemptedLogin::where('user_id', $user_id)->first();
if($code == $validCode->generatedCode) {
$validCode->delete();
....
标签:laravel-5,rest,api,session,android 来源: https://codeday.me/bug/20191120/2041929.html