【问题标题】:Encrypt and decrypt FormsAuthenticationTicket to authenticate users加密和解密 FormsAuthenticationTicket 以对用户进行身份验证
【发布时间】:2013-03-03 04:54:32
【问题描述】:

我正在尝试创建自己的身份验证机制,该机制依赖于FormsAuthentication。我基本上使用 OAuth 来允许用户在授权服务器中进行身份验证,一旦他们通过身份验证,我需要使用 FormsAuthentication 在整个会话中对他们进行身份验证。所以无论如何,我创建了一个HttpModule 和一个帮助类来完成这项工作。不幸的是,事实并非如此。

发生的情况是,在PostAuthenticateRequest 上,我加密了票证并在响应中添加了一个 cookie,然后将用户重定向到网站的根目录。重定向用户后,将发出另一个 HTTP 请求,因此再次触发 HttpModule,并在 AuthenticateRequest 事件中检查此用户是否已通过身份验证。为了检查用户是否经过身份验证,我试图读取 cookie,从中获取用户名,然后设置 Thread.CurrentPrincipal 属性。但是,由于某种原因,找不到 cookie。

这是我的代码:

public class OAuthModule : IHttpModule
{
    private const String USERNAME = "username";

    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        context.AuthenticateRequest += context_AuthenticateRequest;
        context.PostAuthenticateRequest += context_PostAuthenticateRequest;
    }

    void context_PostAuthenticateRequest(object sender, EventArgs e)
    {
        var application = sender as HttpApplication;
        if (application != null)
        {
            String username = application.Context.Items[USERNAME].ToString();
            String uri = RemoveQueryStringFromUri(application.Context.Request.Url.AbsoluteUri);
            var cookie = IdentityHelper.GetEncryptedFormsAuthenticationCookie(username, uri);
            application.Context.Response.Cookies.Add(cookie);

            application.Context.Response.Redirect(uri);
        }
    }

    void context_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpApplication application = sender as HttpApplication;
        if (sender != null)
        {
            if (!application.Context.Request.Url.AbsolutePath.Contains("."))
            {
                if (!IdentityHelper.IsAuthenticated)
                {
                    HttpContextWrapper wrapper = new HttpContextWrapper(application.Context);
                    String clientId = WebConfigurationManager.AppSettings["ClientId"];
                    String clientSecret = WebConfigurationManager.AppSettings["ClientSecret"];
                    String authorizationServerAddress = WebConfigurationManager.AppSettings["AuthorizationServerAddress"];
                    var client = OAuthClientFactory.CreateWebServerClient(clientId, clientSecret, authorizationServerAddress);
                    if (String.IsNullOrEmpty(application.Context.Request.QueryString["code"]))
                    {
                        InitAuthentication(wrapper, client);
                    }
                    else
                    {
                        OnAuthCallback(wrapper, client);
                    }
                }
            }
        }
    }


    private void InitAuthentication(HttpContextWrapper context, WebServerClient client)
    {
        var state = new AuthorizationState();
        var uri = context.Request.Url.AbsoluteUri;
        uri = RemoveQueryStringFromUri(uri);
        state.Callback = new Uri(uri);
        var address = "https://localhost";
        state.Scope.Add(address);

        OutgoingWebResponse outgoingWebResponse =  client.PrepareRequestUserAuthorization(state);
        outgoingWebResponse.Respond(context);
    }

    private void OnAuthCallback(HttpContextWrapper context, WebServerClient client)
    {
        try
        {
            IAuthorizationState authorizationState = client.ProcessUserAuthorization(context.Request);
            AccessToken accessToken = AccessTokenSerializer.Deserialize(authorizationState.AccessToken);
            String username = accessToken.User;
            context.Items[USERNAME] = username;                
        }
        catch (ProtocolException e)
        {
            EventLog.WriteEntry("OAuth Client", e.InnerException.Message);
        }
    }

    private String RemoveQueryStringFromUri(String uri)
    {
        int index = uri.IndexOf('?');
        if (index > -1)
        {
            uri = uri.Substring(0, index);
        }
        return uri;
    }
}


public class IdentityHelper
{
    public static Boolean IsAuthenticated
    {
        get
        {
            String username = DecryptFormsAuthenticationCookie();
            if (!String.IsNullOrEmpty(username))
            {
                SetIdentity(username);
                return Thread.CurrentPrincipal.Identity.IsAuthenticated;
            }
            return false;
        }
    }

    private static String DecryptFormsAuthenticationCookie() 
    {
        var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (cookie != null)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            return ticket.UserData;
        }
        return String.Empty;
    }

    internal static HttpCookie GetEncryptedFormsAuthenticationCookie(String username, String domain)
    {
        var expires = DateTime.Now.AddMinutes(30);
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, expires, true, username, FormsAuthentication.FormsCookiePath);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
        cookie.Value = FormsAuthentication.Encrypt(ticket);
        cookie.Domain = domain;
        cookie.Expires = expires;
        return cookie;
    }

    private static void SetIdentity(String username)
    {
        ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.Name, username) });
        var principal = new ClaimsPrincipal(claimsIdentity);
        Thread.CurrentPrincipal = principal;
    }
}

我哪里做错了?有什么想法吗?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-4 forms-authentication httpmodule


    【解决方案1】:

    好的,我终于解决了。就这么简单:

    application.Context.Response.Redirect(uri, false);
    

    我需要告诉模块不要终止当前响应(因此是 false),以便它会在即将到来的请求中保留 cookie。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      相关资源
      最近更新 更多