zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    JavaScript 垃圾回收
    JavaScript 跳坑指南
    javaScript AJAX
    高效 JavaScript
    Java使用 Thumbnails 压缩图片
    Vue前端压缩图片
    JS input输入框字数超出长度显示省略号.....
    Vue图片浏览组件vviewer使用
    浏览器获取京东cookie
    图片在容器内水平垂直居中显示
  • 原文地址:https://www.cnblogs.com/ybst/p/9242334.html
Copyright © 2011-2022 走看看