zoukankan      html  css  js  c++  java
  • 身份验证

       

    AddAuthentication 认证

    AddAuthorization 授权

    一、Cookie认证

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();
    
                //启动身份验证中间件
                services.AddAuthentication(options =>
                {
                    //默认身份验证方案,CookieAuthenticationDefaults.AuthenticationScheme就是个常量字符创=Cookies
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    //
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                }).AddCookie("Cookies", options =>
                {
                    //访问一个开启了[Authorize]的api,如果没有被认证会跳到login界面
                    options.LoginPath = new PathString("/home/login");
                    //
                    //options.Cookie.Name = "meng";
                    // cookie 30秒后过期
                    options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
                }
                );
            }
    
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
    
                app.UseRouting();
                app.UseAuthentication();
                app.UseAuthorization();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
    [ApiController]
        [Route("[controller]")]
        public class HomeController : Controller
        {
            public  IActionResult Index()
            {
                var identity = new ClaimsIdentity(null, CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);
                HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
                return Content("已给客户端授权");
            }
    
            [HttpGet("login")]
            public IActionResult login()
            {
                return Content("请先登录");
            }
    
            //注销cookie
            [HttpGet("signout")]
            public IActionResult signout()
            {
                HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                return Content("注销");
            }
    
            [HttpGet("Auth")]
            [Authorize] //开启验证
    
            public IActionResult Auth()
            {
                var request = HttpContext.Request;
                //var usr = HttpContext.User;
                return Content("验证成功");
            }
        }

    二、JWT

     Microsoft.AspNetCore.Authentication.JwtBearer

    1.JWT令牌结构

    (1)Header 头

    头部承载了两个信息

    声明类型,对于Jwt来说就是jwt

    加密算法,通常使用SHA256,HS256

    {
      'typ': 'JWT',
      'alg': 'HS256'
    }

    (2)Payload 有效载荷

    标准中注册的声明

    iss: jwt签发者

    sub: jwt所面向的用户

    aud: 接收jwt的一方

    exp: jwt的过期时间,这个过期时间必须要大于签发时间

    nbf: 定义在什么时间之前,该jwt都是不可用的.

    iat: jwt的签发时间

    jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击

    公共的声明

    公共的声明可以添加任何的信息,一般添加用户的相关信息或其他业务需要的必要息。但不建议添加敏感信息,因为该部分在客户端可解密

    私有的声明

    私有声明是提供者和消费者所共同定义的声明,一般不建议存放敏感信息,因为base64是对称解密的,意味着该部分信息可以归类为明文信息

    Header和Payload都是基于base64加密的,这种密文都是可以对称解密的,因此请不要存放敏感信息

    (3)Signature 签名

     Signature 部分是对前两部分的签名,防止数据篡改

    2.代码

    Startup中

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers();
    
                //启动身份验证中间件
                services.AddAuthentication(options =>
                {
                    //Bearer
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    //
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                }
                ).AddJwtBearer(options =>
                {
                    //jwt token参数设置
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        //Token颁发机构
                        ValidIssuer = "jwtIssuertest",
                        //颁发给谁
                        ValidAudience = "jwtAudiencetest",
                        //这里的key要进行加密
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("d0ecd23c-dfdb-4005-a2ea-0fea210c858a")),
                    };
                });
            }

    HomeController中

            public IActionResult Index()
            {
    
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, "Tom"),
    
                };
    
                //创建令牌
                var token = new JwtSecurityToken(
                  issuer: "jwtIssuertest",
                  audience: "jwtAudiencetest",
                  notBefore: DateTime.Now,
                  expires: DateTime.Now.AddSeconds(30),
                  claims: claims,
                  signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("d0ecd23c-dfdb-4005-a2ea-0fea210c858a")), SecurityAlgorithms.HmacSha256)
                );
                string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return Content(jwtToken);
            }
  • 相关阅读:
    图像,script,link 空地址带来的困惑
    localStorage变更事件当前页响应新解-awen
    opencv在ios上的开发教程
    torch-ios框架XCODE使用备忘
    重拾老本行_图像处理
    dialogic d300语音卡驱动重装后启动报错问题解决方法
    Winpcap构建用户级网桥
    winpcap usb山寨网卡识别
    最近这段时间
    银行IT入门深似海
  • 原文地址:https://www.cnblogs.com/buchizaodian/p/12992337.html
Copyright © 2011-2022 走看看