zoukankan      html  css  js  c++  java
  • Asp.Net Core安全之认证与授权

    1、认证 VS 授权

    • 认证是一个识别用户是谁的过程
    • 授权是一个决定用户可以干什么的过程
    • 401 Unauthorized 代表:未授权
    • 403 Forbidden 代表:禁止访问

    2、ASP .NET Core 认证授权中间件

    在接收到请求之后,认证(Authentication)和授权(Authorization) 发生在 路由(Routing) 和 终结点(Endpoint) 之间

    3、代码实现

    以JWT为例,在Startup.cs 中配置添加服务

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(
            options => options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true, // 是否验证 Issuer
                ValidateAudience = true, // 是否验证 Audience
                ValidateLifetime = true, // 是否验证失效时间
                ClockSkew = TimeSpan.FromSeconds(30),
                ValidateIssuerSigningKey = true, // 是否验证 SecurityKey
                ValidAudience = "https://localhost:6001",
                ValidIssuer = "https://localhost:6001",
                IssuerSigningKey =
                    new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret88secret666")) // 拿到 SecurityKey
            });
    

    Configure 配置

    app.UseAuthentication();
    app.UseAuthorization();

     添加标签 [Authorize]

    [Authorize(Roles = "Administrators, Mentor")]
    public class ProjectController : ControllerBase

    JWT版发Token

    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret88secret666"));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
    
    var token = new JwtSecurityToken(
                    issuer: "https://localhost:6001",
                    audience: "https://localhost:6001",
                    new List<Claim> {new Claim("name", "mingson")},
                    expires: DateTime.Now.AddMinutes(120),
                    signingCredentials: credentials);
    
    return Ok(new JwtSecurityTokenHandler().WriteToken(token));
  • 相关阅读:
    一千亿亿亿字节
    分布式发布订阅消息系统
    Google Chrome 的内核引擎 WebKit 介绍
    找项目网站C# 下写入视频的简单实现
    学ios开发:Delegate,Action Sheet, Alert
    Web服务器
    Google Chrome Source Code 源码下载
    大数据处理的趋势五种开源技术介绍
    MDA项目思路小结
    重新发布本人所有博客文章中涉及的代码与工具(大部分是C++和Java)
  • 原文地址:https://www.cnblogs.com/duyao/p/14610710.html
Copyright © 2011-2022 走看看