NETCore MVC登录授权

1.需要在Startup ConfigureServices(IServiceCollection services)中 配置如下代码

 #region  //身份认证时需要使用的方法
            services.AddSession(options=> {
                options.Cookie.HttpOnly = true;
              
                options.Cookie.Name = ApplicationEnvironments.Site.CookieName;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.IdleTimeout = TimeSpan.FromMinutes(ApplicationEnvironments.Site.SessionTimeout);
            });
           
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.DataProtectionProvider= DataProtectionProvider.Create(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory+ "/shared-auth-ticket-keys/"));
                options.Cookie.Name = ApplicationEnvironments.Site.CookieName;
                options.Cookie.Path = "/";
                options.LoginPath = new PathString("/login");
                options.AccessDeniedPath = new PathString("/Forbidden"); //禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径。
               // options.SlidingExpiration = false;  //Cookie可以分为永久性的和临时性的。 临时性的是指只在当前浏览器进程里有效,浏览器一旦关闭就失效(被浏览器删除)。 永久性的是指Cookie指定了一个过期时间,在这个时间到达之前,此cookie一直有效(浏览器一直记录着此cookie的存在)。 slidingExpriation的作用是,指示浏览器把cookie作为永久性cookie存储,但是会自动更改过期时间,以使用户不会在登录后并一直活动,但是一段时间后却自动注销。也就是说,你10点登录了,服务器端设置的TimeOut为30分钟,如果slidingExpriation为false,那么10:30以后,你就必须重新登录。如果为true的话,你10:16分时打开了一个新页面,服务器就会通知浏览器,把过期时间修改为10:46。 更详细的说明还是参考MSDN的文档。
            });
            #endregion
services.MVC() .AddSessionStateTempDataProvider();

在Configure(IApplicationBuilder app, IHostingEnvironment env)添加如下代码

app.UseAuthentication();

在登录页面中调用如下代码


var claims = new List<Claim>()
{
   new Claim(ClaimTypes.Name,model.UserName) ,

  new Claim(ClaimTypes.NameIdentifier,model.UserId.ToString()
)

var Identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
Identity.AddClaims(claims);
          
            //init the identity instances 
var userPrincipal = new ClaimsPrincipal(Identity);  };
  await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
            {
                ExpiresUtc = DateTimeOffset.Now.AddMinutes(ApplicationEnvironments.Site.SessionTimeout),
                IsPersistent = true,
                AllowRefresh = true
            });

退出使用

HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme)

转载于:https://my.oschina.net/u/3049482/blog/2965015

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值