小编use*_*457的帖子

使用cookie身份验证的ASP.NET Core 2.0自定义中间件

我需要为我的公司实施自定义"身份验证".我在引号中说这是因为用户在技术上在它到达应用程序之前进行了身份验证,如果是这样,userId将存在于请求标头中.

我需要做的是找出一种方法来查询数据库并根据该Id获取其他用户信息,并设置HttpContext.User对象,以便在应用程序中轻松使用它.

我现在采取的路线涉及使用没有ASP.NET核心身份的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?}");
        });
    }
Run Code Online (Sandbox Code Playgroud)

自定义中间件:

    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) …
Run Code Online (Sandbox Code Playgroud)

authentication cookies asp.net-core asp.net-core-middleware

4
推荐指数
1
解决办法
4476
查看次数