热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用没有密码的JWTLaravel5进行身份验证-AuthenticationwithJWTLaravel5withoutpassword

ImtryingtolearnLaravelandmygoalistobeabletobuildaRESTfulAPI(nouseofviewsorbla

I'm trying to learn Laravel and my goal is to be able to build a RESTful API (no use of views or blade, only JSON results. Later, an AngularJS web app and a Cordova hybrid mobile app will consume this api.

我正在尝试学习Laravel,我的目标是能够构建RESTful API(不使用视图或刀片,只使用JSON结果。稍后,AngularJS Web应用程序和Cordova混合移动应用程序将使用此API。

After some research, I'm inclining to choose JWT-Auth library for completely stateless benefit. My problem is: I have 2 main types of users: customers and moderators. Customers are not required to have a password. I need to be able to generate a token for access with the provided email only. If that email exists in the database and it belongs to a customer, it will generate and return the token. If it exists and belongs to a moderator, it will return false so the interface can request a password. If the email doesn't exist, it throws an invalid parameter error.

经过一些研究,我倾向于选择JWT-Auth库来获得完全无国籍的好处。我的问题是:我有两种主要类型的用户:客户和版主。客户无需拥有密码。我需要能够使用提供的电子邮件生成用于访问的令牌。如果该电子邮件存在于数据库中并且它属于客户,则它将生成并返回该令牌。如果它存在且属于主持人,则它将返回false,以便接口可以请求密码。如果电子邮件不存在,则会引发无效的参数错误。

I read the docs here and it says it's possible to use Custom Claims. But the docs doesn't explain what are claims and what it means the array being passed as custom claims. I'd like some input on how to go about achieving what I explain above.

我在这里阅读了文档,并说它可以使用自定义声明。但是文档并没有解释什么是声明,以及数组作为自定义声明传递的含义。我想要了解如何实现我上面解释的内容。

    only('email', 'password');

        try {
            // 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
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        // if no errors are encountered we can return a JWT
        return response()->json(compact('token'));
    }
}

Thanks you.

谢谢。

Update

Bounty's code

赏金的代码

public function authenticate(Request $request) { 
    $email = $request->input('email');
    $user = User::where('email', '=', $email)->first();
    try { 
        // verify the credentials and create a token for the user
        if (! $token = JWTAuth::fromUser($user)) { 
            return response()->json(['error' => 'invalid_credentials'], 401);
        } 
    } catch (JWTException $e) { 
        // something went wrong 
        return response()->json(['error' => 'could_not_create_token'], 500); 
    } 
    // if no errors are encountered we can return a JWT 
    return response()->json(compact('token')); 
}

3 个解决方案

#1


14  

try with this:

试试这个:

$user=User::where('email','=','user2@gmail.com')->first();

if (!$userToken=JWTAuth::fromUser($user)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }

return response()->json(compact('userToken'));

it's work for me, hope can help

它对我有用,希望可以帮到你

#2


5  

Generating token for the customers (without password) can be achieved through

可以通过为客户生成令牌(无密码)

$user = \App\Modules\User\Models\UserModel::whereEmail('xyz@gmail.com')->first();
$userToken=JWTAuth::fromUser($user);

Here $userToken will stores the token after existence check of email in the table configured in UserModel file.

这里$ userToken将在UserModel文件中配置的表中存在电子邮件检查后存储令牌。

I have assumed that you stores both customer and moderators in the same table, there must be some flag to discriminate among them. Assume the flag is user_type

我假设您将客户和版主存储在同一个表中,必须有一些标志来区分它们。假设标志是user_type

$token = null;
$user = \App\Modules\User\Models\UserModel::whereEmail('xyz@gmail.com')->first();
if($user['user_type'] == 'customer'){
   $credentials = $request->only('email');
   $token =JWTAuth::fromUser($user);
}else if($user['user_type'] == 'moderator'){
   $credentials = $request->only('email','password');
   $token = JWTAuth::attempt($credentials);
}else{
   //No such user exists

}
return $token;

As far as custom claims are concerned these are custom defined payloads which can be attached to token string.

就自定义声明而言,这些是自定义的有效负载,可以附加到令牌字符串。

For example, JWTAuth::attempt($credentials,['role'=>1]); Will attempt to add role object to token payload. Once you decode the token string through JWT Facade JWTAuth::parseToken()->getPayload(); you in turn get all payloads defined in required_claims under config/jwt.php with additional role payload.

例如,JWTAuth :: attempt($ credentials,['role'=> 1]);将尝试将角色对象添加到令牌有效内容。通过JWT Facade解码令牌字符串JWTAuth :: parseToken() - > getPayload();您将获得在config / jwt.php下的required_claims中定义的所有有效负载以及其他角色有效负载。

Refer https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens#creating-a-token-based-on-anything-you-like Let me know in case you requires anything else.

请参阅https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens#creating-a-token-based-on-anything-you-like如果您需要其他任何内容,请告诉我。

#3


0  

Rather than making a different login strategy for customers and moderators, you can add token authentication to both user type. this will makes your life easier and prepare for scalability. In your api, you can just restrict moderator users to not have access to the api by sending

您可以为两种用户类型添加令牌身份验证,而不是为客户和管理员制定不同的登录策略。这将使您的生活更轻松,并为可扩展性做好准备。在您的api中,您可以通过发送限制主持人用户无权访问API

'method not allowed')

Apart from this suggestion, I believe @Alimnjan code should work.

除了这个建议,我相信@Alimnjan代码应该可行。


推荐阅读
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文介绍了如何使用Express App提供静态文件,同时提到了一些不需要使用的文件,如package.json和/.ssh/known_hosts,并解释了为什么app.get('*')无法捕获所有请求以及为什么app.use(express.static(__dirname))可能会提供不需要的文件。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • 本文介绍了Sencha Touch的学习使用心得,主要包括搭建项目框架的过程。作者强调了使用MVC模式的重要性,并提供了一个干净的引用示例。文章还介绍了Index.html页面的作用,以及如何通过链接样式表来改变全局风格。 ... [详细]
  • 单页面应用 VS 多页面应用的区别和适用场景
    本文主要介绍了单页面应用(SPA)和多页面应用(MPA)的区别和适用场景。单页面应用只有一个主页面,所有内容都包含在主页面中,页面切换快但需要做相关的调优;多页面应用有多个独立的页面,每个页面都要加载相关资源,页面切换慢但适用于对SEO要求较高的应用。文章还提到了两者在资源加载、过渡动画、路由模式和数据传递方面的差异。 ... [详细]
  • vue使用
    关键词: ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • Ihavethefollowingonhtml我在html上有以下内容<html><head><scriptsrc..3003_Tes ... [详细]
  • 深度学习中的Vision Transformer (ViT)详解
    本文详细介绍了深度学习中的Vision Transformer (ViT)方法。首先介绍了相关工作和ViT的基本原理,包括图像块嵌入、可学习的嵌入、位置嵌入和Transformer编码器等。接着讨论了ViT的张量维度变化、归纳偏置与混合架构、微调及更高分辨率等方面。最后给出了实验结果和相关代码的链接。本文的研究表明,对于CV任务,直接应用纯Transformer架构于图像块序列是可行的,无需依赖于卷积网络。 ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • 实现一个通讯录系统,可添加、删除、修改、查找、显示、清空、排序通讯录信息
    本文介绍了如何实现一个通讯录系统,该系统可以实现添加、删除、修改、查找、显示、清空、排序通讯录信息的功能。通过定义结构体LINK和PEOPLE来存储通讯录信息,使用相关函数来实现各项功能。详细介绍了每个功能的实现方法。 ... [详细]
  • 从零基础到精通的前台学习路线
    随着互联网的发展,前台开发工程师成为市场上非常抢手的人才。本文介绍了从零基础到精通前台开发的学习路线,包括学习HTML、CSS、JavaScript等基础知识和常用工具的使用。通过循序渐进的学习,可以掌握前台开发的基本技能,并有能力找到一份月薪8000以上的工作。 ... [详细]
author-avatar
ttarm_33218389
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有