tags:

views:

48

answers:

1

My current WCF REST Method is defined as:

[OperationContract]
[WebGet(UriTemplate = "{username}/{password}", ResponseFormat =                   
                                                        WebMessageFormat.Json)]
string Login(string username, string password);

An android client app is going to connect to the service, let's say it is http://service.com/login.svc/login...

But I don't want the username and password to be passed in the url like I have specified in the UriTemplate. How can I receive the username and password from the android app into my service, or better yet, how can I change my login method to retrieve the username and password in some POST parameters that I can process in my login function and validate the user against a sql membership database.

A: 

We have done this via using the "Authorization" header. The clients pass along an encrypted set of credentials and we generate a token for them on our side. Here is an example of the BeginRequest method of an HttpModule that handles authentication. We use a custom principal to handle the token:

 private void BeginRequest(Object source, EventArgs e)
    {
        if (null == HttpContext.Current || String.IsNullOrEmpty(HttpContext.Current.Request.Headers["Authorization"]))
        {
            HttpContext.Current.Response.StatusCode = (Int32)HttpStatusCode.Unauthorized;
            HttpContext.Current.Response.End();
        }

        HttpContext context = HttpContext.Current;
        Regex matcher = new Regex(WfmConfigurationManager.GetAppSetting("AuthenticationPath"));

        if (!matcher.IsMatch(context.Request.Url.ToString(),0))
        {
            String authHeader = context.Request.Headers["Authorization"];
            IIdentity tokenIdentity = new TokenIdentity(authHeader);

            if (!tokenIdentity.IsAuthenticated)
            {
                HttpContext.Current.Response.StatusCode = (Int32)HttpStatusCode.Unauthorized;
                HttpContext.Current.Response.End();
            }

            IPrincipal tokenPrincipal = new TokenPrincipal(tokenIdentity, TokenAuthentication.GetRolesForUser(tokenIdentity));
            HttpContext.Current.User = tokenPrincipal;
        }
    }
Adam Fyles
Do you have sample code that you can provide? This is where I am stuck, I have no idea how to set/get the Authorization Header? Basically, where do I start?
Xaisoft
I added some code above from an HttpModule. You can implement a custom principal as you see fit.
Adam Fyles
Adam, thanks for the code snippet. A few questions: Where do I implement this and when do I call it? Also, do I have to make any changes to my config files. This is an internet service that will be accessible from all types of devices.
Xaisoft
This is from within an HttpModule, see this article: http://msdn.microsoft.com/en-us/library/ms227673(v=VS.100).aspx. You will have to register the module in your web.config
Adam Fyles