How can i implement Cookie base authentication and jwt in asp.net core 2.2?

后端 未结 1 722
执笔经年
执笔经年 2021-02-11 07:58

I want to use both cookie based authentication and jwt in my program, used authentication user to access mvc controller with login and JWT to access We

1条回答
  •  爱一瞬间的悲伤
    2021-02-11 08:39

    In order to add support for JWT, we added the AddCookie and AddJwtBearer. Having websites require the token in the header would be a headache, especially for projects that aren’t purely SPA or API. So what I really wanted was support for both Cookies and JWTs.

    In startup.cs you have:

        public class Startup
      {
        public Startup(IConfiguration configuration)
        {
          Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
          services.AddDbContext(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
          services.AddIdentity()
              .AddEntityFrameworkStores()
              .AddDefaultTokenProviders();
    
          // Enable Dual Authentication 
          services.AddAuthentication()
            .AddCookie(cfg => cfg.SlidingExpiration = true)
            .AddJwtBearer(cfg =>
            {
              cfg.RequireHttpsMetadata = false;
              cfg.SaveToken = true;
              cfg.TokenValidationParameters = new TokenValidationParameters()
              {
                ValidIssuer = Configuration["Tokens:Issuer"],
                ValidAudience = Configuration["Tokens:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
              };
            });
    
          // Add application services.
          services.AddTransient();
          services.AddMvc();
        }
    

    And In Configure method:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataSeeder seeder)
    {
      ...
      app.UseAuthentication();
    }
    

    After this in your controller that one you have used JWT, You should add JWT Bearer AuthenticationSchemes to Authorize attribute like this :

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
      [Route("/api/customers")]
      public class ProtectedController : Controller
      {
        public ProtectedController()
        {
        }
    
        public IActionResult Get()
        {
          return Ok(new[] { "One", "Two", "Three" });
        }
      }
    

    Refrence: Two AuthorizationSchemes in ASP.NET Core 2

    It's very simple and helpful to used.

    0 讨论(0)
提交回复
热议问题