Main Content Class

Superclasses: handle

Credentials for authenticating HTTP requests


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 an AuthenticateField 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 a StatusCode of 401 or 407. In this case, you must implement the appropriate response yourself.

For schemes that do not require Username and Password properties, such as NTLM on Windows®, you can use a default Credentials object. A default Credentials 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 as Scope and Realm. 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 same Credentials object on subsequent requests in the same or other HTTPOptions 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 class is a handle class.

Class Attributes


For information on class attributes, see Class Attributes.




obj =,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 as Name1,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 user name or password. For example, on Windows, the object enables NTLM and Kerberos authentication using the credentials of the logged-in user.


expand all

Authentication schemes for credentials, specified as a vector of 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 require Basic authentication, this scheme unnecessarily exposes the Username and Password properties to the server.

If this property includes any scheme besides or in addition to Basic, 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 same Scope include the appropriate authorization information without first requiring a challenge.



URIs to which credentials apply, specified as a vector of objects or strings or character vectors. Strings must be acceptable to the URI constructor or of the form host/path/....

An empty Scope value, or an empty Host or Path in this vector matches all Host or Path properties. Do not leave Scope empty if Scheme 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 the HTTPOptions 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 this Scope. A Scope containing a URI naming a host with no path applies to all paths on that host.

For example, a host name in a Scope matches a request to and A URI matches a request to but not to The /products path is not at or deeper than /products/stateflow.

Only the Host, Port, and Path properties of the Scope URIs are used. Typically you only specify a Host name, such as 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.



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 unspecified Realm. 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 an AuthenticateField 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.



User name for authentication schemes, specified as a string 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.

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, unless GetCredentialsFcn is specified. If you set this property to [], then you must specify GetCredentialsFcn or authentication is not attempted.

If you do not want to embed a user name in your code, then leave this property empty and specify a GetCredentialsFcn that prompts the user for a name or obtains it from another source.



Password for authentication schemes, specified as a string 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.

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, unless GetCredentialsFcn is specified. If you set this property to [] and there is no GetCredentialsFcn property, then no password is provided.

If you do not want to embed a password in your code, then leave this property empty and specify a GetCredentialsFcn that prompts the user for a password or obtains it from another source.



Function returning the Username and Password for authentication, specified as a function handle. This property applies only to schemes requiring you to specify a user 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 this Credentials object

  • req — Last sent request message that provoked this authentication challenge.

  • resp — Response message from the server containing an AuthenticateField. If the cred.Scheme property is set to Basic as the only option, then the resp argument might be empty.

  • authInfo (optional) — One element in the vector of AuthInfo objects returned by the AuthenticateField.convert method that MATLAB selects to match these credentials. Each object in this array has Scheme and at least a Realm parameter.

  • prevUsername, prevPasswd (optional) — Initially empty arguments. If nonempty, then these arguments are the values the GetCredentialsFcn 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. Set username 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 — User name to use. If a server requires only a password, not a user name, then set username to an empty string (''). If the username value is [], then the authentication failed.

  • password — Password to use.

By implementing the GetCredentialsFcn function and leaving the Username and/or Password properties in Credentials 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, or prevUsername, 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 display authInfo.Realm to let the user know the context of the authentication.

Since the Credentials is a handle class, the GetCredentialsFcn function stores the user name and password in the cred argument. You can use that object in future requests without calling the function again. MATLAB saves successful user names and passwords internally to apply them to future requests. However, MATLAB might not always be able to determine whether the same user name and password apply to different requests using these credentials.

If GetCredentialsFcn returns an empty array [] (not an empty string '') for the user name, 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. If prevUsername 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.



Data Types: function_handle


collapse all

Create credentials that are sent to only the appropriate server.

Create a secret in your MATLAB vault containing your password. For more information, see Keep Sensitive Information Out of Code.


Create credentials, getting the password from your vault.

scope = URI('');
creds = Credentials('Username','John','Password',getSecret("JohnPassword"),'Scope',scope);
options = HTTPOptions('Credentials',creds);

Send the message. If the server requires authentication, then the transaction involves an exchange of several messages.

resp = RequestMessage().send(scope,options);

Next, reuse the options that contain the same credentials. Since the credentials already have been used successfully, this transaction requires a single message.

resp = RequestMessage().send(scope,options)

Create a function that prompts for credentials, using the Username 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:" "PasswordKey:"];
username = cred.Username;
    username = "";
defAns = [username ""];
title = "Credentials needed for " + getParameter(authInfo,'realm');
answer = inputdlg(prompt, title, [1, 60], defAns, 'on');
if isempty(answer)
    u = [];
    p = [];
    u = answer{1};
    p = getSecret(answer{2});

Create the request message.

cred ='GetCredentialsFcn',@getMyCredentials);
options ='Credentials',cred);
req =;

Send the message to

uri = '';
resp = req.send(uri,options)

Enter any text. To quit, select Cancel.

Version History

Introduced in R2016b