【发布时间】:2017-10-25 17:23:47
【问题描述】:
我需要为我的公司实施自定义“身份验证”。 我之所以这么说是因为用户在访问应用程序之前在技术上已经过身份验证,如果是这样,userId 将存在于请求标头中。
我需要做的是找出一种方法来查询数据库并根据该 Id 获取其他用户信息,并设置 HttpContext.User 对象,以便可以在应用程序中轻松使用它。
我现在采取的路线涉及使用没有 ASP.NET Core 身份的 Cookie 身份验证。我将这个想法与自定义中间件相结合,该中间件将为用户查询数据库,从 db 字段填充声明,并使用 context.SignInAsync 创建 cookie。我将此中间件放在 app.UseAuthentication() 之前。问题是在第一次请求时未设置 .User 对象,因为似乎 SignIn 方法仅创建 cookie 但未设置 .User 对象。身份验证中间件还没有看到 cookie,因为它在第一次请求时不存在。
谁能提供任何想法?也许我做错了,或者这种技术很好,但我错过了让它发挥作用所需的东西。
在 Startup.cs 中:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication("MyAuthenticationCookie")
.AddCookie("MyAuthenticationCookie");
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMyUserMiddleware();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
自定义中间件:
public class MyUserMiddleware
{
private readonly RequestDelegate _next;
public MyUserMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
// Sign in user if this auth cookie doesn't exist
if (context.Request.Cookies[".AspNetCore.MyAuthenticationCookie"] == null)
{
// Get user from db - not done
// Set claims from user object - put in dummy test name for now
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "TEST"),
};
var claimsIdentity = new ClaimsIdentity(claims, "MyAuthenticationCookie");
context.SignInAsync("MyAuthenticationCookie", new ClaimsPrincipal(claimsIdentity));
}
return this._next(context);
}
}
public static class MyUserMiddlewareExtensions
{
public static IApplicationBuilder UseMyUserMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyUserMiddleware>();
}
}
【问题讨论】:
-
“用户在访问应用程序之前在技术上得到了身份验证”?这听起来像是一个 Intranet 应用程序。您是否尝试过 Windows 身份验证? “用户 ID 将存在于请求标头中”?那么请求头中只会有一个自定义请求头属性“x-user-id”,2?哇,那是东西。
-
我无法决定这部分是如何完成的。
-
尝试在
services.AddAuthentication()和context.SignInAsync()中将MyAuthenticationCookie替换为CookieAuthenticationDefaults.AuthenticationScheme。然后在.AddCookie(options => { options.Cookie.Name = "xxxxxx"; })中设置cookie的名称。 -
不会改变看起来的行为。
标签: c# asp.net-core authentication cookies asp.net-core-middleware