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