ASP.NET Core MVC 项目 WebApi 鉴权授权

目录

一:引用Microsoft.AspNetCore.Authentication.JwtBearer

二:添加JWTTokenOptions类

三:修改Program.cs文件

四:配置appsettings.json文件

五:修改Controller控制器


一:引用Microsoft.AspNetCore.Authentication.JwtBearer

当前项目右键管理NuGet包,浏览搜索Microsoft.AspNetCore.Authentication.JwtBearer,选择6.0版本的进行安装。

二:添加JWTTokenOptions类

namespace Study_ASP.NET_Core_MVC.WebApi.Utility
{
    public class JWTTokenOptions
    {
        public string Audience { get; set; }
        public string SecurityKey { get; set; }
        public string Issuer { get; set; }
    }
}

三:修改Program.cs文件

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Study_ASP.NET_Core_MVC.WebApi;
using Study_ASP.NET_Core_MVC.WebApi.Utility;
using System.Reflection;
using System.Text;
//表示整个应用程序,调用CreateBuilder方法创建一个WebApplicationBuilder对象
var builder = WebApplication.CreateBuilder(args);

//向管道容器添加注册中间件
//添加注册Controller中间件
//添加注册Swagger中间件
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
//配置Swagger
builder.Services.AddSwaggerGen(c =>
{
    //版本控制
    foreach (FieldInfo field in typeof(ApiVersionInfo).GetFields())
    {
        c.SwaggerDoc(field.Name, new OpenApiInfo()
        {
            Title = $"当前Swagger版本为:{field.Name}",
            Version = field.Name,
            Description = $"当前Swagger版本为:{field.Name}"
        });
    }
    //设置文档注释
    //获取当前项目绝对路径
    string basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
    //生成Xml文件
    string xmlPath = Path.Combine(basePath, "Study ASP.NET Core MVC.WebApi.xml");
    //加载Xml文件
    c.IncludeXmlComments(xmlPath);
});
//配置JWT鉴权
JWTTokenOptions tokenOptions = new JWTTokenOptions();
builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        //JWT默认属性  
        //是否验证Issuer
        ValidateIssuer = true,
        //是否验证Audience
        ValidateAudience = true,
        //似乎否验证失效时间  
        ValidateLifetime = true,  
        //是否验证SecurityKey
        ValidateIssuerSigningKey = true,  
        //与签发JWT设置一致
        ValidAudience = tokenOptions.Audience,  
        //与签发JWT设置一致
        ValidIssuer = tokenOptions.Issuer,  
        //获取SecurityKey
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey))
    };
});

//初始化管道
var app = builder.Build();

//配置HTTP请求管道判断开发者模式
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        foreach (FieldInfo field in typeof(ApiVersionInfo).GetFields())
        {
            c.SwaggerEndpoint($"/Swagger/{field.Name}/Swagger.json", $"{field.Name}");
        }
    });
}

//向管道添加用于将HTTP请求重定向到HTTPS的中间件
app.UseHttpsRedirection();
//向管道添加用于身份鉴权授权中间件
app.UseAuthentication();
app.UseAuthorization();
//向管道添加用于Controller中间件
app.MapControllers();


//向管道添加启动应用程序中间件
app.Run();

四:配置appsettings.json文件

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "JWTTokenOptions": {
    "Audience": "http://localhost:5200",
    "Issuer": "http://localhost:5200",
    "SecurityKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD+Lka6DSTy8gt9UwfgVQo6uKjVLG5Ex7PiGOODVqAEghBuS7JzIYU5RvI543nNDAPfnJsas96mSA7L/mD7RTE2drj6hf3oZjJpMPZUQI/B1Qjb5H3K3PNwIDAQAB"
  }
}

五:修改Controller控制器

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Study_ASP.NET_Core_MVC.WebApi.Controllers
{
    /// 
    /// 在控制器上应用特性
    /// Api控制器特性
    /// 路由特性
    /// Swagger版本控制
    /// 
    [ApiController]
    [Route("[controller]/[action]")]
    [ApiExplorerSettings(GroupName =nameof(ApiVersionInfo.V1))]
    public class HomeController : Controller
    {
        /// 
        /// 初始化构造函数
        /// 
        private readonly ILogger _logger;
        public HomeController(ILogger logger)
        {
            _logger = logger;
        }
        /// 
        /// Get请求
        /// JWT鉴权授权
        /// 获取数据
        /// 
        /// 
        [HttpGet]
        [Authorize(AuthenticationSchemes =JwtBearerDefaults.AuthenticationScheme)]
        public object GetData()
        {
            return new
            {
                Id = 123,
                Name = "VinCente"
            };
        }
        /// 
        /// Post请求
        /// 新增数据
        /// 
        /// 
        [HttpPost]
        public object PostData()
        {
            return new
            {
                Success = true,
                Message = "新增操作成功"
            };
        }
        /// 
        /// Put请求
        /// 修改数据
        /// 通过路由特性访问
        /// 
        /// 
        [HttpPut]
        [Route("PutDate")]
        public object PutDate()
        {
            return new
            {
                Success = true,
                Message = "修改操作成功"
            };
        }
        /// 
        /// Delete请求
        /// 删除数据
        /// 通过路由特性访问
        /// 
        /// 
        [HttpDelete]
        [Route("DeleteDate")]
        public object DeleteDate()
        {
            return new
            {
                Success = true,
                Message = "删除操作成功"
            };
        }
    }
}

你可能感兴趣的:(NET,asp.net,.netcore,.net,mvc)