1
votes

I have a couple of systems which uses external authentication, google authentication. I'm just keeping the login information in a session variable and keep track of the user that way (no membership provider).

I would like to have the user identity in the HttpContext.Current.User object. Should I assign the user manually on an event in Global.asax.cs, or could I have the user automatically identified during the session?

2

2 Answers

2
votes

You could write a custom Authorize attribute which will take care of assigning the HttpContext.Current.User property from the session:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var user = httpContext.Session["username"] as string;
        if (string.IsNullOrEmpty(user))
        {
            // we don't have any username inside the session => unauthorized access
            return false;
        }

        // we have a username inside the session => assign the User property
        // so that it could be accessed from anywhere
        var identity = new GenericIdentity(user);
        httpContext.User = new GenericPrincipal(identity, null);
        return true;
    }
}

Then simply decorate your controllers/actions that require authentication with this custom attribute.

1
votes

Use a membership provider, it will give you exactly what you want. Even creating your own provider isn't too difficult, just implement the abstract class MembershipProvider and plug into config, or use some of the out-of-the-box providers.

Don't roll your own solution for something critical like security, it will have gaping security holes. Storing authentication info in the session is a really bad idea. It leaves it open to session hijacking, session replay attacks etc.

If you really want to go down the route of custom authentication. Then have a look at the code I posted here. It will show you how you can take control of the authentication cookie, and use this to create your own HttpContext.Current.User instance.