素材巴巴 > 程序开发 >

记录我在NET5 WEBAPI IdentityServer4 CORS遇到的问题

程序开发 2023-09-13 06:10:48

搞了一个项目,折腾了我一个星期,其中一个问题困扰了我三天。

首先,是为项目添加IdentityServer4 的客户端模式。

安装包为:

startup中的ConfigureServices添加如下代码:

            #region 客户端模式{//authorize url../connect/tokenservices.AddIdentityServer()//怎么处理.AddDeveloperSigningCredential()//添加开发人员签名凭据                                                .AddInMemoryApiResources(ClientInitConfig.GetApiResources())//能访问啥资源.AddInMemoryApiScopes(ClientInitConfig.GetApiScopes())//把受保护的Api资源添加到内存中.AddInMemoryClients(ClientInitConfig.GetClients(Configuration))//把配置文件的Client配置资源放到内存                  ;}//鉴权services.AddAuthentication("Bearer").AddIdentityServerAuthentication(options =>{//ids4的地址,目的: 获取公钥,因为获取获取了公钥才能解密options.Authority = Configuration["App:ServerRootAddress"];options.ApiName = "UserApi";options.RequireHttpsMetadata = false;});//自定义授权--必须包含Claim client_role & 必须是Adminservices.AddAuthorization(options =>{options.AddPolicy("AdminPolicy",policyBuilder => policyBuilder.RequireAssertion(context =>context.User.HasClaim(c => c.Type == "client_role")&& context.User.Claims.First(c => c.Type.Equals("client_role")).Value.Equals("Admin")));});//自定义授权--必须包含Claim client_EMail & 必须qq结尾services.AddAuthorization(options =>{options.AddPolicy("EMailPolicy",policyBuilder => policyBuilder.RequireAssertion(context =>context.User.HasClaim(c => c.Type == "client_EMail")&& context.User.Claims.First(c => c.Type.Equals("client_EMail")).Value.EndsWith("@qq.com")));});#endregion          // Configure CORS for angular2 UIservices.AddCors(options => options.AddPolicy(_defaultCorsPolicyName,builder => builder.WithOrigins(// App:CorsOrigins in appsettings.json can contain more than one address separated by comma.Configuration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.Remove(o.LastIndexOf("/"), 1)).ToArray()).AllowAnyHeader().AllowAnyMethod().AllowCredentials()指定处理cookie));

startup的Configure中添加:

 #region 添加IdentityServer中间件app.UseIdentityServer();#endregionapp.UseRouting();app.UseCors(_defaultCorsPolicyName); // Enable CORS!app.UseAuthorization();

新建一个类

public class ClientInitConfig{/// /// 定义ApiResource   /// 这里的资源(Resources)指的就是管理的API/// /// 多个ApiResourcepublic static IEnumerable GetApiResources(){return new[]{new ApiResource("UserApi", "用户获取API")};}/// /// 定义验证条件的Client/// /// public static List GetClients(IConfiguration configuration){var rClinets = new List();var section = configuration.GetSection("ClientCredentials");var clients = section.GetChildren().ToList();for (int i = 0; i < clients.Count; i++){var clientId = clients[i]["ClientId"];var clientSecret = clients[i]["ClientSecret"];var scopes = clients[i].GetSection("Scopes");var claims = clients[i].GetSection("Claims");var c = new Client{ClientId = clientId,//AppIdClientSecrets = new[] { new Secret(clientSecret.Sha256()) },//客户端密码AllowedGrantTypes = GrantTypes.ClientCredentials,//Grant类型                  AllowedScopes = scopes.AsEnumerable().Select(x => x.Value).Where(x => !string.IsNullOrWhiteSpace(x)).ToList(),//允许访问的资源                   Claims = new List(){new ClientClaim(IdentityModel.JwtClaimTypes.Role, claims["role"]),new ClientClaim(IdentityModel.JwtClaimTypes.NickName, claims["nickname"]),new ClientClaim("EMail", claims["EMail"])},AllowedCorsOrigins = configuration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(o => o.Remove(o.LastIndexOf("/"), 1)).ToArray()};rClinets.Add(c);}return rClinets;}//定义Api资源public static IEnumerable GetApiScopes(){return new List{new ApiScope("UserApi"),};}          }

以上代码,运行后,用postman调试时报错“invalid_client”

当我把ClientInitConfig中的以下这段注释,postman调试成功

 //AllowedCorsOrigins = configuration["App:CorsOrigins"]//            .Split(",", StringSplitOptions.RemoveEmptyEntries)
 //            .Select(o => o.Remove(o.LastIndexOf("/"), 1))
 //            .ToArray()

上面是注释,将影响后续的鉴权,我将继续研究问题并解决。


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。