简体   繁体   中英

How to implement auto user login using asp.net mvc

We are using mvc framework 6, identity framework 3 and EF 7 with sql server. The webapp requires user authentication and authorization. But there's a situation when we want to authenticate/authorize user from query string. I am having problem in creating usermanager/signinmanager. This is what AccountController looks like for login

[Authorize]
public class AccountController : Controller
{
    private readonly ApplicationDbContext _dbContext;
    public AccountController(ApplicationDbContext dbContext, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
    {
        _dbContext = dbContext;
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public UserManager<ApplicationUser> UserManager { get; private set; }

    public SignInManager<ApplicationUser> SignInManager { get; private set; }

    //
    // GET: /Account/Login
    [HttpGet]
    [AllowAnonymous]
    public IActionResult Login(string returnUrl = null)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewBag.ReturnUrl = returnUrl;
        if (ModelState.IsValid)
        {
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, set shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            if (result.Succeeded)
            {
                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                return View("Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid username or password.");
                return View(model);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

For auto login from URL string, I want to create or instantiate SigninManager object to I so I could use PasswordSignInAysync method. But I am not sure how to do that. This is what I have , but I am not sure about the arguments to pass.

    [HttpGet]
    public async Task<IActionResult> Index()
    {
       //from url
       if(Request != null)
        {
            if(Request.Query["emailId"] != null)
            {

                var store = new UserStore<ApplicationUser>(_dbContext);
                var manager = new UserManager<ApplicationUser>(store,null,null,null,null,null,null,null,null,null);
                //var userstore = new IUserStore(ApplicationUser);
                //var user = new UserManager();
                var user = new ApplicationUser { UserName = "someone@XXX.com" };

                var signinmanager = new SignInManager<ApplicationUser>(manager,);

                var result =  await SignInManager.PasswordSignInAsync(Request.Query["emailId"],
                                        Request.Query["TokenId"], false, shouldLockout: false);
                if (result.Succeeded)
                {
                    return RedirectToAction("MyHome", "People");
                }
                return RedirectToAction("MyHome",  "People");
            }
        }


    }

Answer based off of the conversation in comments: Ok, what I would recommend is that to do this you create a custom login endpoint which accepts a loginid, that way after you've finished showing a client the site, you can revoke that id and stop un-auth access in the future.

I'm sorry but I don't fully remember how you do a custom login endpoint, I know theres somthing about setting User's authorised.

But once you figure out how to Authorize the user, create a new claims on the users identity of potentialClient, from there you can create an action filter and make it so that people who are potentialClients can only access endpoints which have the custom filter which allows potential clients.

If I find out the way you authorise I'll pass it back to you, I'ts not using the sign in manager though if I remember correct, its somthing pretty simple, like setting something to true.. I wish I could remember but it's evading me.

Hope this helps

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