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

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

services.AddAuthorization();

完整代码:

        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)方法下添加:

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookie",
                LoginPath = new PathString("/Manage/Login"),
                AccessDeniedPath = new PathString("/Manage/Forbidden"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true
            });

完整代码:

        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.在控制器文件中,登录的方法下,添加:

                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方法代码:

        [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上

        [Authorize]
        public IActionResult Dashboard()

或加在Controller上

    [Authorize]
    public class ManageSystemController : Controller

5.取验证信息

     var auth = await HttpContext.Authentication.GetAuthenticateInfoAsync("Cookie");
     string username = auth.Principal.Identity.Name;    //用户名

6.注销登录

    HttpContext.Authentication.SignOutAsync("Cookie");

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

Last modification:May 15, 2018
如果觉得我的文章对你有用,请随意赞赏