NetCore3.1系列 Asp.NetCore3.1 WebApi 使用Jwt 授权认证使用(附源代码)

1.导入NuGet包

Microsoft.AspNetCore.Authentication.JwtBearer

Swashbuckle.AspNetCore.Swagger

Swashbuckle.AspNetCore.SwaggerUI

2.代码配置

appsettings.json 

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "JwtSettings": {
    "Issuer": "http://localhost:44349/",
    "Audience": "http://localhost:44349/",
    "SecretKey": "a1s2123d45d3f4erqweas5" //私密钥,SecretKey必须大于16位
  }
}

startUp.cs

using Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.IO;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.Runtime.Loader;

namespace NetCoreStudy
{
    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.AddControllersWithViews();


            #region JWT认证

            //将appsettings.json中的JwtSettings部分文件读取到JwtSettings注入依赖
            services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));

            //由于初始化就需要用,所以使用Bind的方式读取配置
            //将配置绑定到JwtSettings实例中
            var jwtSettings = new JwtSettings();
            Configuration.Bind("JwtSettings", jwtSettings);

            services.AddAuthentication(options =>
            {
                //认证middleware配置
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                //主要是jwt  token参数设置
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    //Token颁发机构
                    ValidIssuer = jwtSettings.Issuer,
                    //颁发给谁
                    ValidAudience = jwtSettings.Audience,
                    //这里的key要进行加密,需要引用Microsoft.IdentityModel.Tokens
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
                    //ValidateIssuerSigningKey=true,
                    是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                    //ValidateLifetime=true,
                    允许的服务器时间偏移量
                    //ClockSkew=TimeSpan.Zero
                };
            });

            #endregion

            #region 跨域  

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });

            #endregion

            #region Swagger

            //注册Swagger生成器,定义一个和多个Swagger 文档
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",         //版本
                    Title = "我的API",     //标题
                    Description = "API描述",//描述

                    Contact = new OpenApiContact   //联系人信息
                    {
                        Name = "联系人",
                        Email = "我的邮箱",
                    }
                });
                // 为 Swagger JSON and UI设置xml文档注释路径
                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                var xmlPath = Path.Combine(basePath, "NetCoreStudy.xml");//xml路径名称
                c.IncludeXmlComments(xmlPath);
            });
            #endregion


            services.AddMvc(options => options.EnableEndpointRouting = false);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            //跳转https
            //app.UseHttpsRedirection();

            //静态文件
            app.UseStaticFiles();

            app.UseRouting();
            #region JWT

            //1.先开启认证
            app.UseAuthentication();
            //2.再开启授权
            app.UseAuthorization();

            #endregion

            #region 跨域

            app.UseCors("CorsPolicy");

            #endregion

            #region Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "我的API文档 v1"));
            #endregion

            //路由

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });


        }

    }
}

3.使用

使用时在Controller /action 上打上特性 [Authorize]

可以单独在Action上打上特性[Authorize]  不需要检查授权认证的话打上特性: [AllowAnonymous]

两个特性类都在如下命名空间下:using Microsoft.AspNetCore.Authorization;

 

4.获取token

 

5.登录后调用其他接口

200 ok

无权限 401

附:

源代码:https://download.csdn.net/download/sunwork888/14907148

Postman 工具下载: https://www.onlinedown.net/soft/971602.htm

HTTP状态码: https://baike.baidu.com/item/HTTP%E7%8A%B6%E6%80%81%E7%A0%81/5053660?fr=aladdin

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值