Roberto Correia Roberto Correia - 1 month ago 12
C# Question

Custom url for authentication

Currently I have a project in ASP.NET Core with a simple authentication.

The main code was generated with Yeoman and generator-aspnet.

The generated code has a Account Controller to authenticate the users.

Every time a user needs to log, asp.net redirect the user to http://domain/Account/Login.

Because the primary language of this site it's not english, I like to change the url to something like this:
http://domain/usuarios/login

So, in Account Controller, I added a Route annotation on top of the class:

[Authorize]
[Route("usuarios")]
public class AccountController : Controller
{
...

[HttpGet]
[AllowAnonymous]
[Route("login")]
public IActionResult Login(string returnUrl = null)
{
...
}

[HttpPost]
[AllowAnonymous]
[ValidadeAntiForgeryToken]
[Route("login")]
public async Task<IActionResult> Login(LoginViewModel model, string returlUrl = null)
{
...
}
}


Now, if I go manually to http://domain/usuarios/login, the login page appears.
But, If I go to a page that need authentication, ASP.NET Core still redirect-me to http://domain/Account/Login and return a 404 error.

Checking the project.json, I see in dependencies section, the package:

"dependencies": {
"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
...
}


Opening the Startup class, I see in ConfigureServices and Configure methods the code
app.UseIdentity();
, but nothing about
app.UseCookieAuthentication()


Here is a part of Configure method:

app.UseStaticFiles();
app.UseIdentity();

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


So, where I update the code to redirect to the correctly url?

PS: the generated code it's a lot like https://shellmonger.com/2015/04/04/asp-net-vnext-identity-part-2-the-login-process/

Answer

if you are using cookie based authentication, update your startup.cs like this:

public void ConfigureServices(IServiceCollection services)
{       
    services.Configure<CookieAuthenticationOptions>(options =>
    {
        options.LoginPath = new PathString("/usuarios/login");
    });
}