Digest authentication in Android using HttpURLConnection

前端 未结 5 703
终归单人心
终归单人心 2020-12-03 16:05

as the question allready says, I am trying to do digest authentication in android.
Until now i have used the DefaultHttpClient and it\'s authentication meth

5条回答
  •  误落风尘
    2020-12-03 16:34

    The answer is, that HttpUrlConnection does not support digest.

    You therefore have to implement RFC2617 by yourself.

    You can use the following code as a baseline implementation: HTTP Digest Auth for Android.

    The steps involve (see RFC2617 for reference):

    • If you get a 401 response, iterate over all WWW-Authenticate headers and parse them:
      • Check if algorithm is MD5 or undefined, (optionally select the auth qop option), otherwise ignore the challenge and go to the next header.
      • Get the credentials using Authenticator.requestPasswordAuthentication.
      • Calculate H(A1) using the username, realm and password.
      • Store the canonical root URL, realm, HA1, username, nonce (+ optionally algorithm, opaque and the client selected qop option if present).
      • Retry the request.
    • On each request, iterate over all realms you have session information stored for by canonical root URL:
      • Calculate H(A2) using the request method and path.
      • Calculate H(A3) using HA1, nonce (+ optionally nc, cnonce, qop) and HA2.
      • Build and add the Authorization header to your HttpUrlConnection.
    • Implement some sort of session pruning.

    By using Authenticator, you can make sure, that as soon as HttpUrlConnection supports digest natively, your code is not being used anymore (because you wont receive the 401 in the first place).

    This is just a quick summary on how to implement it, for you to get an idea.

    If you want to go further you would probably like to implement SHA256 as well: RFC7616

提交回复
热议问题