Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

matlab.net.http.Credentials class

Package: 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 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.

MATLAB only implements the Basic and Digest authentication schemes. If the server requires other schemes, or you do not supply credentials for the required scheme, then the authentication response message returns a StatusCode object of 401 or 407. In which case, you must implement the appropriate response yourself.

After a successful authentication, MATLAB saves the information in the Credentials object. If you apply these credentials on subsequent requests to the same server, then MATLAB does not wait for an authentication challenge from the server. To apply the credentials, provide the same Credentials object for every request.

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.

Construction

example

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 as Name1,Value1,...,NameN,ValueN. Unspecified properties are set to their default values.

Properties

expand all

Authentication schemes for credentials, specified as a vector of matlab.net.http.AuthenticationScheme objects. The default value is AuthenticationScheme.Basic and AuthenticationScheme.Digest. If Scheme is empty, then the credentials apply to all authentication schemes.

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 one of the options is Digest or if Scheme is empty, then the first message to which these credentials potentially apply is sent without an Authorization header field. The message is chosen based on the Scope property and the request URI. These Credentials are used only after the server responds with a challenge and if the Scope and Realm properties match the URI and the server challenge.

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 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 mathworks.com host name in a Scope matches a request to www.mathworks.com and anything.mathworks.com. A mathworks.com/products/stateflow URI matches a request to www.mathworks.com/products/stateflow/features but not to www.mathworks.com/products. 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 www.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.

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 is an empty string, 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. 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 Basic or Digest authentication schemes, specified as a string or character vector. 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.

Password for Basic or Digest authentication schemes, specified as a string or character vector. Use the Password property to authenticate any request for which these credentials apply, unless the GetCredentialsFcn property is specified. If the Password value is [], then no password is provided.

Function returning the Username and Password for authentication, specified as a function handle. 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 request.

  • resp — Response message from the server containing an AuthenticateField. If the cred.Scheme property is set to only Basic, 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 Realm fields.

  • prevUsername, prevPasswd (optional) — Initially empty arguments. If set, these arguments are the values the GetCredentialsFcn function returned in a previous invocation, which the server did not accept. If you are not prompting for credentials, then compare these values to the ones you plan to return. If they are the same, set username to [] to indicate an authentication failure. If you prompt the user for credentials, then you do not need to specify these arguments.

  • 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 property. A 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 cred argument is a handle, the GetCredentialsFcn function stores the user name and password in the object. You can use that object in future requests without calling the function again. MATLAB saves the name and password 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 authentication is denied, then GetCredentialsFcn returns an empty array [] (not an empty string '') for the user name. MATLAB returns the server authentication failure in the response message. 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

Examples

expand all

Create credentials that are sent to only the appropriate server.

import matlab.net.http.Credentials
scope = URI('http://my.server.com');
creds = Credentials('Username','John','Password','secret','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)
    u = cred.Username;
    prompt{1} = 'Username:';
    prompt{2} = 'Password:';
    defAns = {char(u), ''};
    title = ['Credentials needed for ' char(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.

Copy Semantics

Handle. To learn how handle classes affect copy operations, see Copying Objects.

Credentials objects are handle objects and internally accumulate information about prior successful authentications, so that you can reuse the information for subsequent messages. If you insert this object into multiple HTTPOptions objects, then Credentials might be updated on 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.

Introduced in R2016b

Was this topic helpful?