简体   繁体   English

在角度应用程序中添加 Azure AD 身份验证(使用 MSAL)时出现 CORS 问题

[英]Trouble with CORS when adding Azure AD authentication (with MSAL) in a angular app

I'm currently developing an Angular 8 Frontend & asp.net core 3.1 backend application where I use Azure AD to authenticate users.我目前正在开发一个 Angular 8 Frontend & asp.net core 3.1 后端应用程序,我使用 Azure AD 对用户进行身份验证。

The flow of the application goes as followed.申请流程如下。

The user tries to login or access a route that is protected/guarded in my Angular app so the user gets redirected to the Azure login page.用户尝试登录或访问在我的 Angular 应用程序中受保护/保护的路由,以便用户被重定向到 Azure 登录页面。 So now the Angular app has the required token to send along to my asp backend.因此,现在 Angular 应用程序具有发送到我的 asp 后端所需的令牌。 My backend receives the token along with an API request.我的后端接收令牌和 API 请求。 backend checks token & responds to the API call.后端检查令牌并响应 API 调用。

PROBLEM问题

When making the API call, I get redirected to the login page, but after logging in. I get this error .进行 API 调用时,我被重定向到登录页面,但在登录后。我收到此错误

After I log in, I receive a valid token from azure via the URL: http://localhost:4200/#id_token= << TOKEN >>登录后,我通过 URL 从 azure 收到一个有效令牌: http://localhost:4200/#id_token= << TOKEN >>

These are the headers from the request found in the network tab in my browser.这些是在我的浏览器的网络选项卡中找到的请求的标头

Not sure about this, but I don't see any tokens passed in those headers.对此不确定,但我没有看到这些标头中传递的任何令牌。 Although I'm using HTTP INTERCEPTORS to add the token to my headers of each request.尽管我使用 HTTP INTERCEPTORS 将令牌添加到每个请求的标头中。 Can this be the problem?这可能是问题吗?

MY CODE我的代码

Backend后端

Startup.cs启动文件

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //other config services


        services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
            .AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));

        services.AddCors((opt =>
        {
            opt.AddPolicy("FrontEnd", builder => builder
                            .WithOrigins("http://localhost:4200")
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials()
                        );
        }));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //other configurations

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseCors("FrontEnd");

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });


    }
}

Simple API简单的API

[Route("api/[controller]")]
[ApiController]
[EnableCors("FrontEnd")]
[Authorize]
public class GezinnenController : ControllerBase
{
    //Constructor & properties

    // GET: api/Gezinnen
    [HttpGet]
    public async Task<ActionResult<IEnumerable<GezinForLijstDto>>> GetGezinnen()
    {
        var gezinnen = await _unitOfWork.GezinRepo.GetAllAsync(null, "Personen,Gemeente");

        var gezinnenForLijstDto = _mapper.Map<IEnumerable<GezinForLijstDto>>(gezinnen);

        return Ok(gezinnenForLijstDto);
    }

Angular

App.module.ts应用模块.ts

  import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
  import { MsalModule, MsalInterceptor } from '@azure/msal-angular';
  //other imports

  export const protectedResourceMap:
     [string, string[]][] = [['https://localhost:5001/api/gezinnen', ['api://<<API Client ID>>/api-access']] ];

  @NgModule({
     declarations: [
        ...
     ],
     imports: [
        ...
        MsalModule.forRoot({
           clientID: '<<Frontend Client ID>>',
           authority: 'https://login.microsoftonline.com/<<API tenant ID>>',
           consentScopes: [ 'user.read', 'api://<<API Client ID>>/api-access' ],
           protectedResourceMap: protectedResourceMap }),
     ],
     providers: [
        {
        provide: HTTP_INTERCEPTORS,
        useClass: MsalInterceptor,
        multi: true
     }],
     bootstrap: [
        AppComponent
     ]
  })
  export class AppModule { }

Can someone help me fix this?有人可以帮我解决这个问题吗? I'm starting to get desperate :-)我开始绝望了:-)

Workround:解决方法:

1.Modify the server to add the header Access-Control-Allow-Origin: * to enable cross-origin requests from anywhere (or specify a domain instead of *). 1.修改服务器添加头Access-Control-Allow-Origin: *以启用来自任何地方的跨域请求(或指定域而不是 *)。 This should solve your problem.这应该可以解决您的问题。

2.Using Angular proxy 2.使用Angular 代理

For more details, you could refer to this article .更多细节,你可以参考这篇文章

要解决 CORS 错误,在您的 startup.cs 中,您能否将 app.UseCors("FrontEnd") 移动到 app.UseAuthentication() 上方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Azure AD的Azure API APP身份验证 - Azure API APP authentication using Azure AD 从 Azure App Service(NuGet.Server) 添加 NuGet server with AD Authentication results 401 unauthorized in VS2019 proffesional - Adding NuGet server from Azure App Service(NuGet.Server) with AD Authentication results 401 unauthorized in VS2019 proffesional Azure AD集成身份验证 - Azure AD Integrated Authentication 使用 Azure AD 身份验证在 Blazor 应用程序上获取未配置的回复 URL 错误 - Getting an unconfigured reply URL error on Blazor App with Azure AD authentication 在 Azure AD 保护的自定义 REST API 的情况下,MSAL 是否能够维护令牌缓存并在令牌即将到期时为你刷新令牌 - Will MSAL be able to maintain a token cache and refreshes tokens for you when they are close to expire in case of Custom REST API secured by Azure AD 使用Azure AD身份验证的自定义授权 - Custom authorization with Azure AD authentication 应用程序之间的Azure AD身份验证 - Azure AD authentication between applications 针对Azure AD的WebForms身份验证 - WebForms authentication against Azure AD Alexa技能和Azure AD身份验证 - Alexa skill and Azure AD authentication Azure AD身份验证以及Passport身份验证 - Azure AD Authentication alongwith Passport Authentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM