简体   繁体   中英

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

In MVC6, I am able to implement the core ADO.net with Microsoft.AspNet.Identity(except EntityFramework). But authentication is still pending from my-side because I don't know how to maintain the authentication in MVC 6 when user logged-in state.

In MVC6, there is own demo project which is maintaining the authentication of logged-in user credential in entity framework.

But I want core ADO.Net implementation with authentication in MVC6.

So, if those know how to authenticate the logged-in user in MVC6.

My login action method:

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); 
} 

You need make a ClaimsIdentity and put it in Authentication.SignIn() method. Then Identity makes relevant cookie and keep your user signed in:

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); 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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