Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在MVC项目中验证OWIN中的令牌_C#_Asp.net Mvc_Authentication_Cookies_Owin - Fatal编程技术网

C# 如何在MVC项目中验证OWIN中的令牌

C# 如何在MVC项目中验证OWIN中的令牌,c#,asp.net-mvc,authentication,cookies,owin,C#,Asp.net Mvc,Authentication,Cookies,Owin,我有一个ASP.NETMVC项目,我正试图在其中集成OWIN身份验证。我觉得我快到了,但可能错过了几步。我的应用程序有MVC视图和一些旧的ASPX页面,以及几个Web API控制器。我有一个Startup.Auth.cs文件,其配置方法如下 public void Configuration(IAppBuilder app) { // add a signin manager to the OWIN context app.CreatePerOwi

我有一个ASP.NETMVC项目,我正试图在其中集成OWIN身份验证。我觉得我快到了,但可能错过了几步。我的应用程序有MVC视图和一些旧的ASPX页面,以及几个Web API控制器。我有一个Startup.Auth.cs文件,其配置方法如下

    public void Configuration(IAppBuilder app)
    {
        // add a signin manager to the OWIN context
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            CookieSecure = CookieSecureOption.SameAsRequest
        });
    }
public void配置(IAppBuilder应用程序)
{
//将登录管理器添加到OWIN上下文
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
//使应用程序能够使用cookie存储登录用户的信息
//配置登录cookie
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Account/Login”),
CookieSecure=CookieSecureOption.SameAsRequest
});
}
AccountController的登录方法如下所示:

    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }
    public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
    {
        var user = new ApplicationUser { Email = userName, UserName = userName, PasswordHash = password };

        var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Role, "user"));

        this.AuthenticationManager.SignIn(identity);
        return SignInStatus.Success;
    }
公共异步任务登录(LoginViewModel模型,字符串返回URL)
{
如果(!ModelState.IsValid)
{
返回视图(模型);
}
var result=wait SignInManager.PasswordSignInAsync(model.Email、model.Password、model.RememberMe、shouldllockout:false);
开关(结果)
{
案例标志状态成功:
返回重定向到本地(returnUrl);
案例标志状态锁定输出:
返回视图(“锁定”);
案例标志状态。要求验证:
return RedirectToAction(“SendCode”,new{ReturnUrl=ReturnUrl,RememberMe=model.RememberMe});
案例信号状态故障:
违约:
AddModelError(“,”登录尝试无效“);
返回视图(模型);
}
}
PasswordSignInAsync方法最终将在LDAP中查找用户凭据,但为了简化,我认为任何输入都可以成功启动。方法如下所示:

    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }
    public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
    {
        var user = new ApplicationUser { Email = userName, UserName = userName, PasswordHash = password };

        var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Role, "user"));

        this.AuthenticationManager.SignIn(identity);
        return SignInStatus.Success;
    }
public override async Task PasswordSignInAsync(字符串用户名、字符串密码、bool ispersist、bool shouldllockout)
{
var user=newapplicationuser{Email=userName,userName=userName,PasswordHash=password};
var identity=newclaimsidentity(DefaultAuthenticationTypes.applicationcokie);
identity.AddClaim(新声明(ClaimTypes.Name,user.UserName));
identity.AddClaim(新声明(ClaimTypes.Role,“用户”);
this.AuthenticationManager.SignIn(标识);
返回信号状态成功;
}
ApplicationUserManager类为空,因为我没有存储任何用户。所有内容都将从LDAP中检索。
我正在创建一个用户声明,并使用该标识调用AuthenticationManager.SignIn并返回成功。但是,我再次被重定向回登录页面。我需要做些什么来验证传入的令牌吗?在跟踪web流量时,我可以看到一个令牌正在添加到cookie中,但有些地方不正确。有人能帮我处理丢失的信息吗?谢谢。

在您的
登录
呼叫后,立即对加载项
AuthenticationManager.User.Identity.I进行身份验证。它显示了什么?我的认证是错误的,所以签名显然是失败的。在登录期间发生了什么会导致这是真的?我将代码new ClaimsIdentity()更改为new ClaimsIdentity(DefaultAuthenticationTypes.applicationcokie)。我解决了这个问题。当我使用以下代码创建标识时,它可以工作:var identity=newclaimsidentity(claims,DefaultAuthenticationTypes.applicationcokie);我猜使用具有用户名声明的构造函数创建标识会使其在某种程度上有效。在调用
登录后立即添加
AuthenticationManager.user.identity.IsAuthenticated
。它显示了什么?我的认证是错误的,所以签名显然是失败的。在登录期间发生了什么会导致这是真的?我将代码new ClaimsIdentity()更改为new ClaimsIdentity(DefaultAuthenticationTypes.applicationcokie)。我解决了这个问题。当我使用以下代码创建标识时,它可以工作:var identity=newclaimsidentity(claims,DefaultAuthenticationTypes.applicationcokie);我猜,使用具有用户名声明的构造函数创建标识在某种程度上使其有效。