ASP.NET Core快速入门(第5章:认证与授权)--学习笔记

2023-11-08

课程链接:http://video.jessetalk.cn/course/explore

良心课程,大家一起来学习哈!

任务31:课时介绍

  • 1.Cookie-based认证与授权
  • 2.Cookie-based认证实现
  • 3.Jwt认证与授权介绍
  • 4.Jwt认证与授权实现
  • 5.Jwt认证与授权
  • 6.Role based授权
  • 7.Claims-based授权

任务32:Cookie-based认证介绍

1412316-20191001014457039-1792976912.jpg

任务34:Cookie-based认证实现

dotnet new mvc --name MvcCookieAuthSample

在Controllers文件夹新增AdminController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MvcCookieAuthSample.Models;

namespace MvcCookieAuthSample.Controllers
{
    public class AdminController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

在Views文件夹新增Admin文件夹,在Admin文件夹新增Index.cshtml

@{
    ViewData["Title"] = "Admin";
}
<h2>@ViewData["Title"]</h2>

<p>Admin Page</p>

启动项目,浏览器访问https://localhost:5001/Admin

1412316-20191001014509218-1684426084.jpg

实际情况不应该直接让用户访问到Admin页面,所以应当跳转到登陆界面

AdminController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MvcCookieAuthSample.Models;
// 添加引用
using Microsoft.AspNetCore.Authorization;

namespace MvcCookieAuthSample.Controllers
{
    public class AdminController : Controller
    {
        [Authorize]
        public IActionResult Index()
        {
            return View();
        }
    }
}

startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
// 添加引用
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.Cookies;

namespace MvcCookieAuthSample
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            // Addmvc之前AddAuthentication,AddCookie
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // 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.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

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

再次访问https://localhost:5001/Admin,跳转到登陆界面https://localhost:5001/Account/Login?ReturnUrl=%2FAdmin

1412316-20191001014521177-419352918.jpg

在Controllers文件夹新增AccountController.cs


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MvcCookieAuthSample.Models;
// 添加引用
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;

namespace MvcCookieAuthSample.Controllers
{
    [Authorize]
    public class AccountController : Controller
    {
        public IActionResult MakeLogin()
        {
            var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.Name,"Mingson"),
                new Claim(ClaimTypes.Role,"admin")
            };

            var claimIdentity = new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);

            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimIdentity));
            
            return Ok();
        }

        public IActionResult Logout()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            
            return Ok();
        }
    }
}

启动项目

登出:localhost:5000/account/logout
访问admin:localhost:5000/admin,跳转到account/login
登陆:localhost:5000/account/makelogin
再次访问admin:localhost:5000/admin,登陆成功访问admin

任务35:JWT 认证授权介绍

1412316-20191001014532906-1908588066.jpg

可在官网解密:https://jwt.io

1412316-20191001014547047-2082649638.jpg

任务36:应用Jwtbearer Authentication

dotnet new webapi --name JwtAuthSample
dotnet watch run

打开postman调用
http://localhost:5000/api/values

1412316-20191002172004962-879288043.png

ValuesController.cs

// 添加引用
using Microsoft.AspNetCore.Authorization;

    // 添加特性
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase

新增一个Models文件夹,在文件夹中新增JwtSettings.cs

namespace JwtAuthSample
{
    public class JwtSettings
    {
        // token颁发者
        public string Issure{get;set;}
        // token使用的客户端
        public string Audience{get;set;}
        // 加密Key
        public string SecretKey="hellokey";
    }
}

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "JwtSettings":{
    "Audience":"http://localhost:5000",
    "Issuer":"http://localhost:5000",
    "SecretKey":"Hello-key"
  }
}

Startup.cs

// 添加引用
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

            // 添加在services.AddMvc()之前
            services.Configure<JwtSettings>(Configuration);
            var JwtSettings = new JwtSettings();
            Configuration.Bind("JwtSettings",JwtSettings);
            // 认证MiddleWare配置
            services.AddAuthentication(options=>{
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            // Jwt配置
            .AddJwtBearer(o=>{
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
                    ValidIssuer = JwtSettings.Issure,
                    ValidAudience = JwtSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSettings.SecretKey))// 对称加密
                };
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            app.UseHttpsRedirection();
            // 添加在app.UseMvc()之前
            app.UseAuthentication();
dotnet watch run

postman调用
http://localhost:5000/api/values
返回401,未授权

1412316-20191002172016580-241379177.png

任务37:生成 JWT Token

新建文件夹ViewModels,在文件夹中新建LoginViewModel.cs

using System.ComponentModel.DataAnnotations;

namespace JwtAuthSample
{
    public class LoginViewModel
    {
        [Required]
        public string User{get;set;}
        [Required]
        public string Password{get;set;}
    }
}

AuthorizeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// 添加引用
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Options;
using System.Text;
using System.IdentityModel.Tokens.Jwt;

namespace JwtAuthSample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorizeController : ControllerBase
    {
        private JwtSettings _jwtSettings;

        public AuthorizeController(IOptions<JwtSettings> _jwtSettingsAccesser)
        {
            _jwtSettings = _jwtSettingsAccesser.Value;
        }

        public IActionResult Token(LoginViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                if (!(viewModel.User == "mingson" && viewModel.Password == "123456"))
                {
                    return BadRequest();
                }

                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, "mingson"),
                    new Claim(ClaimTypes.Role, "admin")
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));// 对称加密算法
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                // VSCode安装扩展NuGet Package Manager
                // ctrl + shift + p
                // NuGet Package Manager:Add Pcakage
                // Microsoft.AspNetCore.Authentication.JwtBearer
                // 需要FQ才能添加
                // 2.0.0
                // 安装到csproj
                // 安装成功后csproj中出现<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.0.0" />
                // dotnet restore

                var token = new JwtSecurityToken(
                    _jwtSettings.Issure,
                    _jwtSettings.Audience,
                    claims,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    creds);

                return Ok(new {token = new JwtSecurityTokenHandler().WriteToken(token)});
            }

            return BadRequest();
        }
    }
}

Startup.cs

            // 添加在services.AddMvc()之前
            //services.Configure<JwtSettings>(Configuration);// 获取不到JwtSettings配置
            services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));// 获取appsettings.json中的配置

appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "JwtSettings":{
    "Audience":"http://localhost:5000",
    "Issuer":"http://localhost:5000",
    "SecretKey长度必须大于128bit=16字符":"",
    "SecretKey":"Hello-key.jessetalk"
  }
}
dotnet watch run

postman调用
http://localhost:5000/Authorize/Token
返回Token

1412316-20191002172310137-1650066765.jpg

加上token调用
http://localhost:5000/api/values

1412316-20191002172339742-33389572.jpg

1412316-20191002172058861-1172042339.jpg

token可在官网解密:https://jwt.io

输入正确的SecretKey:Hello-key.jessetalk

1412316-20191002172109311-1481864615.jpg

任务38:JWT 设计解析及定制

新建文件MyTokenValidator.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
// 添加引用
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

namespace JwtAuthSample
{
    public class MyTokenValidator : ISecurityTokenValidator
    {
        bool ISecurityTokenValidator.CanValidateToken => true;

        int ISecurityTokenValidator.MaximumTokenSizeInBytes { get;set; }

        bool ISecurityTokenValidator.CanReadToken(string securityToken)
        {
            return true;
        }

        ClaimsPrincipal ISecurityTokenValidator.ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken = null;
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);

            if (securityToken == "abcdefg")
            {
                identity.AddClaim(new Claim("name", "mingson"));
                identity.AddClaim(new Claim("SuperAdminOnly", "true"));
                identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, "user"));
            }

            var principal = new ClaimsPrincipal(identity);

            return principal;
        }
    }
}

Startup.cs

            // 认证MiddleWare配置
            services.AddAuthentication(options=>{
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            // Jwt配置
            .AddJwtBearer(o=>{
                // o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
                //     ValidIssuer = JwtSettings.Issure,
                //     ValidAudience = JwtSettings.Audience,
                //     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSettings.SecretKey))// 对称加密
                // };

                // 修改token来源
                o.SecurityTokenValidators.Clear();// 一个包含验证的数组,先清除
                o.SecurityTokenValidators.Add(new MyTokenValidator());

                // 修改token验证方式
                o.Events = new JwtBearerEvents(){
                  OnMessageReceived = context => {
                      var token = context.Request.Headers["mytoken"];
                      context.Token = token.FirstOrDefault();
                      return Task.CompletedTask;
                  }  
                };
            });
            
            services.AddAuthorization(Options=>{
                Options.AddPolicy("SuperAdminOnly", policy => policy.RequireClaim("SuperAdminOnly"));
            });

AuthorizeController.cs

                // var claims = new Claim[]
                // {
                //     new Claim(ClaimTypes.Name, "mingson"),
                //     new Claim(ClaimTypes.Role, "admin")
                // };
                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, "mingson"),
                    new Claim(ClaimTypes.Role, "user"),
                    new Claim("SuperAdminOnly", "true")
                };

ValuesController.cs

// [Authorize]// 添加标签
    [Authorize(Policy="SuperAdminOnly")]
dotnet run

输入一个错误的mytoken,返回403 Forbidden,禁止访问

1412316-20191004002651315-1627239655.png

输入一个正确的mytoken,返回200 OK

1412316-20191004002700381-76840959.jpg

任务39:Role以及Claims授权

Role授权

AuthorizeController.cs

                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, "mingson"),
                    new Claim(ClaimTypes.Role, "admin")
                };

ValuesController.cs

    [Authorize(Roles="user")]
dotnet run

带着token访问,返回403 Forbidden,禁止访问

AuthorizeController.cs修改为user,可访问

                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, "mingson"),
                    new Claim(ClaimTypes.Role, "user")
                };

Claims授权

Startup.cs

            // 认证MiddleWare配置
            services.AddAuthentication(options=>{
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            // Jwt配置
            .AddJwtBearer(o=>{
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
                    ValidIssuer = JwtSettings.Issure,
                    ValidAudience = JwtSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSettings.SecretKey))// 对称加密
                };
            });

            services.AddAuthorization(Options=>{
                Options.AddPolicy("SuperAdminOnly", policy => policy.RequireClaim("SuperAdminOnly"));
            });

ValuesController.cs

    [Authorize(Policy="SuperAdminOnly")]

AuthorizeController.cs

                var claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, "mingson"),
                    new Claim(ClaimTypes.Role, "user"),
                    new Claim("SuperAdminOnly", "true")
                };
dotnet run

带着token访问,返回200 Ok

知识共享许可协议

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。

如有任何疑问,请与我联系 (MingsonZheng@outlook.com) 。

转载于:https://www.cnblogs.com/MingsonZheng/p/11614686.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET Core快速入门(第5章:认证与授权)--学习笔记 的相关文章

  • 我可以使用 javascript 生成 JSON 文件吗?

    我想在域 example1 com 上创建一个页面 并获取 解析另一个域 example2 com json json 上的 JSON 文件 可以使用 javascript 生成 json 文件 在 example2 com 上 吗 我认为
  • 将 pandas DataFrame 写入 unicode 中的 JSON

    我正在尝试将包含 unicode 的 pandas DataFrame 写入 json 但是内置的 to json函数对字符进行转义 我该如何解决 Example import pandas as pd df pd DataFrame a
  • 反序列化 HTTP POST 参数

    我正在尝试找到一种更原生或更优雅的解决方案 用于将 HTTP POST 参数反序列化为相应的对象 目前 我将字符串转换为字典 然后将其序列化为 JSON 然后将其反序列化为我的最终对象 参数字符串示例 TotalCost 0 01200 D
  • 使用 JSONDecoder 解码的对象的打印输出出现问题

    我正在尝试快速解码 JSON 字符串 但在解码后访问属性时遇到一些奇怪的问题 这是我从本地存储的 JSON 文件检索的 JSON 文件的内容 word a usage partOfSpeech determiner 这是访问 JSON 文件
  • 为什么 Twitter API 返回错误的推文 ID?

    我使用 Twitter API 来检索用户主页时间线推文 我使用 json 响应格式 最近推文 ID 在 API 中只是 id 被重新调整错误 举个例子 通常它应该像这样返回 id 14057503720 示例来自twitter控制台 但是
  • 如何通过文本搜索返回 JSON 数组中项目的索引位置?

    这是我的 JSON 数组 var planets Name Mercury Temperature 427 C Position 1 Name Venus Temperature 462 C Position 2 Name Earth Te
  • Spring boot 404错误自定义错误响应ReST

    我正在使用 Spring boot 来托管 REST API 即使浏览器正在访问 URL 以及自定义数据结构 我也希望始终发送 JSON 响应 而不是使用标准错误响应 我可以使用 ControllerAdvice 和 ExceptionHa
  • go json marshal 的默认大小写选项?

    我有以下结构要导出为 json type ExportedIncident struct Title string json title Host string json host Status string json status Dat
  • shell解析json并循环输出组合变量

    杰斯克喜欢我之前的话题 https stackoverflow com questions 74063588 shell parsing json contains spaces in string 我知道如何解析带有空格的简单 json
  • 如何将带有自定义标头的任意 JSON 数据发送到 REST 服务器?

    TL DR 如何将 JSON 字符串发送到带有 auth 标头的 REST 主机 我尝试了 3 种不同的方法 发现一种适用于匿名类型 为什么我不能使用匿名类型 我需要设置一个名为 Group Name 的变量 并且连字符不是有效的 C 标识
  • 从 React.js 中的 json 文件获取数据

    我有一个 json 文件调用 data json 例如 我使用 React js id 1 title Child Bride id 2 title Last Time I Committed Suicide The id 3 title
  • 如何通过 JSON / JS 在 Jenkins 中添加 CSRF 面包屑

    我想在 Jenkins 中通过 API 创建作业 但无法连接 Jenkins 中的 CSRF 保护课程 我得到了一个面包屑 但不知道如何将其附加到 JSON 或 JavaScript 中的 url 请求 以通过 POST 方法获取数据传递
  • Google AJAX API - 如何获得 4 个以上结果?

    我使用下面的 google API ajax 来获取特定搜索词的图像 这是在一个WinForms app 下面的链接似乎有效 但它只返回 4 个结果 通过 JSON 有谁知道如何哄得更多吗 显然必须有另一个参数来请求更多或分页结果 但我似乎
  • 如何在 JsonNode 中创建插入新节点?

    我创建了一个新的 JsonNode JsonNode jNode new ObjectCodec createObjectNode 有了这个节点 我如何在其中添加键值对 以便我可以使用新值构造这个新节点 我读到的内容http www cow
  • 来自不同级别的一对值根据邻居成员选择一个

    我正在尝试使用 jq 遍历对象数组并将其转换为 csv 我可以做一些选择和 csv 部分 但我正在努力解决的是如何获得Name每个对象的标签值 json 看起来像这样 Groups Instances InstanceType m5 xla
  • 使用 JSONKit 解析 JSON 文件

    我正在构建一个音叉应用程序 货叉应允许最多 12 个预设节距 此外 我希望允许用户选择一个主题 每个主题都会加载一组预设 不必使用所有预设 我的配置文件看起来像这样 theme A3 comment An octave below conc
  • 使用 Ajax Jquery post 请求进行 Json 劫持

    昨天 我读了一些关于如何预防的好文章使用 Asp Net MVC 进行 Json 劫持 http haacked com archive 2009 06 24 json hijacking aspx 规则是 永远不要通过 get 请求发送
  • Javascript 将对象推送为克隆

    我将 d3 用于交互式网络应用程序 我需要绑定的数据在交互过程中发生变化 并且由 JSON 变量中的一些选定对象组成 为此 我在 JSON 变量上使用了映射 并进行了一些查询来选择适当的对象 对象被推送到列表中 并且该列表被绑定为新数据 我
  • 使用 Rails 中的 postgres json 字段更新嵌套键

    我一直在尝试更新以下内容 boxes book 2 moving 2 goods to boxes book new 2 moving 2 goods 无需使用正则表达式或在 ruby 中执行此操作 但似乎有点棘手 我想添加新密钥 然后删除
  • mysql_query 保留返回时在表中创建的数据类型?

    我在mysql中有一个表 CREATE TABLE user id INT name VARCHAR 250 我查询表 result mysql query SELECT id name FROM user 我收集结果 while row

随机推荐