MvvmCross HTTP DownloadCache with authentication

天涯浪子 提交于 2020-01-06 14:07:26

问题


In my app, the user need to be authenticated on the server to download data using WebAPIs. The MvvmCross DownloadCache plugin seems to handle only basic HTTP GET queries. I can't add my authentication token in the url as it's a big SAML token.

How can I add a HTTP header to queries done through DownloadCache plugin ?

With the current version I think I should inject my own IMvxHttpFileDownloader but I'm looking for an easier solution. Injecting my own MvxFileDownloadRequest would be better (not perfect) but it doesn't have an interface...


回答1:


I'm able to do it registering a custom IWebRequestCreate for a custom scheme (http-auth://).

It's a bit ugly to transform urls from my datasource but it does the job.

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


来源:https://stackoverflow.com/questions/21093752/mvvmcross-http-downloadcache-with-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!