asp.net core cookie和jwt简单的登录认证

  1. 首先在Startup.cs文件中配置Cookie认证和jwt认证
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.IdentityModel.Tokens;
    
    namespace JwtDemo
    {
        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.AddControllersWithViews();
                //这里为jwt登录验证的的key,在配置文件中
                var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]));
                services.AddSingleton(securityKey);
                //配置cookie认证和jwt认证
                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                    {
    
                    })
                    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true,
                            ValidateAudience = true,
                            ValidateLifetime = true,
                            ClockSkew = TimeSpan.FromSeconds(30),
                            ValidateIssuerSigningKey = true,
                            ValidAudience = "localhost",
                            ValidIssuer = "localhost",
                            IssuerSigningKey = securityKey
                        };
                    });
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
                app.UseStaticFiles();
    
                app.UseRouting();
                //使用认证中间件
                app.UseAuthentication();
                app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    1. 在appsettings.json中添加SecurityKey
      {
        "Logging": {
          "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
          }
        },
        "AllowedHosts": "*",
        "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
      }
      1. 测试代码:
        using System;
        using System.Collections.Generic;
        using System.IdentityModel.Tokens.Jwt;
        using System.Linq;
        using System.Security.Claims;
        using System.Threading.Tasks;
        using Microsoft.AspNetCore.Authentication;
        using Microsoft.AspNetCore.Authentication.Cookies;
        using Microsoft.AspNetCore.Authentication.JwtBearer;
        using Microsoft.AspNetCore.Authorization;
        using Microsoft.AspNetCore.Mvc;
        using Microsoft.IdentityModel.Tokens;
        
        namespace JwtDemo.Controllers
        {
            public class AccountController : Controller
            {
                public async Task<string> Login()
                {
                    return await Task.FromResult("请先登录");
                }
                //使用cookie登录才能看到内容
                [Authorize]
                public IActionResult Content1()
                {
                    return Content("只有登录的人才能看到");
                }
                
                //使用cookie认证才能看到内容
                [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
                public IActionResult Content2()
                {
                    return Content("只有登录的人才能看到");
                }
        
                // cookie和jwt认证
                [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme+","+CookieAuthenticationDefaults.AuthenticationScheme)]
                public IActionResult Content3()
                {
                    return Content("只有登录的人才能看到");
                }
                
                // cookie登录
                public async Task<IActionResult> CookieLogin(string userName, string password)
                {
                    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    identity.AddClaim(new Claim("Name", userName));
                    await this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
                    return Content("登录"); 
                }
        
                /// <summary>
                /// token登录
                /// </summary>
                /// <param name="securityKey"></param>
                /// <param name="userName"></param>
                /// <returns></returns>
                public IActionResult JwtLogin([FromServices]SymmetricSecurityKey securityKey,string userName)
                {
                    List<Claim> claims = new List<Claim>();
                    claims.Add(new Claim("Name", userName));
                    var creds = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
                    var token = new JwtSecurityToken(
                        issuer: "localhost",
                        audience: "localhost",
                        claims:claims,
                        expires:DateTime.Now.AddMinutes(30),
                        signingCredentials:creds
                        );
                    var t = new JwtSecurityTokenHandler().WriteToken(token);
                    var result = User.Identity.IsAuthenticated;
                    return Content(t + "----" + result.ToString());
                }
        
            }
        }
      来自:https://blog.csdn.net/xingkongtianyuzhao/article/details/107893268
原文地址:https://www.cnblogs.com/djd66/p/15659850.html