Search code examples
c#asp.netasp.net-identity-2

Asp.net Identity 2.0 custom login method


I'm developing ASP.NET 5 application using Identity 2.0. I have two types of users:

  1. Normal - they authenticate using standard login method.
  2. Temporary - they should login based on provided token.

I do not want to store temporary users, except from information required to authenticate user (some username and token). If the user provides username and valid password he should be logged in.

I'm not sure how to achieve this.


Solution

  • You could use Identity in both scenarios simultaneously as well. For first scenario use Identity just like you have done before without any change but for second scenario you a slight modify in login method.

    public ActionResoult TempLogin(string username, string password)
    {
        // imaging you have own temp user manager, completely independent from identity
        if(_tempUserManager.IsValid(username,password))         
        {
            // user is valid, going to authenticate user for my App
            var ident = new ClaimsIdentity(
            new[] 
            {
                // adding following 2 claim just for supporting default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, username),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
    
                // an optional claim you could omit this 
                new Claim(ClaimTypes.Name, username),
    
                // you could even add some role
                new Claim(ClaimTypes.Role, "TempUser"),
                new Claim(ClaimTypes.Role, "AnotherRole"),
                // and so on
            },
            DefaultAuthenticationTypes.ApplicationCookie);
    
            // Identity is sign in user based on claim don't matter 
            // how you generated it Identity 
            HttpContext.GetOwinContext().Authentication.SignIn(
                new AuthenticationProperties { IsPersistent = false }, ident);
    
            // auth is succeed, 
            return RedirectToAction("MyAction"); 
         }
         ModelState.AddModelError("", "We could not authorize you :(");
         return View();
    }
    

    Since we injected our logic to Identity, we don't need to do extra thing at all.

    [Authorize]
    public ActionResult MySecretAction()
    {
        // all authorized users could use this method don't matter how has been authenticated
        // we have access current user principal by calling also
        // HttpContext.User
    }
    
    [Authorize(Roles="TempUser")]
    public ActionResult MySecretAction()
    {
        // just temp users have accesses to this method
    }