具有身份验证的MvvmCross HTTP DownloadCache

时间:2014-01-13 14:32:20

标签: httpwebrequest xamarin mvvmcross

在我的应用中,用户需要在服务器上进行身份验证才能使用WebAPI下载数据。 MvvmCross DownloadCache插件似乎只处理基本的HTTP GET查询。我无法在网址中添加我的身份验证令牌,因为它是一个很大的SAML令牌。

如何为通过DownloadCache插件完成的查询添加HTTP标头?

对于当前版本,我认为我应该注入我自己的IMvxHttpFileDownloader,但我正在寻找一个更简单的解决方案。注入我自己的MvxFileDownloadRequest会更好(不完美),但它没有接口......

1 个答案:

答案 0 :(得分:1)

我能够为自定义方案注册自定义IWebRequestCreate(http-auth://)。

从我的数据源转换网址有点难看但是它可以完成这项任务。

  public class AuthenticationWebRequestCreate : IWebRequestCreate
  {
    public const string HttpPrefix = "http-auth";
    public const string HttpsPrefix = "https-auth";

    private static string EncodeCredential(string userName, string password)
    {
      Encoding encoding = Encoding.GetEncoding("iso-8859-1");
      string credential = userName + ":" + password;
      return Convert.ToBase64String(encoding.GetBytes(credential));
    }

    public static void RegisterBasicAuthentication(string userName, string password)
    {
      var authenticateValue = "Basic " + EncodeCredential(userName, password); 
      AuthenticationWebRequestCreate requestCreate = new AuthenticationWebRequestCreate(authenticateValue);
      Register(requestCreate); 
    }

    public static void RegisterSamlAuthentication(string token)
    {
      var authenticateValue = "SAML2 " + token;
      AuthenticationWebRequestCreate requestCreate = new AuthenticationWebRequestCreate(authenticateValue);
      Register(requestCreate);
    }

    private static void Register(AuthenticationWebRequestCreate authenticationWebRequestCreate)
    {
      WebRequest.RegisterPrefix(HttpPrefix, authenticationWebRequestCreate);
      WebRequest.RegisterPrefix(HttpsPrefix, authenticationWebRequestCreate);
    }

    private readonly string _authenticateValue;

    public AuthenticationWebRequestCreate(string authenticateValue)
    {
      _authenticateValue = authenticateValue;
    }

    public WebRequest Create(System.Uri uri)
    {
      UriBuilder uriBuilder = new UriBuilder(uri);
      switch (uriBuilder.Scheme)
      {
        case HttpPrefix:
          uriBuilder.Scheme = "http";
          break;
        case HttpsPrefix:
          uriBuilder.Scheme = "https";
          break;
        default:
          break;
      }
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriBuilder.Uri);
      request.Headers[HttpRequestHeader.Authorization] = _authenticateValue;
      return request;
    }
  }