CookieAuthenticationOptions类 (MVC身份验证)

定义与介绍

using Microsoft.Owin;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Security;
using System;
 
namespace Microsoft.Owin.Security.Cookies
{
    // 摘要: 
    //     包含由cookiesauthenticationmiddleware使用的选项
    public class CookieAuthenticationOptions : AuthenticationOptions
    {
        // 摘要: 
        //    创建与默认值初始化的选项的一个实例
        public CookieAuthenticationOptions();
 
        // 摘要: 
        //     确定用于创建的cookie的域。不提供默认。
        public string CookieDomain { get; set; }
        //
        // 摘要: 
        //确定是否浏览器应该允许由客户端JavaScript来访问该cookie。默认值是true,
        //这意味着该cookie将只通过HTTP请求,而不是提供给脚本的页面上。
        public bool CookieHttpOnly { get; set; }
        //
        // 摘要: 
        // 确定用于保存标识cookie名称。默认值是“.AspNet.Cookies”。
        // 如果你改变了AuthenticationType的名称,这个值应该被改变,特别是如果你的系统使用cookie认证中间件多次。
        public string CookieName { get; set; }
        //
        // 摘要: 
        //确定用于创建cookie中的路径。默认值是“/”为最高的浏览器兼容性。
        public string CookiePath { get; set; }
        //
        // 摘要: 
        //确定是否饼干应只对HTTPS请求转交。默认是限制cookie来HTTPS请求,
        //如果这是在做签到的页面也HTTPS。如果你有一个HTTPS登录页面和网站的部分是HTTP,您可能需要修改这个值。
        public CookieSecureOption CookieSecure { get; set; }
        //
        // 摘要: 
        //控制cookie将多少时间留在其创建点有效。到期信息是受保护的cookie票。
        //正因为如此,即使它被传递给服务器过期cookie将被忽略后浏览器应该清除它
        public TimeSpan ExpireTimeSpan { get; set; }
        //
        // 摘要: 
        //该LoginPath属性通知,它应该改变传出401 Unauthorized状态码为302重定向到指定的登录路径中间件。        
        //将产生的401的当前的URL被添加到LOGINPATH作为命名由ReturnUrlParameter查询字符串参数。
        //一旦请求到LOGINPATH赋予一个新的登入标识,ReturnUrlParameter值用于浏览器重定向回造成原始未经授权的状态码的网址。
        //如果LoginPath为null或空,中间件也不会去找401 Unauthorized状态码,并在登录时它不会自动重定向。
        public PathString LoginPath { get; set; }
        //
        // 摘要: 
        //如果LogoutPath设置在中间件然后一个请求发送到该路径将重定向基于所述ReturnUrlParameter。
        public PathString LogoutPath { get; set; }
        //
        // 摘要: 
        //提供者可以被分配给由在启动时所述应用程序创建的对象的实例。
        //中间件呼吁提供这给在某些地方应用控制在哪里处理正在发生的方法。 
        //如果它不提供的默认实例被提供其中不执行任何时调用方法。
        public ICookieAuthenticationProvider Provider { get; set; }
        //
        // 摘要: 
        //所述ReturnUrlParameter确定其由中间件所附当一个401 Unauthorized状态码被改变成302重定向到登录路径查询字符串参数的名称。
        //这也是查询字符串参数看起来当一个请求到达该登录路径或注销路径上,为了执行该操作后,返回到原来的URL的。
        public string ReturnUrlParameter { get; set; }
        //
        // 摘要: 
        //该SlidingExpiration设置为true,以指示中间件到一个新的到期时间重新发一个新的Cookie它处理一个请求是超过一半的过期窗口中的任何时间。
        public bool SlidingExpiration { get; set; }
        //
        // 摘要: 
        //该SystemClock提供访问系统的当前时间坐标。如果它不提供的默认实例被用于其中要求DateTimeOffset.UtcNow。
        //这通常是不会被替换,除非进行单元测试。
        public ISystemClock SystemClock { get; set; }
        //
        // 摘要: 
        //所述TicketDataFormat用于保护和不保护的身份和被存储在cookie值等性能。
        //如果它不提供一个缺省数据处理程序是使用包含在数据保护服务创建在IAppBuilder.Properties。
        //在ASP.NET运行时,默认的数据保护服务是基于计算机密钥,并DPAPI在不同的进程中运行时。
        public ISecureDataFormat<AuthenticationTicket> TicketDataFormat { get; set; }
    }
}


 

using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
 
namespace MVC50
{
    public partial class Startup
    {
        // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // 使应用程序可以使用 Cookie 来存储已登录用户的信息
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
 
            // 取消注释以下行可允许使用第三方登录提供程序登录
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");
 
            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");
 
            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");
 
            // 支持使用 google 账户登录
            app.UseGoogleAuthentication();
        }
    }
}

认证过程:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C# MVC中,可以通过使用ASP.NET Identity来实现登录验证。具体步骤如下: 1. 在Visual Studio中创建一个新的MVC项目。 2. 在NuGet包管理器中安装Microsoft.AspNet.Identity.Core和Microsoft.AspNet.Identity.EntityFramework。 3. 在Models文件夹中创建一个名为ApplicationUser.cs的类,该类继承自IdentityUser类。 4. 在DbContext类中添加以下代码以启用Identity: ``` public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } ``` 5. 在Startup.cs文件中添加以下代码以配置Identity: ``` public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); } ``` 6. 在AccountController.cs文件中添加以下代码以处理登录: ``` [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindAsync(model.UserName, model.Password); if (user != null) { await SignInAsync(user, model.RememberMe); return RedirectToLocal(returnUrl); } else { ModelState.AddModelError("", "Invalid username or password."); return View(model); } } ``` 7. 在Views文件夹中创建一个名为Login.cshtml的视图,该视图包含登录表单。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值