public interface IAuthenticationService { TaskAuthenticateAsync(HttpContext context, string scheme); }
public class MyController : ControllerBase { private readonly IAuthenticationService _authenticationService; public MyController(IAuthenticationService authenticationService) { _authenticationService = authenticationService; } [HttpPost("login")] public async TaskThis code example shows how to use the AuthenticateAsync method with the Cookie authentication scheme to sign in and sign out a user. It first authenticates the user credentials and then creates user claims, authentication ticket, and finally signs in the user using the IAuthenticationService SignInAsync method. The Logout method signs out the user using the IAuthenticationService SignOutAsync method. Package: Microsoft.AspNetCore.Authentication.Cookiess.Login() { // authenticate user credentials var user = await _userService.AuthenticateAsync(username, password); // create user claims var claims = new List { new Claim(ClaimTypes.Name, user.Username), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Role, user.Role) }; // create authentication ticket var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); var properties = new AuthenticationProperties { IsPersistent = true }; var ticket = new AuthenticationTicket(principal, properties, CookieAuthenticationDefaults.AuthenticationScheme); // sign in user await _authenticationService.SignInAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme, ticket); return Ok(); } [HttpPost("logout")] public async Task Logout() { await _authenticationService.SignOutAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme); return Ok(); } }