前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >.Net Core系列教程(四)—— 基础身份认证

.Net Core系列教程(四)—— 基础身份认证

作者头像
徐大嘴
发布2019-03-21 10:40:43
2.4K0
发布2019-03-21 10:40:43
举报
文章被收录于专栏:大嘴说编程

在ASP.NET 4.5及之前的版本,可以使用FormsAuthenticationTicket来做基础身份认证,现在到了.Net Core中,发现原来的FormsAuthenticationTicket不能用了,其实在.Net Core中,依然可以使用基础身份认证,下面是使用方法。因为这是在具体项目中使用的,会多出一些其他的代码,请自行忽略。

1.在Startup.cs文件中,public void ConfigureServices(IServiceCollection services)方法下添加:

代码语言:javascript
复制
services.AddAuthorization();

完整代码:

代码语言:javascript
复制
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddOptions();
            services.Configure<Models.ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
            services.AddAuthorization();    //Form基础验证
            services.AddMvc();
        }

2.在public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)方法下添加:

代码语言:javascript
复制
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookie",
                LoginPath = new PathString("/Manage/Login"),
                AccessDeniedPath = new PathString("/Manage/Forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true
            });

完整代码:

代码语言:javascript
复制
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            //Form基础验证
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookie",
                LoginPath = new PathString("/Manage/Login"),
                AccessDeniedPath = new PathString("/Manage/Forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true
            });
            app.UseApplicationInsightsRequestTelemetry();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseApplicationInsightsExceptionTelemetry();
            app.UseStaticFiles();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

如果发现有报错,添加引用即可。

3.在控制器文件中,登录的方法下,添加:

代码语言:javascript
复制
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,login.username) 
                    //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")  
                };
                //var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));
                var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, token));
                HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });

在我自己的项目中,完整的Login方法代码:

代码语言:javascript
复制
        [HttpPost]
        [ModelValidationFilter]
        public Models.ResultModel<object> Login(Models.Login login)
        {
            var result = new Models.ResultModel<object>();
            result = _manage.Login(login);            
            if(result.status)
            {//登录成功
                string token = result.data.ToString();  //登录成功后生成的token,用于验证登录有效性
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,login.username) 
                    //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com")  
                };
                //var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin"));
                var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, token));
                HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties
                {
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
                    IsPersistent = false,
                    AllowRefresh = false
                });
            }
            return result;
        }

4.在需要进行身份验证的控制器或Action上,添加Authorize特性,如:

加在Action上

代码语言:javascript
复制
        [Authorize]
        public IActionResult Dashboard()

或加在Controller上

代码语言:javascript
复制
    [Authorize]
    public class ManageSystemController : Controller

5.取验证信息

代码语言:javascript
复制
     var auth = await HttpContext.Authentication.GetAuthenticateInfoAsync("Cookie");
     string username = auth.Principal.Identity.Name;    //用户名

6.注销登录

代码语言:javascript
复制
    HttpContext.Authentication.SignOutAsync("Cookie");

具体可参考微软官方Demo:How to achieve a basic authorization in ASP.NET Core


本文作者:老徐

本文链接:https://cloud.tencent.com/developer/article/1405681

转载时须注明出处及本声明

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
多因子身份认证
多因子身份认证(Multi-factor Authentication Service,MFAS)的目的是建立一个多层次的防御体系,通过结合两种或三种认证因子(基于记忆的/基于持有物的/基于生物特征的认证因子)验证访问者的身份,使系统或资源更加安全。攻击者即使破解单一因子(如口令、人脸),应用的安全依然可以得到保障。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档