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

2019-03-21 10:40:43 浏览数 (1)

在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

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

0 人点赞