Cấp bậc tác giả:

DOTNET

Sử dụng xác thực cookie mà không cần ASP.NET Core Identity

Được viết bởi webmaster ngày 17/12/2023 lúc 04:28 PM
Xác thực(Authentication) là quá trình xác định danh tính của người dùng. Ủy quyền(Authorization) là quá trình xác định xem người dùng có quyền truy cập vào tài nguyên hay không.
  • 0
  • 1164

Sử dụng xác thực cookie mà không cần ASP.NET Core Identity

Xác thực(Authentication) là quá trình xác định danh tính của người dùng. Ủy quyền(Authorization) là quá trình xác định xem người dùng có quyền truy cập vào tài nguyên hay không. 
Trình xử lý xác thực đã đăng ký và các tùy chọn cấu hình được gọi là lược đồ(schemes).
Các lược đồ xác thực được chỉ định bằng cách đăng ký dịch vụ xác thực trong Program.cs:

Bằng cách gọi  phương thức tiện ích mở rộng dành riêng cho lược đồ sau lệnh gọi tới AddAuthentication, chẳng hạn như AddJwtBearer để đăng ký các lược đồ với cài đặt thích hợp dùngAuthenticationBuilder.AddScheme. Phương thức mở rộng này sử dụng AddCookie hoặc AddJwtBearer
Ít phổ biến hơn thì gọi trực tiếp AuthenticationBuilder.AddScheme.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme,
        options => builder.Configuration.Bind("JwtSettings", options))
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options => builder.Configuration.Bind("CookieSettings", options));

ASP.NET Core Identity là nhà cung cấp xác thực hoàn chỉnh, đầy đủ tính năng để tạo và duy trì thông tin đăng nhập. Tuy nhiên, có thể sử dụng nhà cung cấp xác thực dựa trên cookie không có ASP.NET Core Identity.

Thêm xác thực cookie
Thêm Authentication Middleware services bằng phương pháp AddAuthentication và AddCookie.
Gọi UseAuthentication và UseAuthentication để thiết lập thuộc tính HttpContext.User và chạy Authorization Middleware cho các yêu cầu. UseAuthentication và UseAuthorization phải gọi trước các phương thức ánh xạ(map) như MapRazorPages và MapDefaultControllerRoute

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

builder.Services.AddHttpContextAccessor();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.MapDefaultControllerRoute();

app.Run();
 
Cấu hình CookieAuthenticationOptions trong phương thức AddCookie
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
        options.SlidingExpiration = true;
        options.AccessDeniedPath = "/Forbidden/";
    });

Cookie Policy Middleware
UseCookiePolicy kích hoạt các chức năng của chính sách cookie. Middleware được xử lý theo thứ tự được thêm vào:
app.UseCookiePolicy(cookiePolicyOptions);
Sử dụng CookiePolicyOptions được cung cấp cho Cookie Policy Middleware để kiểm soát các đặc tính chung của quá trình xử lý cookie và kết nối với các trình xử lý xử lý cookie khi cookie được thêm hoặc xóa.

Tạo cookie xác thực

Để tạo cookie chứa thông tin người dùng, hãy tạo ClaimsPrincipal. Thông tin người dùng được tuần tự hóa và lưu trữ trong cookie.

Tạo ClaimsIdentity với bất kỳ Xác nhận quyền sở hữu bắt buộc nào và gọi SignInAsync để đăng nhập người dùng:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    ReturnUrl = returnUrl;

    if (ModelState.IsValid)
    {
        // Use Input.Email and Input.Password to authenticate the user
        // with your custom authentication logic.
        //
        // For demonstration purposes, the sample validates the user
        // on the email address maria.rodriguez@contoso.com with 
        // any password that passes model validation.

        var user = await AuthenticateUser(Input.Email, Input.Password);

        if (user == null)
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, user.Email),
            new Claim("FullName", user.FullName),
            new Claim(ClaimTypes.Role, "Administrator"),
        };

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

        var authProperties = new AuthenticationProperties
        {
            //AllowRefresh = <bool>,
            // Refreshing the authentication session should be allowed.

            //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
            // The time at which the authentication ticket expires. A 
            // value set here overrides the ExpireTimeSpan option of 
            // CookieAuthenticationOptions set with AddCookie.

            //IsPersistent = true,
            // Whether the authentication session is persisted across 
            // multiple requests. When used with cookies, controls
            // whether the cookie's lifetime is absolute (matching the
            // lifetime of the authentication ticket) or session-based.

            //IssuedUtc = <DateTimeOffset>,
            // The time at which the authentication ticket was issued.

            //RedirectUri = <string>
            // The full path or absolute URI to be used as an http 
            // redirect response value.
        };

        await HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme, 
            new ClaimsPrincipal(claimsIdentity), 
            authProperties);

        return LocalRedirect(Url.GetLocalUrl(returnUrl));
    }

    // Something failed. Redisplay the form.
    return Page();
}

SignInAsync tạo một cookie được mã hóa và thêm nó vào phản hồi hiện tại. Nếu AuthenticationScheme không được chỉ định thì lược đồ mặc định sẽ được sử dụng.

Sign out(Đăng xuất)
Để đăng xuất người dùng hiện tại và xóa cookie của họ, hãy gọi SignOutAsync:
public async Task OnGetAsync(string returnUrl = null)
{
    if (!string.IsNullOrEmpty(ErrorMessage))
    {
        ModelState.AddModelError(string.Empty, ErrorMessage);
    }

    // Clear the existing external cookie
    await HttpContext.SignOutAsync(
        CookieAuthenticationDefaults.AuthenticationScheme);

    ReturnUrl = returnUrl;
}

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML