asp.net core 添加breaer token认证

Step 1. 增加配置信息和配置类

增加一个类与配置信息绑定

    public class JWTConfig
    {
        public string Issuer { get; set; }
        public string Audience { get; set; }
        public string IssuerSigningKey { get; set; }
        public int AccessTokenExpiresMinutes { get; set; }
    }

appsetting.json

"JWT": {
    "Issuer": "AZDigital",
    "Audience": "allCustomer",
    "IssuerSigningKey": "AZDigital67451147",
    "AccessTokenExpiresMinutes": "1440"
  }

Step 2. Startup.cs增加

ConfigureServices函数增加

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //services.AddControllers();

            //增加报错异常提示
            services.AddControllers().AddHttpExceptions();

            //这里可以添加注入对象并与配置内容绑定
            services.AddOptions();
            services.Configure<JWTConfig>(Configuration.GetSection("JWT"));

            #region 读取配置文件
            JWTConfig config = new JWTConfig();
            Configuration.GetSection("JWT").Bind(config);
            #endregion

            #region 开启JWT
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).
            AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer = config.Issuer,
                    ValidAudience = config.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.IssuerSigningKey)),
                    ClockSkew = TimeSpan.FromMinutes(1),
                };
            });
            #endregion
            
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "AZReport API", Version = "v1" });
            });
        }

Configure函数增加

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

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Report V1");
            });

            // 这里使用http异常信息
            app.UseHttpExceptions();
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            // brerer token 开启使用认证必须加到上下两个函数之间
            app.UseAuthentication();
            app.UseAuthorization();

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

 

Step 3. 创建token的函数

        // 创建和认证的时候
        // issuer + audience + signingCredentials 和 认证的时候必须一致才行
        private string CreateToken()
        {
            var now = DateTime.Now;
            var expires = now.Add(TimeSpan.FromMinutes(_options.Value.AccessTokenExpiresMinutes));
            Claim[] claims = { new Claim(ClaimTypes.Email, "admin"), new Claim(ClaimTypes.Name, "admin") };
            var token = new JwtSecurityToken(
                   issuer: _options.Value.Issuer,
                   audience: _options.Value.Audience,
                   claims: claims,
                   notBefore: now,
                   expires: expires,
                   signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Value.IssuerSigningKey)), SecurityAlgorithms.HmacSha256));
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

 

Step 4. 增加需要认证的控制器

    [Route("api/test")]
    [Authorize] //添加这个配置
    public class ValuesController : ControllerBase
    {
        [HttpGet("aaa")]
        [AllowAnonymous]  //这个意思是跳过认证
        public string getsss()
        {
            return "aaaaa";
        }

        [HttpGet("bbb")]
        public string getcccc()
        {
            return "bbbbb";
        }

    }

ok。。至此完了。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值