的Windows Phone 8基本身份验证 [英] Windows Phone 8 Basic Authentication

查看:135
本文介绍了的Windows Phone 8基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主持使用用户名和密码基本认证头一个Windows网页API。

I have hosted a Windows Web API using a basic authentication header with username and password.

我试图创建一个登录表单,需要一个用户名和密码,并发送回一个令牌。
所以我有以下code。

I'm trying to create a login form that takes a username and password and sends back a token. so i have the following code.

我使用的是归因方法

 public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{

    private IPromiseRepository promiseRepository;


    public BasicAuthenticationAttribute()
    {


        this.promiseRepository = new EFPromiseRepository(new PropellorContext());
        //repository = promiseRepository;
    }

    public BasicAuthenticationAttribute(IPromiseRepository promiseRepository, INewsFeedRepository newsfeedRepository)
    {
        this.promiseRepository = promiseRepository;

    }



    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {

        if (actionContext.Request.Headers.Authorization == null)
        {
            actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
        }

        else
        {


            string authToken = actionContext.Request.Headers.Authorization.Parameter;

            string decodedToken = authToken;
            //    Encoding.UTF8.GetString(Convert.FromBase64String(authToken));

            string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
            string password = decodedToken.Substring(decodedToken.IndexOf("^")+1);
            string APIToken = decodedToken.Substring(decodedToken.IndexOf("="));
            APIToken = APIToken.Replace("=", string.Empty);

            password = password.Replace("=", string.Empty);


            if (!string.IsNullOrEmpty(APIToken))
            {
                password = password.Replace(APIToken, string.Empty);
            }



            if (username != null && password != null)
            {
                try
                {
                    var user = promiseRepository.GetUserByName(username);
                    var salt = user.PasswordSalt;

                    System.Security.Cryptography.SHA512Managed HashTool = new System.Security.Cryptography.SHA512Managed();
                    Byte[] PasswordAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(password, salt));
                    Byte[] EncryptedBytes = HashTool.ComputeHash(PasswordAsByte);
                    HashTool.Clear();
                    var hashedpass = Convert.ToBase64String(EncryptedBytes);


                    if (hashedpass == user.Password)
                    {

                        if (string.IsNullOrEmpty(user.APIToken))
                        {
                            String guid = System.Guid.NewGuid().ToString();
                            user.APIToken = guid;
                            promiseRepository.UpdateUser(user);
                            promiseRepository.Save();
                        }


                        if (user != null)
                        {

                            user = promiseRepository.GetUserByUserID(user.UserID);
                            HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(user), new string[] { });


                            base.OnActionExecuting(actionContext);
                        }

                    }

                    if (APIToken != null)
                    {
                        if (user.APIToken == APIToken)
                        {
                            var userbytoken = promiseRepository.GetUserByAPIToken(APIToken);
                            HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(userbytoken), new string[] { });


                            base.OnActionExecuting(actionContext);
                        }
                    }

                }


                catch (Exception)
                {

                    {
                        actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
                        base.OnActionExecuting(actionContext);
                    }
                    throw;
                }








            }



        }


    }



    }

这可与小提琴手时正确的凭据传递

This works with Fiddler when the correct credentials are passed

我试图产生我的Windows Phone应用程序相同的验证。

I'm attempting to produce the same authentication in my windows phone application.

将用户名和密码,进入基本身份验证HTTP标头。

Passes a username and password into the basic authentication http header.

不过我不知道如何做到这一点的大量diggging在exmaples的互联网很多的之后Windows Phone 7和一定的方法不存在了。

However I'm not sure how to do this after a large amount of diggging on the internet alot of the exmaples are windows phone 7 and certain methods don't exist anymore.

这是code I的到了。

This is the code i have arrived at.

private void Login1_Click(object sender, RoutedEventArgs e)

    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:5650/api/start");

        NetworkCredential credentials = new NetworkCredential(userName.Text + ":^",password.Text + "=");
        request.Credentials = credentials;

        request.BeginGetResponse(new AsyncCallback(GetSomeResponse), request);

希望有人能指点我到正确的方向。
它应该是原理简单:(

Hopefully someone can guide me into the right direction. it should be simple in principle :(

推荐答案

下面是一个使用样本的HttpClient:

Here is a sample using HttpClient:

public static async Task<String> Login(string username, string password)
{
    HttpClient Client = new HttpClient();
    Client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(StringToAscii(string.Format("{0}:{1}", username, password))));
    var response = await Client.GetAsync(new Uri(new Uri("http://yourdomain.com"), "/login"));
    var status= await response.Content.ReadAsAsync<String>();
    return status;
}

当然,你可以在互联网上找到的ToBase64String功能。这里最棘手的部分是Authorization头。

And of course you can find the ToBase64String function on the internet. The tricky part here is the Authorization header.

这篇关于的Windows Phone 8基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆