gpt4 book ai didi

c# - ASP.Net Web Api响应未经授权的访问

转载 作者:行者123 更新时间:2023-12-03 03:08:56 25 4
gpt4 key购买 nike

我有托管在 Azure 上的 ASP.Net webapi。实际上我有两个不同的订阅

  1. 对于 Azure Active Directory - 指定其 demo.onmicrosoft.com
  2. 用于托管 webapi。 - 假设其托管在 abc.azurewebsites.net

我的 api 托管在 abc.azurewebsites.net 上,已在 demo.onmicrosoft.com 上注册。我的客户端应用程序是一个服务应用程序,它针对驻留在 demo.onmicrosoft.com 中的用户进行身份验证。身份验证是通过传递用户凭据并从 Azure Active Directory 接收 AccessToken 进行的基本身份验证。从 demo.onmicrosoft.com 收到 token 后,我从 abc.azurewebsites.net 调用 api。像这样:

https://abc.azurewebsites.net/api/some/queryapi

现在,在我的 Controller 中,如果我使用

[Authorize]
public class SomeController:ApiController
{
//my code
}

我正在获得未经授权的访问权限。如果我从 Controller 中删除该属性,它就可以正常工作。你能帮我吗?即使在应用程序注册和身份验证之后,为什么我会这样。这是因为两个不同的订阅还是其他原因。

更新

我通过这种方式将 token 发送到我的 webapi

using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
}

IMO,因为我的 token 来自其他订阅的 azure 广告,所以我的 webapi 无法识别它。

更多更新 - Startup.cs

  public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
});
}

Web.config

  <add key="ida:Tenant" value="demo.onmicrosoft.com" />
<add key="ida:Audience" value="https://demo.onmicrosoft.com/4e4xxxx5-5xx1-4355-8xxc-705xxxx163" />
<add key="ida:ClientID" value="d0xxxxa-2xxx6-4xx-9e58-07xxxxxxxx1" />

最佳答案

这与保护 Web API 而不是 Azure 订阅的方式有关。例如,下面是一段用于在.net core中使用Azure AD保护Web API的代码:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Add the console logger.
loggerFactory.AddConsole(LogLevel.Debug);

// Configure the app to use Jwt Bearer Authentication
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAD:Tenant"]),
Audience = Configuration["AzureAd:Audience"],
Events = new JwtBearerEvents
{
OnTokenValidated = tokenValidated ,
OnAuthenticationFailed= AuthenticationFailed
}
});
}

此 Web API 将验证 token 的签名,以确保 token 是从 Azure AD 颁发的。然后它将检查访问 token 中的 aud 声明。如果 aud 声明也符合我们在上面代码中的配置,我们就可以成功调用 Web API。

关于c# - ASP.Net Web Api响应未经授权的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41458831/

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