CORS issue when getting bearer token in ASP.net application

Caroline Henning 46 Reputation points
2022-02-01T06:42:43.227+00:00

I am trying to get a bearer token to make an azure rest api call in my ASP.net application. My http request works in postman, but not when I test with my application in localhost. With the fetch mode set to "cors", I get an error that the request has been blocked by CORS policy. With the fetch mode set to "no-cors", I get a Bad Request error. How can I get the bearer token in my application? I would like to get the token without a login popup if possible.

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,561 questions
0 comments No comments
{count} votes

Accepted answer
  1. Shweta Mathur 27,711 Reputation points Microsoft Employee
    2022-02-01T13:58:15.33+00:00

    Hi @Caroline Henning ,

    Thanks for reaching out.

    Here bad request can be due to 'Access-Control-Allow-Origin' header is not set. To allow specific headers to be sent in a CORS request, call WithHeaders and specify the allowed headers:

    builder =>
    {
    builder.WithOrigins("http://contoso.com")
    .WithHeaders(HeaderNames.ContentType, "x-custom-header");
    });

    Also, You can enable CORS through different ways in ASP.net application as disabling the CORS is not recommended for security reasons.

    1.Using a default policy in middleware
    2.With endpoint routing, CORS can be enabled on a per-endpoint basis using the RequireCors() in the middleware as
    3.With the [EnableCors] attribute in the controller class or controller action method as

    Ref : Enable CORS in ASP.NET application

    Thanks,
    Shweta


    Please remember to "Accept Answer" if answer helped you.


0 additional answers

Sort by: Most helpful