使用Azure Active Directory访问Azure Function时,Blazor客户端会收到CORS错误 [英] Blazor Client side get CORS error when accessing Azure Function using Azure Active directory

查看:61
本文介绍了使用Azure Active Directory访问Azure Function时,Blazor客户端会收到CORS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我一直在尝试部署Blazor PWA 2天,但没有成功,如果有人对我做错的事情有所了解,我将非常感激.你好我可以自己解决大部分问题,但现在我只能使用AAD解决CORS问题.

I've been trying to deploy my Blazor PWA for 2 days without any success so far, if someone has an idea of what I’m doing wrong I would be really grateful. hello I could resolve most of my issues by myself but I'm now stuck on a CORS problem using AAD.

这是我的项目设置:

  • 在静态网站存储上托管的Blazor Webassembly客户端(有效很棒),Net 5
  • AzureFunctions已连接到Azure Sql Server数据库(效果很好Blazor中具有匿名身份验证的用户)
  • 我想用来验证用户身份的Azure Active Directory.(同时保护blazor应用程序和功能)

因此,我创建了一个应用程序注册,将我的静态网站地址添加为SPA uri,并取消了两个隐式复选框.在我的blazor客户端program.cs中,我添加了以下代码以连接到AAD:

So I’ve created an App registration, added my static web site address as SPA uri and uncheck both implicit. In my blazor client, program.cs, I’ve added the following code to connect to AAD:

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication); //contains clientId, Authority
    options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read");
    options.ProviderOptions.LoginMode = "redirect";
});

这也很好,我可以登录并按预期授权视图工作.

That works great too, I can login, authorize view works as expected.

问题是,当我尝试使用《使用Azure Active Directory登录》对Azure功能进行身份验证时,我尝试了快速配置和高级配置(使用clientId,tenantId),但是当我

The problem is when I try to authenticate Azure functions with «Login with Azure Active Directory», I' tried with both express and advanced configurations (using clientId, tenantId) but when I

可从来源"获取"https://login.windows.net/tenantid/oauth2/authorize ...(从'https://myfunctionstorage.azurewebsites.net/api/client/list'重定向)https://*****9.web.core.windows.net"已被CORS策略阻止:所请求的资源上没有"Access-Control-Allow-Origin"标头.如果不透明的响应可以满足您的需求,请将请求的模式设置为"no-cors",以在禁用CORS的情况下获取资源.

Access to fetch at 'https://login.windows.net/tenantid/oauth2/authorize ... (redirected from 'https://myfunctionstorage.azurewebsites.net/api/client/list') from origin 'https://*****9.web.core.windows.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我当然已经在Azure Functions配置中为我的Blazor客户端地址启用了CORS,但问题似乎与登录窗口uri有关.

I have of course enabled CORS for my Blazor Client Address on Azure Functions configuration but the problem seems to be about the login windows uri...

此外,如果我在应用程序注册中启用了令牌ID隐式流,并在浏览器中访问了登录网址,则效果很好.

Also, if I enable the token id implicit flow in the App registration and access the login url in the browser it works perfectly fine.

到目前为止,我能找到的所有示例都是关于msal 1.0和使用隐式流而不是SPA进行的App注册,因此它无济于事...

All the examples I could find so far are about msal 1.0 and App registration using implicit flow instead of SPA so it doesn't help...

感谢您的时间和帮助.

更新:从昨天开始,我进行了更多研究,我认为可以与我的HTTPClient相关,目前我使用的是基本的(只有基本地址).

UPDATE: I’ve done more researches since yesterday and I think it could by related to my HTTPClient, currently I use the basic one (with just a base adress).

但是我在一些示例中看到,在通过AAD使用客户端时,它需要更多参数,例如:

But I’ve seen on some example that when using the Client using AAD it needs more parameters, for example:

builder.Services.AddHttpClient("companiesAPI", cl => { cl.BaseAddress = new Uri("https://localhost:5001/api/"); }) .AddHttpMessageHandler(sp => { var handler = sp.GetService<AuthorizationMessageHandler>() .ConfigureHandler( authorizedUrls: new[] { "https://localhost:5001" }, scopes: new[] { "companyApi" } ); return handler; });

需要AuthorizationMessageHandler吗?我也看到一些有关使用"use_impersonation»范围的需要的参考.

Is that AuthorizationMessageHandler needed ? Also I see some references to the need of using the «use_impersonation» scope.

使用msal2/SPA应用程序注册时,是否还需要进行这些更改(在HttpClient和use_impersonation范围上)?

Are those changes (on HttpClient and the use_impersonation scope) also required when using msal2/SPA app registration ?

谢谢

推荐答案

如果要在Blazor Webassembly客户端中调用Azure AD投影的Azure函数,请参考以下步骤如果要在角度应用程序中调用Azure AD投影的Azure函数,请参考以下代码

If want to call the Azure function projected by Azure AD in Blazor webassembly client, please refer to the following steps If you want to call Azure function projected by Azure AD in angular application, please refer to the following code

  • 创建Azure AD应用程序以保护功能

  1. 注册Azure AD应用程序.完成后,请复制应用程序(客户端)ID 目录(租户)ID

配置重定向URI .选择网络,然后键入< app-url>/.auth/login/aad/callback .

Configure Redirect URI. Select Web and type <app-url>/.auth/login/aad/callback.

启用隐式授予流程

定义API范围并复制它

Define API scope and copy it

创建客户端机密.

  • 在App Service应用中启用Azure Active Directory

    在Azure Function中配置CORS策略

    创建客户端AD应用程序以访问功能

    1. 注册申请
    2. 启用隐式授予流程
    3. 配置API权限.让您的客户端应用程序具有访问功能的权限

  • 代码

    1. 创建自定义 AuthorizationMessageHandler

    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
    
    public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler
    {
        public CustomAuthorizationMessageHandler(IAccessTokenProvider provider, 
            NavigationManager navigationManager)
            : base(provider, navigationManager)
        {
            ConfigureHandler(
                authorizedUrls: new[] { "<your function app url>" },
                scopes: new[] { "<the function app  API scope your define>" });
        }
    }
    

    1. Program.cs 中添加以下代码.
    1. Add the following code in Program.cs.

     public static async Task Main(string[] args)
            {
                var builder = WebAssemblyHostBuilder.CreateDefault(args);
                builder.RootComponents.Add<App>("app");
                 // register CustomAuthorizationMessageHandler 
                builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
                // configure httpclient
                // call the following code please add packageMicrosoft.Extensions.Http 3.1.0
                builder.Services.AddHttpClient("ServerAPI", client =>
                  client.BaseAddress = new Uri("<your function app url>"))
                        .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
                // register the httpclient
                builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
                 .CreateClient("ServerAPI"));
                // configure Azure AD auth
                builder.Services.AddMsalAuthentication(options =>
                {
                    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
                    options.ProviderOptions.DefaultAccessTokenScopes.Add("<the function app  API scope your define>");
    
    
                });
    
                await builder.Build().RunAsync();
            }
    

    1. 调用API

    @page "/fetchdata"
    @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
    @inject HttpClient Http
    
    <h1>Call Azure Function</h1>
    
    <p>This component demonstrates fetching data from the server.</p>
    
    <p>Result: @forecasts</p>
    
    <button class="btn btn-primary" @onclick="CallFun">Call Function</button>
    
    @code {
        private string forecasts;
    
        protected async Task CallFun()
        {
            forecasts = await Http.GetStringAsync("api/http");
        }
    
    
    }
    

    这篇关于使用Azure Active Directory访问Azure Function时,Blazor客户端会收到CORS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆