'.net core 5.0 Outlook authorization Login Error

I have a .Net Core 5.0 project and I am trying to login to outlook application with this project. The purpose of the project is to get the calendar List, schedule work, etc. But when I try to login I get the following error. What is the reason? My codes are below and I have ClientId and TenantId taken from Outlook account. With my Localhost address given in the RedirectUrl part of the Outlook account.(http://localhost:5000)

Startup.cs

   using Microsoft.AspNetCore.Authentication.OpenIdConnect;
   using Microsoft.AspNetCore.Authorization;
   using Microsoft.AspNetCore.Builder;
   using Microsoft.AspNetCore.Hosting;
   using Microsoft.AspNetCore.Http;
   using Microsoft.Extensions.Configuration;
   using Microsoft.Extensions.DependencyInjection;
   using Microsoft.Extensions.Hosting;
   using Microsoft.Identity.Web;
   using Microsoft.OpenApi.Models;
   using System.Threading.Tasks;

 namespace EvetOutlookAPI
{
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(options => {
                this.Configuration.GetSection("AzureAd").Bind(options);
                options.Events.OnRedirectToIdentityProvider = context => {
                    if (context.HttpContext.Items.ContainsKey("allowRedirect"))
                    {
                        return Task.CompletedTask;
                    }
                    context.HandleResponse();
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    return Task.CompletedTask;
                };
            });

        services.AddAuthorization(options => {
            options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
        });


        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "EvetOutlookAPI", Version = "v1" });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "EvetOutlookAPI v1"));
        }

        app.UseCors(policyBuilder => 
   policyBuilder.AllowCredentials().SetIsOriginAllowed(origin => 
  true).AllowAnyHeader().WithExposedHeaders("Location"));
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints => {
            endpoints.MapControllers();
        });
    }
}
}

appsettings.json

{
  "AzureAd": {
   "Instance": "https://login.microsoftonline.com/",
   "Domain": "https://dev.azure.com/",
   "ClientId": "***********",
   "TenantId": "*************",
   "CallbackPath": "/signin-oidc"
 },
 "Logging": {
 "LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
}
 },
 "AllowedHosts": "*"

}

Controller;

 using Microsoft.AspNetCore.Authentication;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Mvc;
 using System.Threading.Tasks;

 namespace EvetOutlookAPI.Controllers
{
 [Route("api/[controller]")]
 [ApiController]
 public class LoginController : Controller
 {
    [HttpGet]
    public ActionResult IsUserLoggedIn()
    {
        if (!this.HttpContext.User.Identity.IsAuthenticated)
        {
            return this.Unauthorized();
        }

        return this.Accepted();
    }

    [HttpGet("Authenticate")]
    public async Task Login()
    {
        if (!this.HttpContext.User.Identity.IsAuthenticated)
        {
            this.HttpContext.Items.Add("allowRedirect", true);
            await this.HttpContext.ChallengeAsync();
            return;
        }

        this.HttpContext.Response.Redirect("http://localhost:5000");
    }
   }
 }

enter image description here enter image description here



Solution 1:[1]

Maybe the reason is cookies were not being set as secure.

By default, when the OIDC middleware middle generates its correlation cookie (and nonce) cookies, it sets the "SameSite" property to "None". Try using SameSiteMode.Lax.

Another way if you're using Chrome against localhost, you may have run into a change in Chrome cookie-handling behavior.

To verify, navigate to chrome://flags/ and change "Cookies without SameSite must be secure" to "Disabled".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Qing Guo