微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

来自MVC的授权Web API访问

如何解决来自MVC的授权Web API访问

Azure AD身份验证遇到一些问题。

我的应用程序体系结构是Asp.net MVC Web和Web API作为中间件

当我尝试通过MVC在Web API上使用AD令牌进行身份验证时,我无法从代码中的WEB API获得任何错误,甚至没有响应 但是,如果我尝试使用已经使用凭据对MVC应用进行身份验证的浏览器访问API,则效果很好。

下面是访问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)
        { 
        
        } 

解决方法

检查您的范围是否允许您访问API。另外,您需要在API端调试令牌是否随请求一起发送,如果是,则如何对其进行验证。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。