繁体   English   中英

如何在MVC6中为登录的用户凭据实施OWIN身份验证?

[英]How to implement OWIN authentication for logged-in user credential in MVC6?

在MVC6中,我能够使用Microsoft.AspNet.Identity(EntityFramework除外)实现核心ADO.net。 但是身份验证仍在我方进行挂起,因为在用户登录状态下,我不知道如何在MVC 6中维护身份验证。

在MVC6中,有一个自己的演示项目,该项目在实体框架中维护登录用户凭证的身份验证。

但我想要MVC6中带有身份验证的核心ADO.Net实现。

因此,如果这些人知道如何在MVC6中对登录的用户进行身份验证。

我的登录操作方法:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
{ 
    if (ModelState.IsValid)
    { 
        var user = await _customerUserManager.FindAsync(model.UserName, model.Password); 
        if (user != null)
        { 
            // await SignInAsync(user, model.RememberMe); 
            return RedirectToLocal(returnUrl); 
        } 
        else 
        { 
            ModelState.AddModelError(string.Empty, "Invalid username or password."); 
        } 
    } 
    return View(model); 
} 

您需要进行ClaimsIdentity并将其放入Authentication.SignIn()方法中。 然后,身份将制作相关的Cookie并保持您的用户登录:

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) 
{ 
    if (ModelState.IsValid)
    {
        var user = await _customerUserManager.FindAsync(model.UserName, model.Password); 
        if (user != null)
        {
            var options=new IdentityOptions(); 
            var ident = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationType);
            ident.AddClaims(new[] 
            {              
                new Claim(options.ClaimsIdentity.UserIdClaimType,user.Id),
                new Claim(options.ClaimsIdentity.UserNameClaimType, user.userName),
                // populate assigned user roles form the DB and add each one as a claim  
                new Claim(ClaimTypes.Role,"RoleName1"),
                new Claim(ClaimTypes.Role,"RoleName2"),
            });

            Context.Authentication.SignIn(IdentityOptions.ApplicationCookieAuthenticationScheme, new ClaimsPrincipal(ident));
            return RedirectToLocal(returnUrl); 
        } 
        else 
        { 
            ModelState.AddModelError(string.Empty, "Invalid username or password."); 
        } 
    } 
    return View(model); 
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM