();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/PDFDemo/Properties/PublishProfiles/FolderProfile.pubxml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 | False
8 | False
9 | True
10 | Release
11 | Any CPU
12 | FileSystem
13 | bin\Release\netcoreapp3.1\publish\
14 | FileSystem
15 |
16 |
--------------------------------------------------------------------------------
/PDFDemo/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:51402",
8 | "sslPort": 0
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "weatherforecast",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "PDFDemo": {
21 | "commandName": "Project",
22 | "launchBrowser": true,
23 | "launchUrl": "weatherforecast",
24 | "applicationUrl": "http://localhost:5000",
25 | "environmentVariables": {
26 | "ASPNETCORE_ENVIRONMENT": "Development"
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/PDFDemo/Rotativa/Linux/libwkhtmltox.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyq025/DotNetCoreStudyDemo/8ca9932e1cbb86ce33b982d10c914b8049436850/PDFDemo/Rotativa/Linux/libwkhtmltox.so
--------------------------------------------------------------------------------
/PDFDemo/Rotativa/Linux/wkhtmltopdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyq025/DotNetCoreStudyDemo/8ca9932e1cbb86ce33b982d10c914b8049436850/PDFDemo/Rotativa/Linux/wkhtmltopdf
--------------------------------------------------------------------------------
/PDFDemo/Rotativa/Mac/wkhtmltopdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyq025/DotNetCoreStudyDemo/8ca9932e1cbb86ce33b982d10c914b8049436850/PDFDemo/Rotativa/Mac/wkhtmltopdf
--------------------------------------------------------------------------------
/PDFDemo/Rotativa/Windows/wkhtmltopdf.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyq025/DotNetCoreStudyDemo/8ca9932e1cbb86ce33b982d10c914b8049436850/PDFDemo/Rotativa/Windows/wkhtmltopdf.exe
--------------------------------------------------------------------------------
/PDFDemo/Startup.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zyq025/DotNetCoreStudyDemo/8ca9932e1cbb86ce33b982d10c914b8049436850/PDFDemo/Startup.cs
--------------------------------------------------------------------------------
/PDFDemo/Views/Zoe.cshtml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Zoe
8 |
9 |
10 | Zoe 好酷!!!!
11 | 关注 Code综艺圈 一块学呀,来来来
12 |
13 |
14 |
--------------------------------------------------------------------------------
/PDFDemo/Views/ZoeData.cshtml:
--------------------------------------------------------------------------------
1 | @model PDFDemo.Models.Zoe
2 |
3 |
4 |
5 |
6 |
7 | Zoe
8 |
9 |
10 | @Model.Name
11 | 关注 @Model.WeiXin 一块学呀,来来来
12 |
13 |
14 |
--------------------------------------------------------------------------------
/PDFDemo/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace PDFDemo
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/PDFDemo/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/PDFDemo/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DotNetCoreStudyDemo
2 | Code综艺圈涉及相关学习Demo
3 |
4 | SwaggerDemo项目包含Jwt相关代码
5 |
--------------------------------------------------------------------------------
/SwaggerDemo/Controllers/ProductController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Authorization;
6 | using Microsoft.AspNetCore.Http;
7 | using Microsoft.AspNetCore.Mvc;
8 |
9 | namespace SwaggerDemo.Controllers
10 | {
11 | [Route("api/[controller]")]
12 | [ApiController]
13 | [Authorize]
14 | [AllowAnonymous]
15 | public class ProductController : ControllerBase
16 | {
17 |
18 | ///
19 | /// 管理员配置产品相关信息
20 | ///
21 | [HttpPost("AdminConfigProductData")]
22 | //[Authorize(Roles ="Admin")]
23 | //[Authorize(Policy = "AdminPolicy")]
24 | [Authorize(Policy = "Permission")]
25 | public ActionResult AdminConfigProductData()
26 | {
27 | return Ok("管理员配置产品信息");
28 | }
29 |
30 | ///
31 | /// 维护员提交产品维护记录信息
32 | ///
33 | [HttpPost("MaintainProductInfo")]
34 | //[Authorize(Roles = "Maintain")]
35 | //[Authorize(Policy = "AdminAndMaintainPolicy")]
36 | [Authorize(Policy = "Permission")]
37 | public ActionResult MaintainProductInfo()
38 | {
39 | return Ok("维护员提交产品维护记录信息");
40 | }
41 |
42 | ///
43 | /// 用户访问产品信息
44 | ///
45 | [HttpPost("UserProductInfo")]
46 | //[Authorize(Roles = "User")]
47 | //[Authorize(Policy = "AdminAndMaintainPolicy")]
48 | [Authorize(Policy = "Permission")]
49 | public ActionResult UserProductInfo()
50 | {
51 | return Ok("用户访问产品信息");
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/SwaggerDemo/Controllers/UserController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IdentityModel.Tokens.Jwt;
4 | using System.Linq;
5 | using System.Security.Claims;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 | using Microsoft.AspNetCore.Authorization;
9 | using Microsoft.AspNetCore.Http;
10 | using Microsoft.AspNetCore.Mvc;
11 | using Microsoft.IdentityModel.Tokens;
12 | using SwaggerDemo.Permission;
13 | using TestSwaggerModel;
14 |
15 | namespace SwaggerDemo.Controllers
16 | {
17 | ///
18 | /// 用户API
19 | ///
20 | [Route("api/[controller]")]
21 | [ApiController]
22 | public class UserController : ControllerBase
23 | {
24 |
25 | //通过构造函数注入 PermissionRequirement,注册的时候用的是单例模式
26 | private PermissionRequirement _permissionRequirement;
27 | public UserController(PermissionRequirement permissionRequirement)
28 | {
29 | _permissionRequirement = permissionRequirement;
30 | }
31 |
32 | ///
33 | /// 登录Api,传入用户名和密码
34 | ///
35 | [HttpPost("Login")]
36 | public ActionResult Login(UserConditon userConditon)
37 | {
38 | // 返回用户信息,模拟从数据库中查询用户得到用户信息
39 | if(userConditon==null||userConditon.UserName!="Code综艺圈"||userConditon.Pwd!="Zoe")
40 | {
41 | return Ok("登录失败~~~");
42 | }
43 | // 这里可以根据需要将其权限放在Redis中,每次登陆时都重新存,即登陆获取最新权限
44 | // 这里模拟通过userId从数据库中获取分配的接口权限信息,这里存在内存中
45 | _permissionRequirement.Permissions = new List {
46 | new PermissionData{ UserId="Zoe1111",Url="/api/Product/AdminConfigProductData" },
47 | //new PermissionData{ UserId="Zoe1111",Url="/api/Product/MaintainProductInfo" },
48 | new PermissionData{ UserId="Zoe1111",Url="/api/Product/UserProductInfo" }
49 | };
50 | // 生成Token并返回
51 | string token = GenerateToke("Zoe1111", "Code综艺圈");
52 | return Ok(token);
53 | }
54 | private string GenerateToke(string userId, string userName)
55 | {
56 | // 秘钥,这是生成Token需要秘钥,就是理论提及到签名那块的秘钥
57 | string secret = "TestSecretTestSecretTestSecretTestSecret";
58 | // 签发者,是由谁颁发的
59 | string issuer = "TestIssuer";
60 | // 接受者,是给谁用的
61 | string audience = "TestAudience";
62 | // 指定秘钥
63 | var securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret));
64 | // 签名凭据,指定对应的签名算法,结合理论那块看哦~~~
65 | var sigingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
66 | // 自定义payload信息,每一个claim代表一个属性键值对,就类似身份证上的姓名,出生年月一样
67 | var claims = new Claim[] { new Claim("userId", userId),
68 | new Claim("userName", userName),
69 | // claims中添加角色属性,这里的键一定要用微软封装好的ClaimTypes.Role
70 | new Claim(ClaimTypes.Role,"Admin"),
71 | new Claim(ClaimTypes.Role,"Maintain")
72 | };
73 |
74 | // 组装生成Token的数据
75 | SecurityToken securityToken = new JwtSecurityToken(
76 | issuer: issuer,// 颁发者
77 | audience: audience,// 接受者
78 | claims: claims,//自定义的payload信息
79 | signingCredentials: sigingCredentials,// 凭据
80 | expires: DateTime.Now.AddMinutes(30) // 设置超时时间,30分钟之后过期
81 | );
82 | // 生成Token
83 | return new JwtSecurityTokenHandler().WriteToken(securityToken);
84 | }
85 |
86 | ///
87 | /// 获取用户信息
88 | ///
89 | [HttpPost("GetUserInfo")]
90 | [Authorize]
91 | public ActionResult GetUserInfo()
92 | {
93 | return Ok("获取用户信息成功");
94 | }
95 | ///
96 | /// 测试接口
97 | ///
98 | [HttpPost("TestNoAuth")]
99 | public ActionResult TestNoAuth()
100 | {
101 | return Content("不需要认证就能访问");
102 | }
103 |
104 |
105 |
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/SwaggerDemo/Controllers/WeatherForecastController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Mvc;
6 | using Microsoft.Extensions.Logging;
7 |
8 | namespace SwaggerDemo.Controllers
9 | {
10 | [ApiController]
11 | [Route("[controller]")]
12 | public class WeatherForecastController : ControllerBase
13 | {
14 | private static readonly string[] Summaries = new[]
15 | {
16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
17 | };
18 |
19 | private readonly ILogger _logger;
20 |
21 | public WeatherForecastController(ILogger logger)
22 | {
23 | _logger = logger;
24 | }
25 |
26 | [HttpGet]
27 | public IEnumerable Get()
28 | {
29 | var rng = new Random();
30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast
31 | {
32 | Date = DateTime.Now.AddDays(index),
33 | TemperatureC = rng.Next(-20, 55),
34 | Summary = Summaries[rng.Next(Summaries.Length)]
35 | })
36 | .ToArray();
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/SwaggerDemo/Permission/PermissionHandler.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication;
2 | using Microsoft.AspNetCore.Authorization;
3 | using Microsoft.AspNetCore.Http;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace SwaggerDemo.Permission
10 | {
11 | ///
12 | /// 权限处理的关键类
13 | ///
14 | public class PermissionHandler : AuthorizationHandler
15 | {
16 | ///
17 | /// 通过IHttpContextAccessor可以获取HttpContext相关信息,但一定要注册服务
18 | ///
19 | private readonly IHttpContextAccessor _accessor;
20 | ///
21 | /// 用于判断请求是否带有凭据和是否登录
22 | ///
23 | public IAuthenticationSchemeProvider Scheme { get; set; }
24 | ///
25 | /// 构造函数注入
26 | ///
27 | public PermissionHandler(IHttpContextAccessor accessor,IAuthenticationSchemeProvider scheme)
28 | {
29 | this._accessor = accessor;
30 | Scheme = scheme;
31 | }
32 | protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
33 | {
34 | try
35 | {
36 | //拿到HttpContext就无所不能啦
37 | var httpContext = _accessor.HttpContext;
38 | //判断资源数据中权限列表中是否有权限
39 | if (!requirement.Permissions.Any())
40 | {
41 | //没有直接返回无权限,也可以重新获取权限,实现不退出重新登录就可获取最新权限
42 | context.Fail();
43 | }
44 | //判读请求是否拥有凭据,即是否登录
45 | var defaultAuthenticate = await Scheme.GetDefaultAuthenticateSchemeAsync();
46 | if (defaultAuthenticate == null)
47 | {
48 | context.Fail();
49 | }
50 | var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);
51 | //不为空代表登录成功,为空登录失败
52 | if (result?.Principal != null)
53 | {
54 | // 获取生成Token时放在payload里的userId
55 | string userId = _accessor.HttpContext.User.FindFirst("userId").Value;
56 | // 获取当前请求的地址
57 | string requestUrl = httpContext.Request.Path.Value.ToLower();
58 | // 从权限表中查找当前用户是否有当前请求地址的权限
59 | var permission = requirement.Permissions.FirstOrDefault(a => a.Url.ToLower() == requestUrl && a.UserId == userId);
60 | // 如果没找到,代表没有权限
61 | if (permission == null)
62 | {
63 | context.Fail();
64 | }
65 | // 如果找到,就继续往下执行
66 | context.Succeed(requirement);
67 | }
68 | else
69 | {
70 | // 获取不到对应值就返回无权限
71 | context.Fail();
72 | }
73 | }
74 | catch (Exception ex)
75 | {
76 | context.Fail();
77 | }
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/SwaggerDemo/Permission/PermissionRequirement.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authorization;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Threading.Tasks;
6 |
7 | namespace SwaggerDemo.Permission
8 | {
9 | ///
10 | /// 资源数据的载体,可以根据需求自定义任何数据
11 | /// 需要实现IAuthorizationRequirement接口进行标识
12 | ///
13 | public class PermissionRequirement:IAuthorizationRequirement
14 | {
15 | ///
16 | /// 存放系统中所有权限
17 | ///
18 | public List Permissions { get; set; }
19 |
20 | }
21 |
22 | ///
23 | /// 定义了一个权限数据存储类,包含用户ID和对应的权限访问的Url地址
24 | ///
25 | public class PermissionData
26 | {
27 | ///
28 | /// 用户ID
29 | ///
30 | public string UserId { get; set; }
31 | ///
32 | /// 用户对应的 Url地址
33 | ///
34 | public string Url { get; set; }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/SwaggerDemo/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Hosting;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.Hosting;
8 | using Microsoft.Extensions.Logging;
9 |
10 | namespace SwaggerDemo
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/SwaggerDemo/Properties/PublishProfiles/FolderProfile.pubxml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 | False
8 | False
9 | True
10 | Release
11 | Any CPU
12 | FileSystem
13 | bin\Release\netcoreapp3.1\publish\
14 | FileSystem
15 |
16 |
--------------------------------------------------------------------------------
/SwaggerDemo/Properties/PublishProfiles/FolderProfile.pubxml.user:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 | <_PublishTargetUrl>H:\DotNetProject\SwaggerDemo\bin\Release\netcoreapp3.1\publish\
8 |
9 |
--------------------------------------------------------------------------------
/SwaggerDemo/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:62485",
8 | "sslPort": 0
9 | }
10 | },
11 | "profiles": {
12 | "IIS Express": {
13 | "commandName": "IISExpress",
14 | "launchBrowser": true,
15 | "launchUrl": "weatherforecast",
16 | "environmentVariables": {
17 | "ASPNETCORE_ENVIRONMENT": "Development"
18 | }
19 | },
20 | "SwaggerDemo": {
21 | "commandName": "Project",
22 | "launchBrowser": true,
23 | "launchUrl": "weatherforecast",
24 | "applicationUrl": "http://localhost:5000",
25 | "environmentVariables": {
26 | "ASPNETCORE_ENVIRONMENT": "Development"
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/SwaggerDemo/Startup.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using Microsoft.AspNetCore.Authorization;
8 | using Microsoft.AspNetCore.Builder;
9 | using Microsoft.AspNetCore.Hosting;
10 | using Microsoft.AspNetCore.Http;
11 | using Microsoft.AspNetCore.Mvc;
12 | using Microsoft.Extensions.Configuration;
13 | using Microsoft.Extensions.DependencyInjection;
14 | using Microsoft.Extensions.Hosting;
15 | using Microsoft.Extensions.Logging;
16 | using Microsoft.IdentityModel.Tokens;
17 | using Microsoft.OpenApi.Models;
18 | using SwaggerDemo.Permission;
19 | using Swashbuckle.AspNetCore.Filters;
20 |
21 | namespace SwaggerDemo
22 | {
23 | public class Startup
24 | {
25 | public Startup(IConfiguration configuration)
26 | {
27 | Configuration = configuration;
28 | }
29 |
30 | public IConfiguration Configuration { get; }
31 |
32 | // This method gets called by the runtime. Use this method to add services to the container.
33 | public void ConfigureServices(IServiceCollection services)
34 | {
35 | services.AddControllers();
36 | // 注册Swagger相关组件
37 | services.AddSwaggerGen(option =>
38 | {
39 | // 配置Swagger 文档信息,第一个参数很重要"TestSwagger",得和后续注册中间件一直
40 | option.SwaggerDoc("TestSwagger", new OpenApiInfo
41 | {
42 | // 文档版本
43 | Version = "TestSwagger-V1",
44 | // 标题
45 | Title = "TestSwagger 接口文档",
46 | // 描述
47 | Description = "这是TestSwagger文档,版本为V1",
48 | // 联系方式,地址和邮箱配置
49 | Contact = new OpenApiContact { Name = "TestSwagger-C", Email = "Test@xxx.com", Url = new Uri("https://www.cnblogs.com/zoe-zyq/") },
50 | License = new OpenApiLicense { Name = "TestSwagger-L", Url = new Uri("https://www.cnblogs.com/zoe-zyq/") }
51 | });
52 | // 指定Action排序方式,这里是按Action相对路径进行排序
53 | option.OrderActionsBy(o => o.RelativePath);
54 |
55 | //设置注释提示,主要是指定xml文件路径,从xml中读取相关的信息
56 | var basePath = AppContext.BaseDirectory;
57 | // 配置API读取注释
58 | var apiXml = Path.Combine(basePath, "SwaggerDemo.xml");
59 | option.IncludeXmlComments(apiXml, true);
60 |
61 | // 配置Model读取注释
62 | var modelXml = Path.Combine(basePath, "TestSwaggerModel.xml");
63 | option.IncludeXmlComments(modelXml);
64 |
65 | #region Swagger扩展-增加输入Token即添加小锁功能,清楚看见接口是否安全
66 | // 方式1
67 | option.OperationFilter();
68 | option.OperationFilter();
69 | // 将Token放在请求头中传递到后台
70 | option.OperationFilter();
71 |
72 | // 指定名称必须为oauth2,因为SecurityRequirementsOperationFilter默认securitySchemaName指定为oauth2
73 | option.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
74 | {
75 | Description = "Jwt认证授权,在输入框中输入'Bearer token'(Bearer和token之间有一个空格)",
76 | Name = "Authorization",//设置参数名
77 | In = ParameterLocation.Header,//在请求头中添加名称Authorization
78 | Type = SecuritySchemeType.ApiKey,
79 | });
80 |
81 | //方式2
82 | //option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
83 | //{
84 | // Description = "Jwt认证授权",
85 | // Name = "Authorization",
86 | // In = ParameterLocation.Header,
87 | // Type = SecuritySchemeType.ApiKey,
88 | // BearerFormat = "JWT",
89 | // Scheme = "bearer"
90 | //});
91 | //option.AddSecurityRequirement(new OpenApiSecurityRequirement {
92 | // {
93 | // new OpenApiSecurityScheme{
94 | // Reference = new OpenApiReference
95 | // {
96 | // Type = ReferenceType.SecurityScheme,
97 | // Id="Bearer"
98 | // }
99 | // },
100 | // new List()
101 | // }
102 | //});
103 | #endregion
104 | });
105 |
106 | #region 集成JWT
107 | // 将公共的信息提取出来,这里可以放到配置文件中,统一读取;以下直接在程序中写死了
108 | // 秘钥,这是生成Token需要秘钥,就是理论提及到签名那块的秘钥
109 | string secret = "TestSecretTestSecretTestSecretTestSecret";
110 | // 签发者,是由谁颁发的
111 | string issuer = "TestIssuer";
112 | // 接受者,是给谁用的
113 | string audience = "TestAudience";
114 | // 注册服务,显示指定为Bearer
115 | services.AddAuthentication("Bearer")
116 | .AddJwtBearer(options =>
117 | {
118 | // 配置Jwt信息
119 | options.TokenValidationParameters = new TokenValidationParameters
120 | {
121 | // 是否验证秘钥
122 | ValidateIssuerSigningKey = true,
123 | // 指定秘钥
124 | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)),
125 |
126 | // 是否验证颁发者
127 | ValidateIssuer = true,
128 | // 指定颁发者
129 | ValidIssuer = issuer,
130 |
131 | // 是否验证接受者
132 | ValidateAudience = true,
133 | // 指定接受者
134 | ValidAudience = audience,
135 |
136 | // 设置必须要有超时时间
137 | RequireExpirationTime = true,
138 | // 设置必须验证超时
139 | ValidateLifetime = true,
140 |
141 | // 将其赋值为0时,即设置有效时间到期,就马上失效
142 | ClockSkew = TimeSpan.Zero
143 | };
144 | });
145 | #endregion
146 |
147 |
148 | var permissionRequirement = new PermissionRequirement
149 | {
150 | Permissions = new List()
151 | };
152 |
153 |
154 | //针对授权定义策略
155 | services.AddAuthorization(option =>
156 | {
157 | ////AminPolicy策略就是要求Admin角色才能访问接口
158 | //option.AddPolicy("AdminPolicy", p => p.RequireRole("Admin").Build());
159 | ////AdminOrMaintainPolicy策略只要有Admin或Maintain其中一个角色即可访问接口
160 | //option.AddPolicy("AdminOrMaintainPolicy", p => p.RequireRole("Admin", "Maintain").Build());
161 | ////AdminOrUserPolicy策略只要有Admin或User其中一个角色即可访问接口
162 | //option.AddPolicy("AdminOrUserPolicy", p => p.RequireRole("Admin", "User").Build());
163 |
164 | ////AdminAndMaintainPolicy策略必须要同时有Admin和Maintain两个个角色才能访问接口
165 | //option.AddPolicy("AdminAndMaintainPolicy", p => p.RequireRole("Admin").RequireRole("User").Build());
166 |
167 | // 同样是策略模式,只是基于Requirement进行权限验证,验证逻辑自己写
168 | option.AddPolicy("Permission", p => p.Requirements.Add(permissionRequirement));
169 | });
170 | // 将权限验证的关键类注册,Jwt的策略模式指定为Requirements时就会自动执行该类方法
171 | services.AddScoped();
172 | // 将permissionRequirement实例注册为单例模式,保证系统中就一个实例,方便权限数据共享
173 | services.AddSingleton(permissionRequirement);
174 | // 注册IHttpContextAccessor,后续可以通过它可以获取HttpContext,操作方便
175 | services.AddSingleton();
176 | }
177 |
178 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
179 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
180 | {
181 | if (env.IsDevelopment())
182 | {
183 | app.UseDeveloperExceptionPage();
184 | }
185 | // 注册Swagger中间件
186 | app.UseSwagger();
187 | // 注册Swagger界面中间件
188 | app.UseSwaggerUI(option =>
189 | {
190 | // 配置文档数据来源及名称设置,其中第一个参数中TestSwagger和注册组件时的名称一致
191 | option.SwaggerEndpoint($"/swagger/TestSwagger/swagger.json", "TestSwaggerCode");
192 | // 设置为空,代表根路径就可访问到Swagger的主页
193 | option.RoutePrefix = "";
194 | });
195 |
196 | app.UseRouting();
197 |
198 | app.UseAuthentication();
199 |
200 | app.UseAuthorization();
201 |
202 | app.UseEndpoints(endpoints =>
203 | {
204 | endpoints.MapControllers();
205 | });
206 | }
207 | }
208 | }
209 |
--------------------------------------------------------------------------------
/SwaggerDemo/SwaggerDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 |
7 |
8 | SwaggerDemo.xml
9 | 1701;1702;1591
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | Always
25 |
26 |
27 | Always
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/SwaggerDemo/SwaggerDemo.csproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ProjectDebugger
5 |
6 |
7 | SwaggerDemo
8 | ApiControllerEmptyScaffolder
9 | root/Controller
10 | FolderProfile
11 |
12 |
--------------------------------------------------------------------------------
/SwaggerDemo/SwaggerDemo.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | SwaggerDemo
5 |
6 |
7 |
8 |
9 | 管理员配置产品相关信息
10 |
11 |
12 |
13 |
14 | 维护员提交产品维护记录信息
15 |
16 |
17 |
18 |
19 | 用户访问产品信息
20 |
21 |
22 |
23 |
24 | 用户API
25 |
26 |
27 |
28 |
29 | 登录Api,传入用户名和密码
30 |
31 |
32 |
33 |
34 | 获取用户信息
35 |
36 |
37 |
38 |
39 | 测试接口
40 |
41 |
42 |
43 |
44 | 权限处理的关键类
45 |
46 |
47 |
48 |
49 | 通过IHttpContextAccessor可以获取HttpContext相关信息,但一定要注册服务
50 |
51 |
52 |
53 |
54 | 用于判断请求是否带有凭据和是否登录
55 |
56 |
57 |
58 |
59 | 构造函数注入
60 |
61 |
62 |
63 |
64 | 资源数据的载体,可以根据需求自定义任何数据
65 | 需要实现IAuthorizationRequirement接口进行标识
66 |
67 |
68 |
69 |
70 | 存放系统中所有权限
71 |
72 |
73 |
74 |
75 | 定义了一个权限数据存储类,包含用户ID和对应的权限访问的Url地址
76 |
77 |
78 |
79 |
80 | 用户ID
81 |
82 |
83 |
84 |
85 | 用户对应的 Url地址
86 |
87 |
88 |
89 |
90 |
--------------------------------------------------------------------------------
/SwaggerDemo/TestSwaggerModel.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | TestSwaggerModel
5 |
6 |
7 |
8 |
9 | 用户登录条件
10 |
11 |
12 |
13 |
14 | 用户名
15 |
16 |
17 |
18 |
19 | 密码
20 |
21 |
22 |
23 |
24 | 返回的用户信息
25 |
26 |
27 |
28 |
29 | 用户名
30 |
31 |
32 |
33 |
34 | 密码
35 |
36 |
37 |
38 |
39 | 年龄
40 |
41 |
42 |
43 |
44 | 地址
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/SwaggerDemo/WeatherForecast.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace SwaggerDemo
4 | {
5 | public class WeatherForecast
6 | {
7 | public DateTime Date { get; set; }
8 |
9 | public int TemperatureC { get; set; }
10 |
11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
12 |
13 | public string Summary { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/SwaggerDemo/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/SwaggerDemo/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft": "Warning",
6 | "Microsoft.Hosting.Lifetime": "Information"
7 | }
8 | },
9 | "AllowedHosts": "*"
10 | }
11 |
--------------------------------------------------------------------------------
/TestSwaggerModel/TestSwaggerModel.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 |
7 |
8 | ..\SwaggerDemo\TestSwaggerModel.xml
9 | 1701;1702;1591
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/TestSwaggerModel/UserConditon.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace TestSwaggerModel
6 | {
7 | ///
8 | /// 用户登录条件
9 | ///
10 | public class UserConditon
11 | {
12 | ///
13 | /// 用户名
14 | ///
15 | public string UserName { get; set; }
16 | ///
17 | /// 密码
18 | ///
19 | public string Pwd { get; set; }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/TestSwaggerModel/UserModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace TestSwaggerModel
4 | {///
5 | /// 返回的用户信息
6 | ///
7 | public class UserModel
8 | {
9 | ///
10 | /// 用户名
11 | ///
12 | public string UserName { get; set; }
13 | ///
14 | /// 密码
15 | ///
16 | public string Pwd { get; set; }
17 | ///
18 | /// 年龄
19 | ///
20 | public int Age { get; set; }
21 | ///
22 | /// 地址
23 | ///
24 | public string Addr { get; set; }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/test/test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 |
7 |
8 |
9 |
10 | runtime; build; native; contentfiles; analyzers; buildtransitive
11 | all
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------