Use Forms Authentication in an ASP.NET Core application

Asked

Viewed 1,023 times

0

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

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

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

But a simple one FormsAuthentication.SignOut(); already returns an error since the settings of web.config are apparently not loaded - the FormsAuthentication.LoginUrl for example is with the default value.

There’s no way to use Formsauthentication on ASP.NET Core itself configuring the Target Framework for NET47 ?

What would be the alternative in this case? There is a similar simple authentication feature in Core?

1 answer

2


I ended up answering my own questions:

There is no way to use Formsauthentication in ASP.NET Core anyway setting up the Target Framework for NET47 ?

Not, using directly the Formsauthentication class no. But just configure manually, follow example of how my configuration turned out:

In the project, certify that the following libraries are referenced (easiest method is to edit the 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 that just use the attribute [Authorize] on a Page/Action that requires authentication and on another Page/Login Action implement the authentication logic, example:

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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.