Search code examples
c#asp.net-coreasp.net-core-identity

Identity on ASP.NET Core(3.0) not functioning when using endpoints


When I use routes, Identity is functioning as expected.

    //Identity functions as expected:
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "areas",
            template: "{area:exists}/{controller=Home}/{action=Index}");
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

However, when I use endpoints, user is stuck in LogIn view (any attempt to access Action methods decorated with [Authorize] are redirected to my LogIn veiw, even after SignInResult succeeds).

// Identity not functioning when using endpoints:
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<ChatHub>("/chatHub");
    endpoints.MapControllerRoute(
        name: "areas",
        pattern: "{area:exists}/{controller=Home}/{action=Index}");
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

The rest of the app works fine using endpoints, my issue is only with Identity.


Solution

  • If the app uses authentication/authorization features such as AuthorizePage or [Authorize], place the call to UseAuthentication and UseAuthorization: after, UseRouting and UseCors, but before UseEndpoints

    public void Configure(IApplicationBuilder app)
    {
      ...
    
      app.UseStaticFiles();
    
      app.UseRouting();
      app.UseCors();
    
      app.UseAuthentication();
      app.UseAuthorization();
    
      app.UseEndpoints(endpoints => {
         endpoints.MapControllers();
      });
      ...
    }
    

    Please read this for more details