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
的文档字符串仅表示 Extension method for authentication
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 authentication 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
,并将其持久化.最常见的方式当然是cookies.
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.
- Cookies 会删除存储的 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屋!