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中:

1
2
3
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>

 

posted @   乁卬杨  阅读(335)  评论(0)    收藏  举报
点击右上角即可分享
微信分享提示