简体   繁体   中英

Reading username and password sent from and Android app into my WCF REST Service?

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.

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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM