zoukankan      html  css  js  c++  java
  • .Net Core Api 授权认证

    一、所使用到的NuGet:

    1. System.IdentityModel.Tokens.Jwt

    2. Microsoft.AspNetCore.Authentication.JwtBearer

    二、在Startup.cs 中配置添加如下服务

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using System.Text;
    using Microsoft.IdentityModel.Tokens;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    
    namespace WebApplication1
    {
        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.AddMvc();
                //手动高亮
                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                      .AddJwtBearer(options => {
                          options.TokenValidationParameters = new TokenValidationParameters
                          {
                              ValidateIssuer = true,//是否验证Issuer
                              ValidateAudience = true,//是否验证Audience
                              ValidateLifetime = true,//是否验证失效时间
                              ValidateIssuerSigningKey = true,//是否验证SecurityKey
                              ValidAudience = "haos.test.com",
                              //山下这两项和签发token时的issuer,Audience一致
                              ValidIssuer = "haos.test.issuer.com",
                              IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567887654321"))//拿到token加密密钥.必须是16个字符
                          };
                      });
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                //手动高亮
                app.UseAuthentication();
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseBrowserLink();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                }
                
                app.UseStaticFiles();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller}/{action=Index}/{id?}");
                });
            }
        }
    }

    三、签发token 添加测试控制器

    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.IdentityModel.Tokens;
    using System;
    using System.IdentityModel.Tokens.Jwt;
    using System.Security.Claims;
    using System.Text;
    using System.Linq;
    
    namespace WebApplication1.Controllers
    {
        [Authorize]
        public class TestController:Controller
        {
    
            public JsonResult Test()
            {
                //获取当前用户信息
                var claims = User.Claims;
                var userName = User.Identity.Name;
                var userId = claims.FirstOrDefault(t => t.Type == "userId");
                var phone = claims.FirstOrDefault(t => t.Type == ClaimTypes.MobilePhone);
                return Json("ok");
            }
            
            /// <summary>
            /// 登录(签发token)
            /// </summary>
            /// <param name="name"></param>
            /// <param name="pwd"></param>
            /// <returns></returns>
            [AllowAnonymous]
            public JsonResult Login(string name ,string pwd)
            {
                var claims = new[]
                   {
                       new Claim(ClaimTypes.Name, "test"),
                       new Claim(ClaimTypes.MobilePhone, "157****7350"),
                       new Claim("userId","value")
                   };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("1234567887654321"));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                       issuer: "haos.test.issuer.com",
                       audience: "haos.test.com",
                       claims: claims,
                       expires: DateTime.Now.AddMinutes(30),
                       signingCredentials: creds);
                return Json(new {
                    Authorization = $"Bearer {new JwtSecurityTokenHandler().WriteToken(token)}"
                });
            }
        }
    }
    //返回的token;注:键为authorization,其中必须有Bearer 字样
    {"authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoidGVzdCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL21vYmlsZXBob25lIjoiMTU3KioqKjczNTAiLCJleHAiOjE1MTc0NjgzNDcsImlzcyI6Imhhb3MudGVzdC5pc3N1ZXIuY29tIiwiYXVkIjoiaGFvcy50ZXN0LmNvbSJ9.Xtrbbz6WF4VreoB-S2nmRL5lx1Vg27WcQYTsek5VPIc"}

    四、访问结果

  • 相关阅读:
    Python装饰器之functools.wraps的作用
    [转]scala和RDD中的占位符"_"
    Scala,Java,Python 3种语言编写Spark WordCount示例
    CentOS系统安装Python3
    [爬虫]采用Go语言爬取天猫商品页面
    go语言的排序和去重
    go语言字符串的连接和截取
    [转]git commit --amend用法
    KM算法小结
    Protocol Buffers学习教程
  • 原文地址:https://www.cnblogs.com/haosit/p/8399048.html
Copyright © 2011-2022 走看看