简体   繁体   中英

Inets http client + authorization

如何在httpc:request()函数的http请求中为客户端授权指定用户/密码?

I don't think httpc module provides facility for that. Nevertheless it isn't hard to implement (if we are talking about Basic Authentification). After all it's just an additional request header with 'user:password' pair Base64 encoded. For example Tsung's ts_http_common module does it.

For instance, here is how you can run HTTP PUT request with basic authentication:

auth_header(User, Pass) ->
    Encoded = base64:encode_to_string(lists:append([User,":",Pass])),
    {"Authorization","Basic " ++ Encoded}.

put_request(Url, User, Pass, Body) ->
    ContentType = "text/json",
    Headers = [auth_header(User, Pass), {"Content-Type",ContentType}],
    Options = [{body_format,binary}],
    httpc:request(put, {Url, Headers, ContentType, Body}, [], Options). 

I see in doc that HTTPOptions holds pass and user:

HTTPOptions = http_options()
http_options() = [http_option()]
http_option() = {timeout, timeout()} | {connect_timeout, timeout()} | {ssl, ssloptions()} | {ossl, ssloptions()} | {essl, ssloptions()} | {autoredirect, boolean()} | {proxy_auth, {userstring(), passwordstring()}} | {version, http_version()} | {relaxed, boolean()} | {url_encode, boolean()}

documentation: http://www.erlang.org/doc/man/httpc.html#request-5

For digest, you'll need to do the same thing as basic but more so. Generally you'll hit the page without auth, get the "WWW-Authenticate" header info, then use the realm and nonce there to generate your "Authorization" header. http://en.wikipedia.org/wiki/Digest_access_authentication has a decent example at the bottom.

Generally, HTTPS + Basic is sufficient, if not better, for most use cases.

Try using ibrowse, that supports and I am have been using that! https://github.com/cmullaparthi/ibrowse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM