首页 > 解决方案 > 来自 MVC 的授权 Web API 访问

问题描述

我在 Azure AD 身份验证方面遇到了一些问题。

我的应用程序架构是 Asp.net MVC Web & Web API 作为中间件

当我尝试使用来自 MVC 的 Web API 上的 AD 令牌进行身份验证时,我无法在代码中收到任何错误,甚至没有来自 WEB API 的响应但是如果我尝试使用浏览器访问 API,而我已经使用了凭据进行身份验证MVC 应用程序运行良好。

下面是访问 API 的代码,但它没有用

     AuthenticationResult result = null;
        string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        string ApiClientId = ConfigurationManager.AppSettings["ida:ApiClientId"];
        string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
        string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:ApplicationURI"];
        string postLoginRedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
        string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
        string authority = aadInstance + tenantId;

      IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();

        var account = await app.GetAccountAsync(ClaimsPrincipal.Current.GetMsalAccountId());
        string[] scopes = { "openid profile offline_access email User.Read" };
        try
        {
            // try to get an already cached token
            result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
        }
        catch (MsalUiRequiredException ex)
        {
     {
              
          // A MsalUiRequiredException happened on AcquireTokenSilentAsync.
            // This indicates you need to call AcquireTokenAsync to acquire a token
            //Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

            try
            {
                // Build the auth code request Uri
                  string authReqUrl = await OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, app, this.HttpContext, Url);

             
            }
            catch (MsalException msalex)
            {
                Response.Write($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
            }
        }
   
    var handler = new HttpClientHandler();
        handler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
        handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;

        HttpClient client = new HttpClient(handler);
        //apiUrl      client.BaseAddress = apiUrl;
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiUrl + "api/General/GetUserDetailsByEmailAddress?emailAddress=ikhlesh.saxena@amexassetmanagement.com");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

        try
        {
            HttpResponseMessage response = await client.SendAsync(request);
        }
        catch (Exception ex)
        { 
        
        } 

标签: asp.net-mvcasp.net-web-apiazure-active-directory

解决方案


检查您的范围是否允许您访问您的 API。此外,您需要在 API 端调试令牌是否随请求一起提供,如果是,则如何验证。


推荐阅读