gpt4 book ai didi

asp.net-web-api - Core 2.0 上的 IdentityServer4 从 API 获取 401(未经授权)

转载 作者:行者123 更新时间:2023-12-05 06:37:37 26 4
gpt4 key购买 nike

在尝试迁移到最新版本的 IdentityServer4 和 .NET Core 2 后,我的 Web API 项目突然出现 401 错误。在上周,我做了很多更改,我不知道不知道什么是对什么是错了。

我有一个小型 3 项目解决方案:

  1. IDSRV:https://localhost:44300
  2. 网络应用:https://localhost:44301
  3. API 应用程序:https://localhost:44302

这是我配置 IDSV 的代码,存储在我的数据库中:

public class Config
{
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}

public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource(){
Name = "api.oc.com",
Description = "OC Api",
Scopes = new[] {new Scope("api.oc.com")}
}
};
}

public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "oc.com",
ClientName = "OC Website",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
AlwaysIncludeUserClaimsInIdToken = true,
ClientSecrets =
{
new Secret("SomeReallyStrongPassword1!".Sha256())
},
RedirectUris = { "https://localhost:44301/signin-oidc" },
PostLogoutRedirectUris = { "https://localhost:44301/signout-callback-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api.oc.com",
"offline_access"
},
AllowOfflineAccess = true
}
};
}
}

在我的 WEB API Startup.cs 中。我在 ConfigureServices 中有这个。我相信我的 Configure 方法没问题。

        services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.Authority = "https://localhost:44300";
o.RequireHttpsMetadata = false;
o.Audience = "api.oc.com";
});

services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();

这将我带到了试图对 WEB API 进行身份验证的 WEB 前端。我已经尝试过使用访问 token 和 ID token ,但似乎都不起作用。

使用访问 token :

  var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.SetBearerToken(accessToken);
var result = await client.GetStringAsync("https://localhost:44302/api/text/welcome");

或使用客户端凭据流程:

  var disco = await DiscoveryClient.GetAsync("https://localhost:44300");
var tokenClient = new TokenClient(disco.TokenEndpoint, "oc.com", "SomeReallyStrongPassword1!");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync();

var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var result = await client.GetStringAsync("https://localhost:44302/api/text/welcome");

如果有人对此有任何建议,我将非常感谢。看了这么久的安全码,眼珠子都要炸了!哈哈。

谢谢,迈克·库什纳

最佳答案

经过一些干预......并添加了一个真实的证书,这似乎在我创建了一些策略而不是仅使用 [Authorize] 属性之后起作用。 请注意,我也再次使用 IdentityServer4.AccessTokenValidation。

    public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization((options) => {
options.AddPolicy("MustBeValidUser", policybuilder =>
{
policybuilder.RequireAuthenticatedUser();
policybuilder.Requirements = new[] { new MustBeValidUserRequirement() };
});
});
services.AddSingleton<IAuthorizationHandler, MustBeValidUserHandler>();
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:44300";
options.RequireHttpsMetadata = true;
options.ApiName = "api.oc.com";
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseDeveloperExceptionPage();
app.UseAuthentication();
app.UseMvc();
}
}

关于asp.net-web-api - Core 2.0 上的 IdentityServer4 从 API 获取 401(未经授权),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com