SignInAsync与AuthenticateAsync [英] SignInAsync vs AuthenticateAsync
问题描述
我终于有了JWT令牌认证的登录方法.
I finally got my login-method with JWT Token Authentication working.
我在打电话
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
ClaimsPrincipalFactory.CreatePrincipal(claims),
authProps);
我也叫
await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
在该示例中,我读到我只需要SignInAsync
.
因此,我对其进行了测试并删除了AuthenticateAsync
.但是User.Identity.IsAuthenticated
返回true
.
In the example I read that I only need the SignInAsync
.
So I tested it and removed AuthenticateAsync
. But still, User.Identity.IsAuthenticated
returns true
.
可以删除AuthenticateAsync
吗?还是我仍然需要它?为什么存在?
AuthenticateAsync
的文档字符串仅表示用于身份验证的扩展方法
Is it okay to remove the AuthenticateAsync
? Or do I still need it? Why does it exist?
The doc-string of AuthenticateAsync
only says Extension method for authenticate
推荐答案
以下是对来自Authentification框架(对于ASP.NET Core 2.0)的所有各种方法的概述,按在它们中调用的顺序典型的身份验证流程.
Here's a recap between all the various methods coming from the Authentification framework (for ASP.NET Core 2.0), in the order in which they're called in a typical auth flow.
ChallengeAsync
这将指导您的浏览器进行身份验证.例如:
This will instruct your browser on where to go to be authenticated. For example:
- Cookie会将您重定向到您自己的登录页面(例如
/Account/Login
) - Azure AD将您重定向到Microsoft登录页面
- 等.
AuthenticateAsync
此步骤处理来自身份验证页面(挑战"步骤将您重定向到该页面)的任何信息,并使用该信息来创建用于标识已登录用户的ClaimsPrincipal
实例.
This step handles whatever information comes from the authentification page (where you were redirected to by the Challenge step), and uses it to create a ClaimsPrincipal
instance that identify the logged in user.
然后将ClaimsPrincipal
分配给HttpContext.User
.
SignInAsync
此步骤采用从上一步构建的ClaimsPrincipal
,并将其持久化.当然,最常见的方式是cookie.
This step takes the ClaimsPrincipal
built from the previous step, and persists it. The most common way is of course the cookies.
请注意,基于 https://github.com/aspnet/Security/,这似乎是保留ClaimsPrincipal
的唯一方法.
Note that based on the source code in https://github.com/aspnet/Security/, it seems to be the only way to persist the ClaimsPrincipal
.
SignOutAsync
这是SignIn
步骤的相反步骤.它指示中间件删除所有保留的数据.
This is the reverse step of the SignIn
step. It instructs the middleware to delete any persisted data.
- Cookie将删除存储的Cookie
- Azure AD将您重定向到其Microsoft注销页面
- 等.
所以要回答您的问题,如果您已经有ClaimsPrincipal
,则无需调用AuthenticateAsync
.
So to answer your question, if you already have a ClaimsPrincipal
, calling AuthenticateAsync
is not necessary.
实际上,在调用AuthentificateAsync
之前您有ClaimsPrincipal
有点奇怪:)
In fact, it's a bit strange that you have a ClaimsPrincipal
before calling AuthentificateAsync
:)
这篇关于SignInAsync与AuthenticateAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!