Log user in manually with Forms Authentication

廉价感情. 提交于 2019-12-11 18:47:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!