[英]How to check if user is authenticated in Web API 2
I have a Web API 2 service. 我有一个Web API 2服务。 In ApiController I create some different methods. 在ApiController中,我创建了一些不同的方法。 One of these methods is used for user Login. 这些方法之一用于用户登录。 In this method I can check user name and password hash selected from DB, and if they are correct, I can generate SessionID for current user session identification. 通过这种方法,我可以检查从数据库中选择的用户名和密码哈希,如果它们正确,则可以为当前用户会话标识生成SessionID。 But when I call other method and trying to check generated in previous step SessionID, this ID is empty (null). 但是,当我调用其他方法并尝试检查上一步SessionID中生成的ID时,此ID为空(空)。 How I can to save this SessionID and how I can check if user is already authenticated in service ? 如何保存此SessionID,以及如何检查用户是否已经在服务中进行了身份验证? I don't want to select user name and password hash from DB on each new method call. 我不想在每个新方法调用中从数据库中选择用户名和密码哈希。 I just want to store this information somewhere and have ability to read it in each ApiController method or somewhere else. 我只想将此信息存储在某个地方,并能够在每个ApiController方法或其他地方读取它。
I do this in the following steps: 我按以下步骤进行操作:
Hope this is clear. 希望这很清楚。
What you describe sounds like cookie-based authentication to me. 您所说的对我来说听起来像是基于cookie的身份验证。 For the you could take a look a ASP.NET Identity 2.0 which works (mostly) flawlessly with WebAPI 2.0. 您可以看一下ASP.NET Identity 2.0,它与WebAPI 2.0完美兼容(大多数情况下)。
In the standard setup (with forms login) ASP.NET Identity will create a session cookie containing proof of authentication so that no subsequent database calls are required. 在标准设置(使用表单登录)中,ASP.NET Identity将创建一个包含身份验证证明的会话cookie,因此不需要后续的数据库调用。 Additionally you get things like claims and roles for free and you can integrate with social authentication providers with very few LOCs! 此外,您还可以免费获得诸如声明和角色之类的东西,并且可以与具有很少LOC的社交身份验证提供程序集成! It plays very well with Entity Framework too, so if you already use that just go for Identity! 它在Entity Framework中也能很好地发挥作用,因此,如果您已经使用过,那就去找Identity吧!
If you want to roll your own, you may want to serialize the "user-profile" to a cookie and sign it cryptographically in order to make it tamper-proof. 如果要自己滚动,则可能需要将“用户配置文件”序列化为cookie并进行加密签名,以防篡改。 Then a middleware just has to de-serialize it and to put it as User-identity into the request object (considering you are using OWIN) 然后,中间件只需要反序列化并将其作为用户身份放入请求对象中(考虑到您正在使用OWIN)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.