【问题标题】:Laravel /w Ionic JWT authenticationLaravel /w 离子 JWT 身份验证
【发布时间】:2016-07-28 18:38:55
【问题描述】:

所以我正在开发带有 Laravel 后端并使用 JWT 身份验证的 Ionic 应用程序。

我的问题是...因为我在注册用户时使用了 4 个字段,而在登录时只使用了 2 个字段(电子邮件和密码),我想在注册时令牌应该只由这 2 个字段组成...

这是有效的注册功能:

public function signUp()
{
    $credentials = Input::all();

    if (User::whereEmail($credentials['email'])->first()) {
        return Response::json([
            'error' => 'User with given e-mail already exists',
        ], 409);
    } elseif (User::wherePhone($credentials['phone'])->first()) {
        return Response::json([
            'error' => 'User with given phone number already exists',
        ], 409);
    } else {
        $user = User::create($credentials);
        $token = JWTAuth::fromUser($user);

        return Response::json(compact('token'));
    }
}

但是,如果我更改 $credentials = Input::only('email', 'password'),则不会创建完整用户(因为缺少字段)。

但即使我原样离开$credentials,并进行如下组合 $token = JWTAuth::fromUser(Input::only('email', 'password')) 或将电子邮件和密码解析为 JSON,或类似的东西...我收到“尝试获取非对象的属性”错误,或者给出了该数组而不是 JWTAuth 的对象...

【问题讨论】:

    标签: php laravel authentication ionic-framework jwt


    【解决方案1】:

    JWTAuth::fromUser(Input::only('email', 'password')) 需要一个用户对象。

    如果您希望使用凭据,可以执行以下操作:

        // grab credentials from the request
        $credentials = Input::only('email', 'password');
    
        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return Response::json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return Response::json(['error' => 'could_not_create_token'], 500);
        }
    
        // all good so return the token
        return Response::json(compact('token'));
    

    https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens

    【讨论】:

    • 我已经阅读了文档,这确实有效......但是我的逻辑有缺陷:) 我有一个想法,即在注册时将令牌存储在数据库中,然后当用户登录时,令牌需要匹配......但我想这是一个更聪明,更可靠的解决方案,不将令牌存储在数据库中。谢谢
    猜你喜欢
    • 2020-03-18
    • 2020-01-05
    • 2019-01-07
    • 2017-05-13
    • 2016-08-17
    • 2020-07-23
    • 2017-06-12
    • 2020-08-17
    • 2019-04-30
    相关资源
    最近更新 更多