0

我使用带有用户名和密码的基本身份验证标头托管了一个 Windows Web API。

我正在尝试创建一个登录表单,该表单采用用户名和密码并发送回一个令牌。所以我有以下代码。

我正在使用属性方法

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








            }



        }


    }



    }

当传递正确的凭据时,这适用于 Fiddler

我正在尝试在我的 Windows Phone 应用程序中生成相同的身份验证。

将用户名和密码传递到基本身份验证 http 标头中。

但是,在互联网上进行大量挖掘后,我不确定如何执行此操作,很多示例是 windows phone 7,某些方法不再存在。

这是我到达的代码。

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

希望有人能引导我走向正确的方向。原则上应该很简单:(

4

1 回答 1

0

这是一个使用 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;
}

当然,您可以在 Internet 上找到 ToBase64String 函数。这里棘手的部分是 Authorization 标头。

于 2013-10-14T20:08:18.167 回答