CORS error when adding Azure AD authentication












0














Trying to add Azure AD authentication to an Angular 7 webapp with a .net core 2.1 backend.



However, I get the CORS error during the request.



"Access to XMLHttpRequest at 'https://login.microsoftonline.com/.......' (redirected from 'https://localhost:5001/api/auth/login') from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."



So I tried adding some CORS policy in the startup pipe-line.



Startup.cs



        public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(config => config
.AddPolicy("SiteCorsPolicy", builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
)
); // <--- CORS policy - allow all for now

services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.Authority = "https://login.microsoftonline.com/MY_AD_DOMAIN.onmicrosoft.com"; // ad domain
options.ClientId = "my_client_id"; // client guid
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = "/auth/signin-callback";
options.SignedOutRedirectUri = "https://localhost:5000";
options.TokenValidationParameters.NameClaimType = "name";
}).AddCookie();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}

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

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseCors("SiteCorsPolicy"); // <--- CORS policy
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});

app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}


angular auth service



login() {        
const url = this.baseUrl + "api/auth/login";
this._http.get(url).subscribe(response => {
console.log(response);
});
}


Or am I going the wrong way about it? Should I use some third pary "ADAL" npm package (https://www.npmjs.com/package/adal-angular) to extract the token from the client side and then pass the token to the server for validation?



If I navigate to the login URL, e.g: localhost:5000/api/auth/login --> I get set off to the AAD login page, and redirected back at successful authentication. But if I trigger it from code, I get the CORS error.










share|improve this question
























  • is your xhr configured withCredentials bc that doesn't work with cookies
    – Daniel A. White
    Nov 19 at 16:11










  • @DanielA.White I don't think so, how do I check that?
    – Henkolicious
    Nov 19 at 16:13
















0














Trying to add Azure AD authentication to an Angular 7 webapp with a .net core 2.1 backend.



However, I get the CORS error during the request.



"Access to XMLHttpRequest at 'https://login.microsoftonline.com/.......' (redirected from 'https://localhost:5001/api/auth/login') from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."



So I tried adding some CORS policy in the startup pipe-line.



Startup.cs



        public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(config => config
.AddPolicy("SiteCorsPolicy", builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
)
); // <--- CORS policy - allow all for now

services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.Authority = "https://login.microsoftonline.com/MY_AD_DOMAIN.onmicrosoft.com"; // ad domain
options.ClientId = "my_client_id"; // client guid
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = "/auth/signin-callback";
options.SignedOutRedirectUri = "https://localhost:5000";
options.TokenValidationParameters.NameClaimType = "name";
}).AddCookie();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}

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

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseCors("SiteCorsPolicy"); // <--- CORS policy
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});

app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}


angular auth service



login() {        
const url = this.baseUrl + "api/auth/login";
this._http.get(url).subscribe(response => {
console.log(response);
});
}


Or am I going the wrong way about it? Should I use some third pary "ADAL" npm package (https://www.npmjs.com/package/adal-angular) to extract the token from the client side and then pass the token to the server for validation?



If I navigate to the login URL, e.g: localhost:5000/api/auth/login --> I get set off to the AAD login page, and redirected back at successful authentication. But if I trigger it from code, I get the CORS error.










share|improve this question
























  • is your xhr configured withCredentials bc that doesn't work with cookies
    – Daniel A. White
    Nov 19 at 16:11










  • @DanielA.White I don't think so, how do I check that?
    – Henkolicious
    Nov 19 at 16:13














0












0








0







Trying to add Azure AD authentication to an Angular 7 webapp with a .net core 2.1 backend.



However, I get the CORS error during the request.



"Access to XMLHttpRequest at 'https://login.microsoftonline.com/.......' (redirected from 'https://localhost:5001/api/auth/login') from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."



So I tried adding some CORS policy in the startup pipe-line.



Startup.cs



        public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(config => config
.AddPolicy("SiteCorsPolicy", builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
)
); // <--- CORS policy - allow all for now

services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.Authority = "https://login.microsoftonline.com/MY_AD_DOMAIN.onmicrosoft.com"; // ad domain
options.ClientId = "my_client_id"; // client guid
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = "/auth/signin-callback";
options.SignedOutRedirectUri = "https://localhost:5000";
options.TokenValidationParameters.NameClaimType = "name";
}).AddCookie();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}

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

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseCors("SiteCorsPolicy"); // <--- CORS policy
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});

app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}


angular auth service



login() {        
const url = this.baseUrl + "api/auth/login";
this._http.get(url).subscribe(response => {
console.log(response);
});
}


Or am I going the wrong way about it? Should I use some third pary "ADAL" npm package (https://www.npmjs.com/package/adal-angular) to extract the token from the client side and then pass the token to the server for validation?



If I navigate to the login URL, e.g: localhost:5000/api/auth/login --> I get set off to the AAD login page, and redirected back at successful authentication. But if I trigger it from code, I get the CORS error.










share|improve this question















Trying to add Azure AD authentication to an Angular 7 webapp with a .net core 2.1 backend.



However, I get the CORS error during the request.



"Access to XMLHttpRequest at 'https://login.microsoftonline.com/.......' (redirected from 'https://localhost:5001/api/auth/login') from origin 'https://localhost:5001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."



So I tried adding some CORS policy in the startup pipe-line.



Startup.cs



        public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(config => config
.AddPolicy("SiteCorsPolicy", builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials()
)
); // <--- CORS policy - allow all for now

services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.Authority = "https://login.microsoftonline.com/MY_AD_DOMAIN.onmicrosoft.com"; // ad domain
options.ClientId = "my_client_id"; // client guid
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.CallbackPath = "/auth/signin-callback";
options.SignedOutRedirectUri = "https://localhost:5000";
options.TokenValidationParameters.NameClaimType = "name";
}).AddCookie();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}

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

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseCors("SiteCorsPolicy"); // <--- CORS policy
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});

app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}


angular auth service



login() {        
const url = this.baseUrl + "api/auth/login";
this._http.get(url).subscribe(response => {
console.log(response);
});
}


Or am I going the wrong way about it? Should I use some third pary "ADAL" npm package (https://www.npmjs.com/package/adal-angular) to extract the token from the client side and then pass the token to the server for validation?



If I navigate to the login URL, e.g: localhost:5000/api/auth/login --> I get set off to the AAD login page, and redirected back at successful authentication. But if I trigger it from code, I get the CORS error.







angular azure-active-directory angular7 .net-core-2.1






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 6 at 10:02









Goncalo Peres

1,3261318




1,3261318










asked Nov 19 at 16:09









Henkolicious

5819




5819












  • is your xhr configured withCredentials bc that doesn't work with cookies
    – Daniel A. White
    Nov 19 at 16:11










  • @DanielA.White I don't think so, how do I check that?
    – Henkolicious
    Nov 19 at 16:13


















  • is your xhr configured withCredentials bc that doesn't work with cookies
    – Daniel A. White
    Nov 19 at 16:11










  • @DanielA.White I don't think so, how do I check that?
    – Henkolicious
    Nov 19 at 16:13
















is your xhr configured withCredentials bc that doesn't work with cookies
– Daniel A. White
Nov 19 at 16:11




is your xhr configured withCredentials bc that doesn't work with cookies
– Daniel A. White
Nov 19 at 16:11












@DanielA.White I don't think so, how do I check that?
– Henkolicious
Nov 19 at 16:13




@DanielA.White I don't think so, how do I check that?
– Henkolicious
Nov 19 at 16:13












1 Answer
1






active

oldest

votes


















2














Your approach is a bit wrong.
You've configured OIDC + Cookies, yet want to call it with an XHR.



The typical approach would be to:




  • Configure JWT Bearer token authentication on the API

  • Use ADAL/MSAL on the front-end to authenticate the user + acquire an access token for the back-end

  • Attach the access token to XHRs so they are authenticated


Some samples/articles that may help:




  • https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi

  • https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-angular/samples/MSALAngularDemoApp

  • https://github.com/azure-samples/active-directory-dotnet-native-aspnetcore-v2

  • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1

  • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2


Keep in mind ADAL can only be used with the AAD v1 endpoint and MSAL with the v2 endpoint.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378607%2fcors-error-when-adding-azure-ad-authentication%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Your approach is a bit wrong.
    You've configured OIDC + Cookies, yet want to call it with an XHR.



    The typical approach would be to:




    • Configure JWT Bearer token authentication on the API

    • Use ADAL/MSAL on the front-end to authenticate the user + acquire an access token for the back-end

    • Attach the access token to XHRs so they are authenticated


    Some samples/articles that may help:




    • https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi

    • https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-angular/samples/MSALAngularDemoApp

    • https://github.com/azure-samples/active-directory-dotnet-native-aspnetcore-v2

    • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1

    • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2


    Keep in mind ADAL can only be used with the AAD v1 endpoint and MSAL with the v2 endpoint.






    share|improve this answer


























      2














      Your approach is a bit wrong.
      You've configured OIDC + Cookies, yet want to call it with an XHR.



      The typical approach would be to:




      • Configure JWT Bearer token authentication on the API

      • Use ADAL/MSAL on the front-end to authenticate the user + acquire an access token for the back-end

      • Attach the access token to XHRs so they are authenticated


      Some samples/articles that may help:




      • https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi

      • https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-angular/samples/MSALAngularDemoApp

      • https://github.com/azure-samples/active-directory-dotnet-native-aspnetcore-v2

      • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1

      • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2


      Keep in mind ADAL can only be used with the AAD v1 endpoint and MSAL with the v2 endpoint.






      share|improve this answer
























        2












        2








        2






        Your approach is a bit wrong.
        You've configured OIDC + Cookies, yet want to call it with an XHR.



        The typical approach would be to:




        • Configure JWT Bearer token authentication on the API

        • Use ADAL/MSAL on the front-end to authenticate the user + acquire an access token for the back-end

        • Attach the access token to XHRs so they are authenticated


        Some samples/articles that may help:




        • https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi

        • https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-angular/samples/MSALAngularDemoApp

        • https://github.com/azure-samples/active-directory-dotnet-native-aspnetcore-v2

        • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1

        • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2


        Keep in mind ADAL can only be used with the AAD v1 endpoint and MSAL with the v2 endpoint.






        share|improve this answer












        Your approach is a bit wrong.
        You've configured OIDC + Cookies, yet want to call it with an XHR.



        The typical approach would be to:




        • Configure JWT Bearer token authentication on the API

        • Use ADAL/MSAL on the front-end to authenticate the user + acquire an access token for the back-end

        • Attach the access token to XHRs so they are authenticated


        Some samples/articles that may help:




        • https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi

        • https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/lib/msal-angular/samples/MSALAngularDemoApp

        • https://github.com/azure-samples/active-directory-dotnet-native-aspnetcore-v2

        • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1

        • https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2


        Keep in mind ADAL can only be used with the AAD v1 endpoint and MSAL with the v2 endpoint.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 6:47









        juunas

        21k34477




        21k34477






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378607%2fcors-error-when-adding-azure-ad-authentication%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]