zoukankan      html  css  js  c++  java
  • asp.net core中使用cookie身份验证

    配置

    在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务:

    services.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    // Cookie settings
                    options.Cookie.HttpOnly = true;
                    options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
    
                    options.LoginPath = "/Account/Login";
                    options.AccessDeniedPath = "/Account/AccessDenied";
                    options.SlidingExpiration = true;
                });

    AuthenticationScheme 传递到 AddAuthentication 设置应用程序的默认身份验证方案。 如果有多个 cookie 身份验证实例,并且你想要使用特定方案进行授权,AuthenticationScheme 会很有用。 将 AuthenticationScheme 设置为CookieAuthenticationDefaults。 AuthenticationScheme为方案提供值 "cookie"。 可以提供任何用于区分方案的字符串值。
    应用的身份验证方案不同于应用的 cookie 身份验证方案。 如果未向 AddCookie提供 cookie 身份验证方案,则使用 CookieAuthenticationDefaults.AuthenticationScheme ("Cookie")。
    默认情况下,身份验证 cookie 的 IsEssential 属性设置为 true。 当站点访问者未同意数据收集时,允许使用身份验证 cookie。 


    在 Startup.Configure中,调用 UseAuthentication 和 UseAuthorization 设置 HttpContext.User 属性,并为请求运行授权中间件。 调用 UseEndpoints之前调用 UseAuthentication 和 UseAuthorization 方法:

    app.UseCookiePolicy();
    app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints
    => {   endpoints.MapControllers();   endpoints.MapRazorPages(); });

    登录

    若要创建保存用户信息的 cookie,请构造一个 ClaimsPrincipal。 将对用户信息进行序列化并将其存储在 cookie 中。
    使用任何所需的 Claim创建 ClaimsIdentity,并调用 SignInAsync 以登录用户:

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

    SignInAsync 创建加密的 cookie,并将其添加到当前响应中。 如果未指定 AuthenticationScheme,则使用默认方案。
    ASP.NET Core 的数据保护系统用于加密。 对于托管在多台计算机上的应用程序、跨应用程序或使用 web 场进行负载平衡,请将数据保护配置为使用相同的密钥环和应用程序标识符。

    注销

    若要注销当前用户并删除其 cookie,请调用 SignOutAsync:

    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    如果 CookieAuthenticationDefaults.AuthenticationScheme (或 "Cookie")不用作方案(例如 "ContosoCookie"),请提供配置身份验证提供程序时所使用的方案。 否则,将使用默认方案。

  • 相关阅读:
    文件夹生成zip
    html 字符串 生成 pdf 完美解决中文不显示
    layui 数据表格+分页+搜索+checkbox+缓存选中项数据
    排序算法总结
    排序算法(10)--Distribution Sorting--分布排序[2]--Radix Sort--基数排序
    排序算法(8)--Merge Sorting--归并排序--Merge sort--归并排序
    [Android]在Dagger 2中使用RxJava来进行异步注入(翻译)
    [Android]使用Dagger 2进行依赖注入
    [Android]Android端ORM框架——RapidORM(v2.1)
    [Android]使用MVP解决技术债务(翻译)
  • 原文地址:https://www.cnblogs.com/oyang168/p/11966118.html
Copyright © 2011-2022 走看看