gpt4 book ai didi

c# - Web API (.NET Framework) Azure AD 身份验证始终返回 401 未经授权

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

我的场景就像我必须在 Azure Web App 中部署 Web API(.NET Framework),并且所有请求都应通过 Azure AD 身份验证。我谷歌了一下,发现微软提供了类似的案例。我遵循了 Microsoft 提供的以下示例,当我在机器中测试此代码时,它工作正常。

Native client to Web API to Web API.

就我而言,我能够生成 OAuth2 token ,但问题是我总是收到 401 未经授权的错误。我关注了很多博客,但无法找出导致问题的原因。非常感谢任何帮助。

我的代码是:

启动.cs

    public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}

启动.Auth.cs

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

Controller .cs

[Authorize]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AuthController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
try
{
using (sqldbEntities entities = new sqldbEntities())
{
return Request.CreateResponse(HttpStatusCode.OK, (ConfigurationManager.AppSettings["GetMethod"]));
}
}
catch (Exception ex)
{
Log4net.log.Error(string.Format(ConfigurationManager.AppSettings["ErrorGetData"], ex.Message));
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}

有两种方式生成 token :方法 1) 来自另一个 ASP.NET 应用程序

private static AuthenticationContext authContext = null;
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
Uri redirectUri = new Uri(ConfigurationManager.AppSettings["ida:RedirectUri"]);

private static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
private static string todoListResourceId = ConfigurationManager.AppSettings["todo:TodoListResourceId"];

protected async void Button1_Click(object sender, EventArgs e)
{
authContext = new AuthenticationContext(authority);
AuthenticationResult result = null;
result = await authContext.AcquireTokenAsync(todoListResourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Always));
TextBox1.Text = result.AccessToken;
}

方法 2) 来自 postman 网址:https://login.microsoftonline.com/myad.onmicrosoft.com/oauth2/token

方法:POST

正文:grant_type=authorization_code&client_id=89479d4f-aaaa-4ebf-80f2-13e423431bfb&client_secret=hZ_8Ls1EmFarH_lPn4=aaaa-k8TJ_&redirect_uri= https://NAClient-OBO/&code=AQABAAIAAABeAFzDwllzTYGDLh_qYbH8KZRKktzMuxXp0hM6k1B__lWQrxaikd6wwrYrKZ470UAdr4g1GqAPWja6JgpqsDtLefE23vW80qP7xgVodury28LkGLzL1Mbq0auUeiBaaaa-oCZf11o5EsaSVRVlke6FMkbIn_ppA_GsEBhIAEjxHXXjkrIcp-e4g0G5t9prme4IZ0Sg2_L4MvN6TAyr-nEPGDlnWZLBkRvu8Izsm3RiI_cnneCi1xonZaKBSlsgONIwpgN1bOaz16OVW2uu5lTiz206CSrJtzWeKkitPNUx2Gnn-RnZcCUVDyLxK-eJy8o_ggn_iu7F7kdjKj-b70Gfp5BPYx6fxB4Zyw8tpnWzVkLG7IbLGx9di112u-UGgVSBfWQiO5w3a4Mx2KdDcUihMlVW_mgBUdQi4160AKq1Id9ZcpJEKCT11KWwkO25_q7huCxJ_6-mEU4ADCGjj8hDOtRLGNeZMwhB13rYTN7qGQMmpX491RoldCfpfevva16DhQl5VHbIqspknkK1pFHvh90J47DSg0VihQOIQp1FZ7EgAA&resource=89479d4f-aaaa-4ebf-80f2-13e423431bfb

请帮忙。

最佳答案

根据我的测试,我们可以使用以下步骤来实现

  1. 为您的 Web API 配置 Azure AD。更多详情请引用document

    a.创建 Azure AD Web api 应用程序

    b. Expose API enter image description here

  2. Create client application to access the web api

  3. 配置代码

    • 网络 API

      a.启动.cs

       public void ConfigureAuth(IAppBuilder app)
      {
      app.UseWindowsAzureActiveDirectoryBearerAuthentication(
      new WindowsAzureActiveDirectoryBearerAuthenticationOptions
      {
      Tenant = "<your tenant id>",
      TokenValidationParameters = new TokenValidationParameters
      {
      ValidAudiences = new[] { "your web api application app id url", "your web api application app id" }
      },
      }) ;;
      }

      b. Controller

      [Authorize]
      [EnableCors(origins: "*", headers: "*", methods: "*")]
      public class ValuesController : ApiController
      {
      // GET api/values
      public IEnumerable<string> Get()
      {
      return new string[] { "value1", "value2" };
      }
      }
    • 客户端应用程序。我使用控制台应用程序调用 api
    var authority = "https://login.microsoftonline.com/<your tenat id>";
    AuthenticationContext authContext = new AuthenticationContext(authority);
    var uri = "< your redirect url>";
    var clientId = "< your client application app id>";
    var resource = "<your web api application app id url or your web api application app id>";
    var result = authContext.AcquireTokenAsync(resource, clientId, new Uri(uri), new PlatformParameters(PromptBehavior.Always)).Result;

    using (HttpClient httpClient = new HttpClient())
    {

    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

    var response = httpClient.GetAsync("https://localhost:44345/api/values").Result;
    Console.WriteLine(response.StatusCode);
    Console.WriteLine(response.Content.ReadAsStringAsync().Result);

    }

    enter image description here

关于c# - Web API (.NET Framework) Azure AD 身份验证始终返回 401 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60478427/

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