简体   繁体   English

没有Identity ASP.NET Core v2的Cookie中间件

[英]Cookie Middleware without Identity ASP.NET Core v2

I am trying to authenticate without using identity. 我试图在不使用身份的情况下进行身份验证。 I have found a few articles describing how to do it in other versions however nothing for ASP.NET Core 2. 我发现了一些文章描述了如何在其他版本中执行它,但对于ASP.NET Core 2没有任何内容。

Below is what I have cobbled together. 以下是我拼凑在一起的内容。 But when it gets to SignInAsync an exception is thrown InvalidOperationException: No authentication handler is configured to handle the scheme: MyCookieMiddlewareInstance 但是当它到达SignInAsync时会抛出异常InvalidOperationException: No authentication handler is configured to handle the scheme: MyCookieMiddlewareInstance

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddCookieAuthentication("MyCookieMiddlewareInstance", o =>
        {
            o.LoginPath = new PathString("/Account/Login/");
            o.AccessDeniedPath = new PathString("/Account/Forbidden/");

        });
        services.AddAuthentication();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        app.UseAuthentication();
    }

    public async Task<IActionResult> Login()
    {

        var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, "joe nobody")
            };
        var identity = new ClaimsIdentity(claims, "MyCookieMiddlewareInstance");
        var principal = new ClaimsPrincipal(identity);

        //blows up on the following statement:
        //InvalidOperationException: No authentication handler is configured to handle the scheme: MyCookieMiddlewareInstance
        await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal); 

        return View();
    }

There is a Microsoft document for asp.net core v1.x ( https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie ) however the IApplicationBuilder.UseCookieAuthentication() is depreciated in v2 and haven't found any solution. 有一个针对asp.net core v1.x的Microsoft文档( https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie ),但是在v2中对IApplicationBuilder.UseCookieAuthentication()进行了折旧。没有找到任何解决方案。

It looks like there are a few breaking changes with Auth 2.0 ( https://github.com/aspnet/Announcements/issues/232 ) 看起来Auth 2.0有一些重大变化( https://github.com/aspnet/Announcements/issues/232

The setup was correct however I needed to do two things: 设置是正确的,但我需要做两件事:

  1. Use HttpContext.SignInAsync() ( using Microsoft.AspNetCore.Authentication ) instead of HttpContext.Authentication.SignInAsync() 使用HttpContext.SignInAsync()using Microsoft.AspNetCore.Authentication )代替HttpContext.Authentication.SignInAsync()
  2. Use "AuthenticationTypes.Federation" as the authentication type (Note: other values don't seem to work and blank will result in the user name being set and IsAuthenticated to false) var identity = new ClaimsIdentity(claims, "AuthenticationTypes.Federation"); 使用"AuthenticationTypes.Federation"作为身份验证类型(注意:其他值似乎不起作用,空白将导致设置用户名并且IsAuthenticated为false) var identity = new ClaimsIdentity(claims, "AuthenticationTypes.Federation");

Below is the corrected code 以下是更正后的代码

In Startup.cs 在Startup.cs中

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddCookieAuthentication("MyCookieMiddlewareInstance", o =>
        {
            o.LoginPath = new PathString("/Account/Login/");
            o.AccessDeniedPath = new PathString("/Account/Forbidden/");
        });
        services.AddAuthentication();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

In Controller 在控制器中

    using Microsoft.AspNetCore.Authentication;
    //...
    public async Task<IActionResult> Login()
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, "joe nobody")
        };
        var identity = new ClaimsIdentity(claims, "AuthenticationTypes.Federation");
        var principal = new ClaimsPrincipal(identity);
        await HttpContext.SignInAsync("MyCookieMiddlewareInstance", principal);

        return View();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 没有身份验证Asp.net核心的Cookie - Cookie without Identity Asp.net core ASP.NET核心身份3 Cookie超时 - ASP.NET Core Identity 3 Cookie timeout 使用 cookie 身份验证的 ASP.NET Core 2.0 自定义中间件 - ASP.NET Core 2.0 custom middleware using cookie authentication 没有身份的 ASP.NET Core 2.0 Cookie 身份验证不指向 LoginPath - ASP.NET Core 2.0 Cookie Authentication without identity not directing to LoginPath ASP.NET 核心。 如何在没有身份用户帐户的情况下创建身份验证 cookie? - ASP.NET Core. How can i create an auth cookie without an identity user account? 在 ASP.NET Core 2.2 和 ASP 之间共享 Cookie 身份验证。 NET MVC 5 (.NET Framework 4.6.1) 没有 Microsoft.Identity - Share Cookie authentication between ASP.NET Core 2.2 and ASP. NET MVC 5 (.NET Framework 4.6.1) without Microsoft.Identity ASP.NET Core身份:是否希望保留应用程序cookie? - ASP.NET Core Identity: intended that application cookie remains? 为什么 ASP.NET Core Identity Cookie 不能跨域工作? - Why ASP.NET Core Identity Cookie is not working across domains? 页面上的Cookie身份验证问题请求ASP.NET Core和身份 - Cookie authentication issues on page request ASP.NET Core & Identity 使用 ASP.NET Core 2.1 / 3+ 身份验证身份验证 cookie - Validate authentication cookie with ASP.NET Core 2.1 / 3+ Identity
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM