问题
I'm trying to implement token-based authorization for an Asp.Net MVC2 app, and I think my approach is wrong. First off: by token-based authorization I mean that when an unauthenticated user goes to http://myapp.com/some/action?tok=[special single-use token here]
they are logged in.
All of the controllers in my app extend a common ApplicationController
, so my approach was to override OnAuthorize
on that controller as follows:
class ApplicationController
{
protected override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.QueryString["tok"] != null)
{
var token = HttpUtility.UrlDecode(filterContext.HttpContext.Request.QueryString["tok"]);
if ((var user = getUserByToken(token)) != null)
{
FormsAuthentication.SetAuthCookie(user.Email, false);
}
else{ /* highly-proprietary handling of invalid token */ }
}
base.OnAuthorization(filterContext);
}
}
I am absolutely certain that SetAuthCookie
is being called when it should and not being called when it shouldn't.
The problem is, that doesn't really log the user in. It sets a cookie, which means I'd have to redirect (User.Identity.IsAuthenticated
remains false after calling SetAuthCookie
.) But the whole idea about this is to continue the request as normal and avoid a pointless redirect. Is there some way to accomplish this goal? It doesn't really seem like a whole lot to ask...
回答1:
After you call SetAuthCookie, nothing changes with the User.Identity. On the next request, the data will be what you are expecting. The best thing to do here is to issue a redirect after SetAuthCookie has been called.
来源:https://stackoverflow.com/questions/4454670/log-user-in-manually-with-forms-authentication