matlab.net.http.Credentials - Credentials for authenticating HTTP requests - MATLAB (original) (raw)
Namespace: matlab.net.http
Superclasses: handle
Credentials for authenticating HTTP requests
Description
The Credentials
class specifies authentication credentials for sending a request message. Specify a Credentials
object in an HTTPOptions object.
The RequestMessage.send
method uses credentials to respond to authentication challenges from servers or proxies. The authentication challenge is in anAuthenticateField header field and specifies one or more authentication schemes that the server or proxy accepts to satisfy the request.
The behavior depends on the authentication scheme. In general, MATLAB® searches the vector of Credentials
objects for one that applies to the request URI and which supports the specified authentication scheme. MATLAB then resends the original request with the appropriate credentials in an AuthorizationField header. If multiple credentials apply, then MATLAB uses the most specific Credentials
object for the strongest scheme. If duplicate Credentials
objects exist, then MATLAB uses the first one.
To see what authentication schemes MATLAB implements automatically, see AuthenticationScheme. If the server requires other schemes, or you do not supply credentials for the required scheme, then the authentication response message returns aStatusCode of 401 or 407. In this case, you must implement the appropriate response yourself.
For schemes that do not require Username
andPassword
properties, such as NTLM on Windows®, you can use a default Credentials
object. A defaultCredentials
object has default or empty properties and applies to all supported schemes and URIs. Your authorization credentials come from information, such as Kerberos tickets, that are stored in your system when you log in. To constrain the conditions under which a particular scheme is used, you can specify additional properties, such asScope andRealm. For example, set these values to use NTLM for some URLs and Kerberos for others and reject authentication requests from servers that do not match those URLs and schemes.
For schemes that require Username
and Password
properties, if MATLAB authenticates with a Credentials
object, then MATLAB saves the results in this object. MATLAB can apply these credentials on subsequent requests without waiting for an authentication challenge from the server. To take advantage of shortcut, provide the sameCredentials
object on subsequent requests in the same or otherHTTPOptions
objects.
Credentials
objects are handle objects and internally accumulate information about prior successful authentications. Therefore, you can reuse the information for subsequent messages. If you insert this object into multiple HTTPOptions
objects, then the Credentials
object might be updated upon each use. If you copy Credentials
using its copy
method, then MATLAB copies only the visible properties that you set, and not the internal state.
The matlab.net.http.Credentials
class is a handle class.
Creation
Description
obj = matlab.net.http.Credentials(Name,Value)
creates HTTP credentials with additional properties specified by one, or more name-value pair arguments. Name
is the property name and Value
is the corresponding value. You can specify several name-value pair arguments in any order asName1,Value1,...,NameN,ValueN
. Unspecified properties are set to their default values.
If you call this constructor with no arguments, then the Credentials
object applies to and thus permits authentication for all URIs and all authentication schemes. However, the object works only for schemes that do not require a username or password. For example, on Windows, the object enables NTLM and Kerberos authentication using the credentials of the logged-in user.
Properties
Authentication schemes for credentials, specified as a vector of matlab.net.http.AuthenticationScheme objects. For a complete list of supported schemes per platform, see AuthenticationScheme.
If Scheme
is empty (default), then the credentials apply to all defined authentication schemes.
For more information about authentication, see Server Authentication and Proxy Server Authentication.
If Scheme
is set to Basic
only, then these credentials might be applied to a request whether or not the server requests authentication. A Basic
-only scheme avoids an extra round trip responding to an authentication challenge. However, if the server does not requireBasic
authentication, this scheme unnecessarily exposes theUsername
and Password
properties to the server.
If this property includes any scheme besides or in addition toBasic
, or if Scheme
is empty (which allow all schemes), then MATLAB does not send any authorization information in the first message to which these credentials apply. MATLAB waits for the server to respond with a challenge, such as a WWW-Authenticate field. The response tells MATLAB what authentication schemes the server accepts. Then MATLAB chooses the strongest scheme listed among the Credentials
, which also match the Scope
and Realm
properties you specify, if any. Subsequent messages to the same server with the sameScope
include the appropriate authorization information without first requiring a challenge.
Attributes:
GetAccess | public |
---|---|
SetAccess | public |
URIs to which credentials apply, specified as a vector of matlab.net.URI objects or strings or character vectors. Strings must be acceptable to the URI
constructor or of the formhost/path/...
.
An empty Scope
value, or an empty Host
orPath
in this vector matches all Host
orPath
properties. Do not leave Scope
empty ifScheme
is set to Basic
only, unless you only access trusted servers. This combination of settings sends Username
and Password
to any server you access using theHTTPOptions
containing these Credentials
.
MATLAB compares the values in Scope
with the request message URI to determine if these credentials apply. Credentials apply if the request URI refers to the same host at a path at or deeper than one of the URIs in thisScope
. A Scope
containing a URI naming a host with no path applies to all paths on that host.
For example, a mathworks.com
host name in aScope
matches a request to www.mathworks.com
and anything.mathworks.com
. Amathworks.com/products/stateflow
URI matches a request towww.mathworks.com/products/stateflow/features
but not towww.mathworks.com/products
. The /products
path is not at or deeper than /products/stateflow
.
Only the Host
, Port
, andPath
properties of the Scope
URIs are used. Typically you only specify a Host
name, such aswww.mathworks.com
. If you know that the credentials are needed only for some paths within a host, then add a Path
or a portion of a path.
Attributes:
GetAccess | public |
---|---|
SetAccess | public |
Authentication realms for credentials, specified as a string array, character vector, or cell array of character vectors containing regular expressions describing the realms for the credentials. The default value is empty, which matches all realms. If any value in this vector is an empty string, then it only matches an empty or unspecifiedRealm
. To anchor the regular expression to the start or end of the authentication Realm
string, include the ^
or $
characters as appropriate.
A Realm
contains text to display so that the user knows what name and password to enter. The server specifies the Realm
in anAuthenticateField
of a ResponseMessage
. In general, leave this property empty. Use a Realm
when a server requires different login values for different URIs and you want to specify programmatically different credentials for different realms on the same server. If you prompt for a name and password, do not set this property. Instead, display the Realm
property from the AuthenticateField
in your prompt so that the user knows which credentials to enter.
MATLAB compares the expressions in Realm
against the authentication Realm
in AuthenticateField
to determine if these credentials apply. Once MATLAB carries out a successful authentication using one of these realms, MATLAB caches information about the authentication in Credentials
. A subsequent request to a host and path that applies to these Credentials
uses this cached information for authentication. This avoids the overhead of an authentication challenge or a call to the GetCredentialsFcn
function.
Attributes:
GetAccess | public |
---|---|
SetAccess | public |
Username for authentication schemes, specified as a secretID
object, string scalar, or a character vector. This property applies only to schemes that require an explicit Username
and Password
, and not for schemes that get your credentials from the system. For more information, seeServer Authentication.
If you set the Username
and Password
properties to any string (including an empty one), then Username
is used for authentication to any request for which these credentials apply, unlessGetCredentialsFcn
is specified. If you set this property to[]
, then you must specify GetCredentialsFcn
or authentication is not attempted.
You do not need to embed a username in your code. Instead, use one of these options:
- Specify the username using a secretID. For example, see Specify Credentials for Username and Password.
- Leave this property empty and specify a
GetCredentialsFcn
property that prompts the user for a name or obtains it from another source. For example, see Prompt User for Name and Password.
Attributes:
GetAccess | public |
---|---|
SetAccess | public |
Password for authentication schemes, specified as a secretID
object, string scalar, or a character vector. This property applies only to schemes that require an explicit Username
and Password
, and not for schemes that get your credentials from the system. For more information, seeServer Authentication.
If you set the Username
and Password
properties to any string (including an empty one), then Password
is used for authentication to any request for which these credentials apply, unlessGetCredentialsFcn
is specified. If you set this property to[]
and there is no GetCredentialsFcn
property, then no password is provided.
You do not need to embed a password in your code. Instead, use one of these options:
- Specify the password using a secretID. For example, see Specify Credentials for Username and Password.
- Leave this property empty and specify a
GetCredentialsFcn
property that prompts the user for a password or obtains it from another source. For example, see Prompt User for Name and Password.
Attributes:
GetAccess | public |
---|---|
SetAccess | public |
Function returning the Username
andPassword
for authentication, specified as a function handle. This property applies only to schemes requiring you to specify a username and password. For an example, see Prompt User for Name and Password.
MATLAB calls the GetCredentialsFcn
function to obtain the name and password to use for the authentication response. MATLAB ignores the Username
or Password
properties in Credentials
.
The function signature for GetCredentialsFcn
is:
[username,password] = GetCredentialsFcn(cred,req,resp,authInfo,prevUsername,prevPasswd)
where the arguments are specified as:
cred
— Handle to thisCredentials
objectreq
— Last sent request message that provoked this authentication challenge.resp
— Response message from the server containing anAuthenticateField
. If thecred.Scheme
property is set toBasic
as the only option, then theresp
argument might be empty.authInfo
(optional) — One element in the vector ofAuthInfo
objects returned by theAuthenticateField.convert
method that MATLAB selects to match these credentials. Each object in this array hasScheme
and at least aRealm
parameter.prevUsername
,prevPasswd
(optional) — Initially empty arguments. If nonempty, then these arguments are the values theGetCredentialsFcn
function returned in a previous invocation, but which the server rejected. If you are not prompting for credentials, then compare these values to the ones you plan to return. If they are the same, then authentication will likely fail again. Setusername
to[]
to so that MATLAB returns an authentication failure. If you prompt the user for credentials, then you do not need to specify these arguments. The user can choose to reenter the same or different credentials.username
— Username to use. If a server requires only a password, not a username, then setusername
to an empty string (""
). If theusername
value is[]
, then the authentication failed.password
— Password to use.
By implementing the GetCredentialsFcn
function and leaving theUsername
and/or Password
properties inCredentials
empty, you can implement a prompt to obtain these values from the user without embedding them in your program. In your prompt, display the request URI or the authInfo.Realm
parameter. Another convenient pattern is to set the Username
property and prompt only for the password. Your prompt can display the existing Username
, orprevUsername
, if set, and give the user the option to change it.
The GetCredentialsFcn
function can examine the credentials in the cred
argument and the header fields in the request and response messages to determine which resource is being accessed. Thus, the function can prompt the user for the correct credentials. In general, the prompt should displayauthInfo.Realm
to let the user know the context of the authentication.
Since the Credentials
is a handle class, theGetCredentialsFcn
function stores the username and password in the cred
argument. You can use that object in future requests without calling the function again. MATLAB saves successful usernames and passwords internally to apply them to future requests. However, MATLAB might not always be able to determine whether the same username and password apply to different requests using these credentials.
If GetCredentialsFcn
returns an empty array[]
(not an empty string ""
) for the username, then authentication should be denied and MATLAB returns the server authentication failure in the response message to the caller of RequestMessage.send
. This behavior is appropriate if you implement a user prompt and the user clicks cancel in the prompt. IfprevUsername
and prevPasswd
are identical to the name and password that you would return, then when you programmatically supply the name and password, you must return []
. This value indicates that your credentials are not accepted and you have no alternative choice. Otherwise, an infinite loop might occur calling your GetCredentaislFcn
function repeatedly.
Attributes:
GetAccess | public |
---|---|
SetAccess | public |
Data Types: function_handle
Examples
Add secrets to your MATLAB vault containing your username and password. For more information, seeKeep Sensitive Information Out of Code.
setSecret("Httpbin.Digest.Username") setSecret("Httpbin.Digest.Password")
Create credentials, getting the username and password from your vault.
import matlab.net.; import matlab.net.http.; uri = URI("http://www.httpbin.org/digest-auth/1/user/passwd"); creds = Credentials(Username=secretID("Httpbin.Digest.Username"), ... Password=secretID("Httpbin.Digest.Password"), ... Scheme="Digest"); opts = HTTPOptions(Credentials=creds);
Send the message.
req = RequestMessage(); resp = req.send(uri,opts);
Create a function that prompts for credentials, using theUsername
property from the Credentials
object as a default. MATLAB calls this function to obtain the name and password to use for the authentication response.
Create the getMyCredentials
function.
function [u,p] = getMyCredentials(cred,req,resp,authInfo) prompt = ["Username:" "Password:"]; username = cred.Username; if(isempty(username)) username = ""; end defAns = [username ""]; title = "Credentials needed for " + getParameter(authInfo,'realm'); answer = inputdlg(prompt, title, [1, 60], defAns, 'on'); if isempty(answer) u = []; p = []; else u = answer{1}; p = answer{2}; end end
Create the request message.
cred = matlab.net.http.Credentials('GetCredentialsFcn',@getMyCredentials); options = matlab.net.http.HTTPOptions('Credentials',cred); req = matlab.net.http.RequestMessage;
Send the message to httpbin.org
.
uri = 'httpbin.org/basic-auth/user/passwd'; resp = req.send(uri,options)
Enter any text. To quit, select Cancel.
Version History
Introduced in R2016b