Laravel - 使用会话令牌进行身份验证

时间:2014-04-23 14:48:16

标签: session laravel token

登录后,我以JSON格式返回用户对象+会话令牌,以便可以验证连接到我的应用程序的移动设备。

但是,我很难理解如何使用他的会话ID来验证用户?

登录后,移动设备会在每次请求时发送会话令牌,这意味着我需要检查它是否是同一个用户(使用自定义身份验证过滤器)。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可能有一个用于保存令牌的表

在routes.php中添加过滤器

Route::group(array('before' => 'auth'), function() { ... })

在filters.php中,您可以搜索数据库中的令牌,如果不存在,则返回无访问响应

Route::filter('auth', function () {

$input_token = Input::get('token');

if (!empty($input_token)) {
    $validator = Validator::make(
        ['token' => $input_token],
        ['token' => 'token']
    );
    if (!$validator->fails()) {

        $token = Token::where('hash', $input_token)->first();

        if ($token) {

            $user = User::find($token->user_id);

            if ($user) {

                Auth::login($user);
                return;

            }
        }
    }
}

$response = Response::make(json_encode([
    'error' => true,
    'messages' => [
        Lang::get('errors.NO_ACCESS')
    ]
]), 200);

$response->header('Content-Type', 'application/json');

return $response;

});

答案 1 :(得分:0)

你可以这样做:

    // These two need to be declared outside the try/catch
    // so that they can be closed in the finally block.
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // Will contain the raw JSON response as a string.
    String jsonStr = null;

    try {
        // Construct the URL.  "BASED_URL + urlString" should be like this 
        // "http://api.instagram.com/oembed?url=https://instagram.com/p/6GgFE9JKzm/"
        URL url = new URL(BASED_URL + urlString);

        // open the connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();

        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
            // But it does make debugging a *lot* easier if you print out the completed
            // buffer for debugging.
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // Stream was empty.  No point in parsing.
            return null;
        }
        jsonStr = buffer.toString();
    } catch (IOException e) {
        exception = e;
        // If the code didn't successfully get the weather data, there's no point in attemping
        // to parse it.
        return null;
    } finally{
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                exception = e;
            }
        }
    }


    try {
        String mediaId = getMediaIdFromJson(jsonStr);
    } catch (JSONException e) {
        exception = e;
    } 


private String getMediaIdFromJson(String jsonStr) throws JSONException {
    // Parse media id from JSON
    if (jsonStr == null) {
        return "";
    }

    final String MEDIA_ID = "media_id";
    JSONObject jsonObject = new JSONObject(jsonStr);
    String mediaId = jsonObject.getString(MEDIA_ID);

    return mediaId;
}

不是最漂亮的代码,但它有效。它使用先前的会话ID创建会话实例,然后开始从文件加载它。用户ID在该密钥中,因此它只是在当前会话上设置用户ID。然后,当您调用Auth :: user()时,它会使用该用户ID加载用户。

密钥中所有数字的原因是因为幼虫开发人员认为散列Auth类名称以使密钥尽可能唯一是明智的...:-S