0

Is there a way to authenticate a session without creating an ApplicationUser in MVC 5 identity?

For various reasons, I ended up using a two layered authentication system. I parse a "user" object from my custom db into session, and in various places all over the site, the existence of this object is how the logged-in status of a user is determined.

I use Identity user stuff (e.g. claims, logins, etc.) at various places of the site. But at this one specific instance, I need to log in an anonymous Identity user and parse whatever user object is requested to the session. So how can I create an anonymously authenticated session with Identity V2?

1 Answer 1

1

In Identity you don't need to have user object to authenticate. You could create some claims on the fly and use them to authenticate. Consider this simple example:

[HttpPost]
public ActionResult AnonymousLogin()
{
    var ident = new ClaimsIdentity(
        new[] 
        {
            // adding following 2 claim just for supporting default antiforgery provider
            new Claim(ClaimTypes.NameIdentifier, "AnonymousUserID"),
            new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

            new Claim(ClaimTypes.Name, "AnonymousUserID"),
         },
         DefaultAuthenticationTypes.ApplicationCookie);

    HttpContext.GetOwinContext().Authentication.SignIn(
       new AuthenticationProperties { IsPersistent = false }, ident);
    return RedirectToAction("MyAction"); // auth succeed 
}

Now you have authenticated an anonymous user just like a real user:

[Authorize]
public ActionResult MyAction()
{
    // all authorized users could use this method don't matter how have been authenticated
    // you have access current user principal
    var username=HttpContext.User.Identity.Name;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, exactly what I needed to know. I can't get rid of a user object in the session because I'm working on a site that already uses this, but I layered my approach to separate this object from Identity. Thanks a lot this indeed helped.
Thanks guys ! About your solution, this means you have to reference OWIN in your project ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.