Use Forms Authentication in an ASP.NET Core application

0

I'm migrating an ASP.NET Web site (.NET Framework 4.7) to ASP.NET Core (but still using .NET 4.7 as a "target framework" ) - The goal is to use Razor Pages, dependency injection, and other resources present in Core while maintaining more "transparent" compatibility with existing .NET Framework libraries (own and third-party).

My question is regarding ASP.NET Full specific web features like Forms Authentication , I simply tried to add a web.config file and the default configuration data:

<authentication mode="Forms">
  <forms name=".ASPXAUTH" loginUrl="/Conta/Login" defaultUrl="/PaginaInicial" (...) />
</authentication>

But a simple FormsAuthentication.SignOut(); already returns an error since the web.config settings apparently do not load - FormsAuthentication.LoginUrl for example is set to the default value.

  

You can not use FormsAuthentication in the same ASP.NET Core   setting the Target Framework for NET47 ?

What would be the alternative in this case? Is there a similar simple authentication feature in Core?

    
asked by anonymous 25.08.2018 / 00:30

1 answer

0

I just answered my own questions:

  

You can not use FormsAuthentication in the same ASP.NET Core   setting the Target Framework for NET47?

No , directly using the FormsAuthentication class. But just configure manually, here is an example of how my configuration was:

In the project, make sure the following libraries are referenced (the easiest method is to edit csproj):

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.CookiePolicy" Version="2.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.DataProtection.SystemWeb" Version="2.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.HttpsPolicy" Version="2.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="2.1.1" />    
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.1" />
</ItemGroup>

In Startup.cs, modify:

    public void ConfigureServices(IServiceCollection services)
    {
        //(...)

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(opt =>
            {
                opt.LoginPath = new PathString("/Conta/Login");
                opt.LogoutPath = new PathString("/Conta/Logout");
                opt.AccessDeniedPath = new PathString("/Erros/AcessoNegado");
                opt.Cookie = new CookieBuilder()
                {
                    Name = ".NomeCookie",
                    Expiration = new System.TimeSpan(0, 120, 0),
                    //Se tiver um domínio...
                    //Domain = ".site.com.br",
                };
            });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //(...)

        app.UseCookiePolicy();
        app.UseAuthentication();

        //(...)                            

        app.UseMvc();
    }

With this, just use the [Authorize] attribute in a Page / Action that requires authentication and in another Login Page / Action implement the authentication logic, eg:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    (...)

   //Sua rotina de autenticação ... 
   var user = await AuthenticateUser(Input.Email, Input.Password);
   if (user == null)
   {
       ModelState.AddModelError(string.Empty, "Invalid login attempt.");
       return Page();
   }

   //Defina pelo menos um conjunto de claims...
   var claims = new List<Claim>
   {
       //Atributos do usuário ...
       new Claim(ClaimTypes.Name, user.Email),
       new Claim(ClaimTypes.Role, "Administrator"),
       new Claim("Nome", user.FullName),                    
   };

   var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

   var authProperties = new AuthenticationProperties
   {
       IsPersistent = true               
   };

   //Loga de fato
   await HttpContext.SignInAsync(
         CookieAuthenticationDefaults.AuthenticationScheme, 
         new ClaimsPrincipal(claimsIdentity), 
         authProperties
   );

   //Redireciona para a url desejada...
   return LocalRedirect(returnUrl);
}
    
27.08.2018 / 22:09