• CORE MVC 自定义认证


    微软的认证体系,集成了EF,和它的表结构,对于我们已有的系统,或者想高度自定义的人,该怎么办呢?

    答案在: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.1&tabs=aspnetcore2x

    具体要点:

    1)Startup.ConfigureServices中:

    1 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    2     .AddCookie();

    2)Startup.Configure中:

                app.UseStaticFiles();
                app.UseCookiePolicy();
                app.UseAuthentication();
    

     

    3)登录成功后,调用这个方法:

     1         private async Task LoginSuccess(string userName )
     2         {
     3             var claims = new List<Claim>
     4             {
     5                 new Claim(ClaimTypes.Name, userName),
     6                 new Claim("FullName", "Test User"),
     7                 new Claim(ClaimTypes.Role, "Administrator"),
     8             };
     9 
    10             var claimsIdentity = new ClaimsIdentity(
    11                 claims, CookieAuthenticationDefaults.AuthenticationScheme);
    12 
    13             var authProperties = new AuthenticationProperties { };
    14 
    15             await HttpContext.SignInAsync(
    16                 CookieAuthenticationDefaults.AuthenticationScheme,
    17                 new ClaimsPrincipal(claimsIdentity),
    18                 authProperties);
    19         }

    以上代码 core mvc 2.1下测试用过。

    4)这样,在需要登录才能访问的地方加上:

    1     [Authorize]
    2     public class HomeController : Controller

    5)取用户名

    <h2>@this.Context.User.Identity.Name</h2>
  • 相关阅读:
    杜教筛
    单纯形法
    回文树
    模板综合
    不明觉厉的数据结构题2
    gedit脚本
    01分数规划入门
    LCT裸题泛做
    洛谷P4586 [FJOI2015]最小覆盖双圆问题(最小圆覆盖)
    洛谷P1742 最小圆覆盖(计算几何)
  • 原文地址:https://www.cnblogs.com/ybst/p/9242334.html
Copyright © 2020-2023  润新知