identity如何与mvc核心协同工作。
作为@
Chris Pratt
你说的是安全子系统。既然你说的是cookie,我就以cookie的身份验证方案为例。
内置安全性主要体现在4个项目中:
-
HttpAbstractions
:核心接口和类,如身份验证方案、身份验证处理程序、身份验证票证等。
-
Security
:身份验证中间件、cookie身份验证、JWT承载身份验证、OAuth2.0身份验证(Google/Facebook/Microsoft/…)等等。
-
Identity
:一个名为“Identity”的脚手架项目,用于帮助管理用户/角色/声明等。
-
DataProtection
:用于保护和取消保护数据的数据保护API。您可以将其视为加密和解密的API。
AuthenticationMiddleware
. 如果可能,此中间件将尝试验证每个请求:
public async Task Invoke(HttpContext context)
{
// ...
// Give any IAuthenticationRequestHandler schemes a chance to handle the request
var handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync())
{
var handler = await handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler;
if (handler != null && await handler.HandleRequestAsync())
{
return;
}
}
// Use the default scheme to authenticate request
var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticate != null)
{
var result = await context.AuthenticateAsync(defaultAuthenticate.Name);
if (result?.Principal != null)
{
context.User = result.Principal;
}
}
await _next(context);
}
通常,这个中间件在其他中间件/mvc之前运行,因此您可以根据需要拦截请求。
url
[Authorize]
如果不登录,它会要求您通过某种方案登录。您可以根据需要配置您的服务以使用不同的方案,例如Jwt承载、cookies等等。
CookieAuthenticationHandler
将进行重载:
注意所有这些都是由
Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationHandler
,即中定义的处理程序
aspnet/Security
,而不是
aspnet/Identity
图书馆
.
为什么我不能偷那块饼干当自己的?
-
当然,你可以偷别人的饼干当自己的。实际上,如果爱丽丝的饼干被鲍勃偷了(比方说
XSS
或
sniffering
),鲍勃将被视为爱丽丝。ASP.NET核心(以及其他技术,如PHP/Python/Java)无法防止这种情况的发生,要防止这种情况,还有很多工作要做:
-
网站应该使用
HTTPS
而不是
HTTP
-
<
,
>
,
<img onclick='javascript:'
以此类推以防止XSS
-
-
而且,有时候你不需要偷别人的饼干。由
CSRF
,你只是“借”他的饼干。
为什么这样安全
另一件事是你很难在客户端伪造饼干。