0

我正在开发一个 jQuery mobiel 应用程序。我有一个 RESTful WCF 服务,它提供一些 JSON 数据,jqm 应用程序使用这些数据。

现在我需要为服务实现身份验证。

目前它看起来像这样:

图表.

4

1 回答 1

1

If you are hosting your service in IIS and you want a custom username/password-validator, you could solve the problem by implementing a HttpModule that will implement Basic-authentication.

public class AuthenticationModule : IHttpModule
{
    void IHttpModule.Dispose() {}

    void IHttpModule.Init(HttpApplication context)
    {
        context.AuthenticateRequest += ContextOnAuthenticateRequest;
        context.EndRequest += ContextOnEndRequest;
    }

    private void ContextOnEndRequest(object sender, EventArgs eventArgs)
    {
        HttpContext context = HttpContext.Current;

        if(context.Response.StatusCode != 401)
            return;

        context.Response.AddHeader("WWW-Authenticate", "Basic realm=\"SomeRealm\"");
    }

    private void ContextOnAuthenticateRequest(object sender, EventArgs eventArgs)
    {
        HttpContext context = HttpContext.Current;
        string authHeader = context.Request.Headers["Authorization"];
        if(string.IsNullOrWhiteSpace(authHeader) || !authHeader.StartsWith("Basic "))
            DenyAccess();

        try
        {
            var encoded = authHeader.Substring(6);
            var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
            var splits = decoded.Split(':');
            var username = splits[0];
            var password = splits[1];

            var principal = //TODO Validate and return a class implementing System.Security.Principal.IPrincipal
            if (principal != null)
                context.User = principal;
            else
                DenyAccess();
        }
        catch(Exception e)
        {
            DenyAccess();
        }
    }

    private void DenyAccess()
    {
        var context = HttpContext.Current;
        context.Response.StatusCode = 401;
        context.Response.End();
    }
}

In your operation you can get the user by writing: ServiceSecurityContext.Current.PrimaryIdentity And also remember to set aspNetCompatibilityEnabled to true.

From your js-client, just include this in the header: Authorization: Basic Base64EncodedStringWithUsername:Password

Best regards db

于 2013-08-28T17:23:40.713 回答