MVC .NET CORE 学习之路三:搭建.net core权限认证的环境(IdentityServer或jwt)

本文详细介绍了如何在ASP.NET Core中配置IdentityServer4,包括设置客户端、API资源、证书,并展示了如何在Web API中启用JWT验证。通过步骤演示了生成证书、配置 Startup.cs 文件以及验证JWT Token的过程。
摘要由CSDN通过智能技术生成

1.新建ASP.NET Core Web 应用程序,程序文件如下图

在这里插入图片描述
引用以下包

2.新建config类配置客户端列表

 public static class Config
    {
        public static IEnumerable<IdentityResource> IdentityResources =>
            new IdentityResource[] 
            { 
                new IdentityResources.OpenId(), 
                new IdentityResources.Profile(), 
            };

        /// <summary>
        /// api范围
        /// </summary>
         public static IEnumerable<ApiScope> ApiScopes => 
            new ApiScope[]           
            {      
                new ApiScope("api")           
            };

        /// <summary>
        /// api资源
        /// </summary>
        public static IEnumerable<ApiResource> ApiResources => 
            new ApiResource[]      
            {      
                new ApiResource("api","#api")      
                {                
                   Scopes = { "api" }           
                }
            };

        public static IEnumerable<Client> GetClientConfigList()
        {                
            var appInfo = Account.Instance.GetApps(); //这个是从数据库获取已配置的客户端。     
            List<Client> Clients = new List<Client>();            
            foreach (var item in appInfo)            
            {                
                Client client = new Client();                
                client.ClientId = item.App_ID;               
                client.AllowedGrantTypes = GrantTypes.ClientCredentials;//授权类型,这里使用的是客户端凭证模式               
                client.ClientSecrets.Add(new Secret(item.App_Key.Sha256()));                
                client.AllowedScopes.Add("api");                
                client.AccessTokenLifetime = 36000;//配置Token 失效时间               
                Clients.Add(client);            
            }           
            return Clients;       
        }
    }
public class Account
    {
        public static Account Instance = new Account();

        public List<Z_Token> GetApps() 
        {
            var list = ConetextHelper.context.Set<Z_Token>().ToList();
            return list;
        }
    }

3.在Startup.cs里面配置id4

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.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var basePath = PlatformServices.Default.Application.ApplicationBasePath;
            services.AddIdentityServer(options =>
            {
                options.Caching.ClientStoreExpiration = TimeSpan.FromMinutes(5);//设置缓存过期时间 多久去数据去取一次数据库? ? ? ? ? ?
            }).AddInMemoryIdentityResources(Config.IdentityResources)
                .AddInMemoryApiScopes(Config.ApiScopes)
                .AddInMemoryApiResources(Config.ApiResources)//把受保护的Api资源添加到内存中
                .AddClientStore<ClientStore>().AddInMemoryCaching()
                .AddClientStoreCache<ClientStore>()
                .AddSigningCredential(new X509Certificate2(Path.Combine(basePath, 
                Configuration["Certificates:CertPath"]), //证书
                Configuration["Certificates:Password"])); ;//证书密码
            }

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

            app.UseRouting();
            //启用id4,将id4中间件添加到管道中           
            app.UseIdentityServer();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("IdentityServer is Already Start!");
                });
            });
        }
    }

证书,证书密码在appsettings.json里配置

"Certificates": {
    "CertPath": "Certificates/idsrv4.pfx",
    "Password": "123.zg"
  }

4.证书和证书密码来源配置

1>下载Openssl
https://oomake.com/download/openssl
2>配置环境变量
在这里插入图片描述
3>生成证书
打开cmd,cd 到项目文件中
1.申请一个私钥,在命令行中输入:openssl genrsa -out idsrv4.key 2048
2.申请一个公钥,在命令行中输入:openssl req -newkey rsa:2048 -nodes -keyout idsrv4.key -x509 -days 365 -out idsrv4.cer
Country Name (2 letter code) []:CN // 输入国家代码,中国填写
CNState or Province Name (full name) []:JiangSu // 输入省份,这里填写 HangZhouLocality Name (eg, city) []:NanJing // 输入城市,我们这里也填写 HangZhouOrganization Name (eg, company) []:newWave // 输入组织机构(或公司名)
Organizational Unit Name (eg, section) []:newWave // 输入机构部门
Common Name (eg, fully qualified host name) []:awave // 输入域名
Email Address []:461192412@qq.com // 你的邮箱地址
3.openssl pkcs12 -export -in idsrv4.cer -inkey idsrv4.key -out idsrv4.pfx
输入密码和确认密码
4>验证JWT Token
网址:https://jwt.io/
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

5.webapi调用

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
1>在Startup.cs里面配置

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.AddDbContext<StudyNetCoreContext>(optionsBuilder => {
                var dataAppSetting = Configuration.GetConnectionString("SqlServer");
                if (dataAppSetting == null)
                {
                    throw new Exception("未配置数据库连接");
                }
                optionsBuilder.UseSqlServer(Configuration.GetConnectionString("SqlServer")); //读取配置文件中的链接字符串
            });
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).
                AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, 
                options => {                    
                    //身份认证平台地址(身份认证时会去这个地址验证token是否有效)                 
                    options.Authority = Configuration["AppSettings:IdentityServerUrl"]; 
                    options.RequireHttpsMetadata = false;   //一般默认(true),开发环境时可以设置为false        
                    options.TokenValidationParameters.RequireExpirationTime = true; //是否需要超时时间参数     
                    //apiResource 
                    options.Audience = Configuration["AppSettings:Audience"]; 
                    options.SaveToken = true;               
                });
                services.AddControllersWithViews();
        }

        // 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();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

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

Configuration[“AppSettings:IdentityServerUrl”];这里是id4微服务的地址
Configuration[“AppSettings:Audience”];这里是微服务开发的可访问资源名称
app.UseAuthentication();
app.UseAuthorization(); 启用验证
2>在api控制器里面加上 [Authorize],代表验证
3>token效果调用在这里插入图片描述
微服务网址: https://localhost:44320/connect/token
访问参数:grant_type:client_credentials //客户端凭证
client_id:客户端名称
client_secret:客户端秘钥
获取到token后,调用自己的webapi资源
在这里插入图片描述
在头文件里面加上参数:
Authorization :Bearer+空格+token
在这里插入图片描述
访问成功,权限验证全部完成。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值