Authentication and sessions

View as Markdown

Almost every call needs a session. LogIn authenticates the caller and returns a session ID; no request message has a field for it. It travels in the binary call metadata mfiles-session-id-bin of every later call.

LogIn  ->  session_data.session_id (48 bytes)
every call  ->  metadata  mfiles-session-id-bin: <the 48 bytes, unchanged>

gRPC libraries base64-encode -bin metadata values themselves: pass the raw bytes. The value must be exactly the 48 bytes from session_data.session_id; other lengths are rejected. A session belongs to one vault, or to no vault (a server-level session).

Calls that need no session

QueryVersion, GetServerCapabilities, GetAuthenticationConfiguration, LogIn and a few public methods (for example those of IRPCSharedLinksPublic, which a shared link's access key authorizes) are served without a session. The reference marks each method with its session requirement.

Choosing the authentication method

authentication_data.type Use for Round trips
AUTH_DATA_TYPE_PLUGIN An authentication plugin: M-Files Login Service, or other OAuth / OpenID Connect single sign-on with a token 1 or more
AUTH_DATA_TYPE_CREDENTIALS User name and password: M-Files (CREDENTIALS_TYPE_MFILES) or Windows (CREDENTIALS_TYPE_WINDOWS) accounts 1
AUTH_DATA_TYPE_WINDOWS The current Windows user, single sign-on with SSPI 2 or more
AUTH_DATA_TYPE_ANONYMOUS Anonymous access, where a vault allows it 1
AUTH_DATA_TYPE_MFILES_LEG1, _LEG2 Challenge-response for M-Files accounts; the password itself is not sent. Not covered here 2

Use single sign-on where the vault offers it: M-Files Login Service, or the vault's other authentication plugin. Use a user name and password for M-Files accounts. Windows authentication (SSPI) is for on-premises servers in a Windows domain; new applications seldom need it.

To learn what a server or vault expects, call GetAuthenticationConfiguration anonymously. AUTH_METHOD_PLUGIN with plugin information means single sign-on through that plugin; AUTH_METHOD_UNSPECIFIED with no plugins means the server has no plugin configured for the target and you use credentials or Windows authentication.

Credentials and tokens travel in the request. Send them only over TLS (Connecting).

The sequences at a glance

Each method's section below has the fields of every step.

Login Service   GetAuthenticationConfiguration  ->  browser: authorize with PKCE  ->  code
                ->  POST TokenEndpoint  ->  access token, refresh token
                ->  LogIn (plugin, Token = access token)  ->  session
                later: POST TokenEndpoint (refresh token)  ->  LogIn again
SSO token       GetAuthenticationConfiguration  ->  sign in at the identity provider  ->  token
                ->  LogIn (plugin, Token)  ->  session
Password        LogIn (credentials)  ->  session
Windows (SSPI)  SSPI token  ->  LogIn (windows)  ->  server's token  ->  SSPI  ->  next token
                ->  LogIn (windows, attempt ID)  ...  until the response has a session
Anonymous       LogIn (anonymous)  ->  session

Then            every call with mfiles-session-id-bin; KeepAlive on a timer; LogOut at the end

The login loop

Every type uses the same loop. Single-step types finish in the first call.

  1. Call LogIn with environment_data, client_data, login_data and authentication_data.
  2. If response.session_data.session_id is set, the login is complete.
  3. Otherwise the server needs another step: send LogIn again with the next authentication data, and copy response.authentication_data.authentication_attempt_identifier into the authentication_attempt_identifier field of the union member you send (for example data.plugin.authentication_attempt_identifier). Repeat from 2.

The server's half of the exchange is in response.authentication_data.data. For plugin and Windows authentication it carries the next token or values and is_done.

A failed authentication is reported as E_MFILES_AUTHENTICATION_FAILED ("Authentication failed.") without details: a wrong password, an unknown user and a login blocked by the server's login attack protection look the same. Repeated failures make the protection block further attempts for a while, so do not retry a failing login in a loop.

The fields of LogIn are the same for every method except authentication_data:

Field Value
environment_data.client_name Your program's name; the server shows it in its list of sessions
environment_data.host_platform Optional: your platform, for example Python
client_data.type CLIENT_TYPE_SERVER_API
client_data.language A language code, for example en
client_data.capabilities.long_authentication_attempt_identifier true: plugin logins need it
login_data.server_hostname The host name you connected to
login_data.vault_guid The vault's GUID, with braces (see below)
authentication_data type and the matching member of data, as the sections below describe

The client packages' helpers log in in one step and stop if the server asks for more:

Python

# Log in to the vault, naming the client and how it authenticates.
request = IRPCLogin_pb2.LogInRequest(
    environment_data=structs_pb2.EnvironmentData(
        client_name=self.client_name, host_platform="Python"),
    client_data=self._client_data(),
    login_data=structs_pb2.LoginData(
        server_hostname=self.config.host, vault_guid=self.config.vault),
    authentication_data=authentication)
response = self.login.LogIn(request)
if not response.session_data.session_id:
    raise RuntimeError("LogIn did not complete: the authentication needs more steps")
# From now on, the interceptor sends this in "mfiles-session-id-bin" on every call.
self.session_id = response.session_data.session_id

Full source: mfiles-grpc-python/src/mfiles_grpc/client.py

C#

// Log in: who the client is, which vault it opens and how it authenticates.
var request = new LogInRequest
{
    EnvironmentData = new EnvironmentData { ClientName = clientName, HostPlatform = ".NET" },
    ClientData = new ClientData
    {
        Type = ClientType.ServerApi,
        Language = "en",
        // Needed for the 32-byte attempt ID of a token login.
        Capabilities = new ClientCapabilities { LongAuthenticationAttemptIdentifier = true },
    },
    LoginData = new LoginData { ServerHostname = _host, VaultGuid = vault },
    AuthenticationData = authentication,
};
var login = new IRPCLogin.IRPCLoginClient(CallInvoker);
var response = await login.LogInAsync(request, cancellationToken: cancellationToken);

// A one-step login returns the session in the response.
if (response.SessionData is not { SessionId.IsEmpty: false } session)
    throw new InvalidOperationException(
        "LogIn returned no session; this helper supports one-step logins only.");

// Every later call sends this session ID in mfiles-session-id-bin (see MFilesCallInvoker).
Session = session;

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

Go


// LogInWith logs in to a vault. From then on every call carries the session. It returns the
// session.
//   - ctx: cancels the call.
//   - vault: the vault GUID, with braces.
//   - auth: the authentication data, e.g. from PasswordAuth or TokenAuth.
//   - clientName: shown in the server's session list; "" for the program's name.
func (c *Client) LogInWith(ctx context.Context, vault string, auth *mfiles.AuthDataClient,
	clientName string) (*mfiles.SessionData, error) {
	// Without a client name, the program's file name.
	if clientName == "" {
		clientName = filepath.Base(os.Args[0])
	}

	// Log in as a server API client.
	response, err := mfiles.NewIRPCLoginClient(c.Conn).LogIn(ctx, &mfiles.LogInRequest{
		EnvironmentData: &mfiles.EnvironmentData{ClientName: clientName, HostPlatform: "Go"},
		ClientData: &mfiles.ClientData{
			Type:     mfiles.ClientType_CLIENT_TYPE_SERVER_API,
			Language: "en",
			// A plugin (token) login uses the 32-byte form of the attempt identifier.
			Capabilities: &mfiles.ClientCapabilities{LongAuthenticationAttemptIdentifier: true},
		},
		LoginData:          &mfiles.LoginData{ServerHostname: c.host, VaultGuid: vault},
		AuthenticationData: auth,
	})
	if err != nil {
		return nil, err
	}

	// A completed login returns a session ID.
	session := response.GetSessionData()
	if len(session.GetSessionId()) == 0 {
		// A plugin that needs more than one round trip answers without a session.
		return nil, errors.New("LogIn returned no session: multi-step authentication is not supported")
	}

	// From now on the interceptor sends session_id in mfiles-session-id-bin on every call.
	c.mu.Lock()
	c.session = session
	c.mu.Unlock()
	return session, nil
}

Full source: mfiles-grpc-go/mfilesclient/client.go

M-Files Login Service

M-Files Login Service is M-Files' own OpenID Connect sign-in service. It signs the user in with the identity provider of their organization (for example Microsoft Entra ID) and issues tokens for the vault. A vault that uses it returns the plugin MFLoginService.Default (assembly MFiles.AuthenticationProviders.OAuth) from GetAuthenticationConfiguration. When a vault offers it, use it: your application then signs users in the same way as M-Files' own clients.

The plugin's plugin_configuration has everything the sign-in needs. Read it from the vault every time; do not hard-code it, because the endpoints differ between environments and the client ID and scope belong to the vault:

Setting Example Use
AuthorizationEndpoint https://<login service>/connect/authorize Where the browser signs in
TokenEndpoint https://<login service>/connect/token Where you exchange the code and refresh tokens
ClientID mfclient,<vault GUID> client_id. A public client: there is no client secret
Scope openid mfiles://<vault host> offline_access scope. offline_access gets you a refresh token
RedirectURI http://localhost/signin-oidc Its path is the path of your redirect URI (see below)
UsePkceWithAuthorizationCode true Use PKCE (S256)
UseIdTokenAsAccessToken false Send the access token, not the ID token, to LogIn
LogoutEndpoint https://<login service>/connect/endsession To sign the user out of the Login Service

system_configuration has Scope (for example *: or *:WINDOWS:) and VaultGUID, which go into LogIn.

The sign-in is the OAuth 2.0 authorization code flow with PKCE, in the user's browser:

  1. Discover. Call GetAuthenticationConfiguration anonymously, with host_name and with type ACCOUNT_TYPE_WINDOWS (see Single sign-on below). Use the plugin whose name starts with MFLoginService. Read the settings above from its plugin_configuration, and Scope and VaultGUID from its system_configuration.
  2. Prepare. Make a random PKCE code_verifier (43 to 128 URL-safe characters), its code_challenge (the SHA-256 hash of the verifier, base64url-encoded without padding) and a random state. Listen for the browser's redirect on http://127.0.0.1:<any free port> with the path of RedirectURI. The Login Service accepts any port with the loopback IP address (as RFC 8252 describes for native apps), but not with the name localhost: an authorization request with http://localhost:<port>/... ends on the Login Service's error page.
  3. Sign in in the browser. Open AuthorizationEndpoint with the query parameters client_id (ClientID), response_type=code, scope (Scope), redirect_uri (your loopback URI), state, code_challenge and code_challenge_method=S256. The browser comes back to your loopback URI with code and state, or with error. Accept the reply only if state is the one you sent.
  4. Get the tokens. POST to TokenEndpoint, form-encoded: grant_type=authorization_code, code, the same redirect_uri, client_id and code_verifier. There is no client secret. The JSON reply has access_token, expires_in and, with offline_access in the scope, refresh_token.
  5. Log in with plugin authentication, with the fields of Single sign-on below: plugin_name is the plugin's name, configuration_scope is Scope, vault_guid is VaultGUID, and the Token value is the access token (the id_token if UseIdTokenAsAccessToken is true). If you don't know the vault yet, VaultGUID is also the GUID for login_data.vault_guid.
  6. Log in again later, without the browser, when the session has expired: POST to TokenEndpoint with grant_type=refresh_token, refresh_token and client_id (no secret and no PKCE). Store the new refresh token from the reply (see Programs that run without a person) and call LogIn with the new access token.

The client packages' helpers do these steps, with a token cache for step 6 that keeps the refresh token in the operating system's credential store. MFILES_AUTH=browser makes every example sign in this way; the recipe login_service shows it on its own. Some identity providers compare the redirect URI with its port; for them the helpers can listen on the configured RedirectURI itself.

Python

# Users who sign in through an identity provider have Windows-type login accounts, and a
# vault can limit its configuration to that type; ask for it first, then for M-Files ones.
offered = []
for account_type in (enums_pb2.ACCOUNT_TYPE_WINDOWS, enums_pb2.ACCOUNT_TYPE_MFILES):
    response = client.login.GetAuthenticationConfiguration(
        IRPCLogin_pb2.GetAuthenticationConfigurationRequest(
            vault_guid=vault, host_name=client.config.host, type=account_type))
    if any(p.assembly_name == OAUTH_ASSEMBLY and (not name or p.name == name)
           for p in response.plugin_infos):
        return oauth_config_from_plugins(response.plugin_infos, name)
    offered.extend(response.plugin_infos)

Full source: mfiles-grpc-python/src/mfiles_grpc/sso.py

# The authorization code flow with PKCE.
parameters = {
    "response_type": "code",
    "client_id": config.client_id,
    "redirect_uri": redirect_uri,
    "scope": " ".join(config.scopes),
    "state": state,
    "code_challenge": challenge,
    "code_challenge_method": "S256",
}
# v1 endpoints (AD FS, Entra ID v1) name the API by resource instead of by scope.
if config.resource and "/v2.0/" not in config.authorization_endpoint:
    parameters["resource"] = config.resource

Full source: mfiles-grpc-python/src/mfiles_grpc/sso.py

# PKCE, and a random state that ties the answer to this request.
verifier, challenge = pkce_pair()
state = secrets.token_urlsafe(16)

# Listen for the browser's redirect on the loopback address, and open the sign-in page.
with _LoopbackListener(config.redirect_uri, exact_redirect_uri) as listener:
    url = authorization_url(config, listener.redirect_uri, state, challenge)
    print(f"Opening the browser to sign in. If it does not open, visit:\n  {url}")
    open_browser(url)

    # Wait for the answer, and accept only the one to this request.
    code = parse_callback(listener.wait(timeout), state)

# Exchange the code for tokens. A native client has no secret: PKCE proves that it started
# the flow.
return _token_request(config, {
    "grant_type": "authorization_code",
    "code": code,
    "redirect_uri": listener.redirect_uri,
    "client_id": config.client_id,
    "code_verifier": verifier,
}, post)

Full source: mfiles-grpc-python/src/mfiles_grpc/sso.py

# No secret and no PKCE: the refresh token itself is the proof.
return _token_request(config, {
    "grant_type": "refresh_token",
    "refresh_token": refresh_token,
    "client_id": config.client_id,
}, post)

Full source: mfiles-grpc-python/src/mfiles_grpc/sso.py

# The token goes to the plugin with its name, configuration scope and vault.
token = sso.acquire_token(config, cache, open_browser, timeout)
return self.log_in_with_token(token, config.plugin_name, config.configuration_scope,
                              config.vault_guid)

Full source: mfiles-grpc-python/src/mfiles_grpc/client.py

C#

// Users who sign in through an identity provider have Windows-type login accounts, and a
// vault can limit its configuration to that type; ask for it first, then for M-Files ones.
var login = new IRPCLogin.IRPCLoginClient(CallInvoker);
var offered = new List<PluginInfo>();
foreach (var accountType in new[] { AccountType.Windows, AccountType.Mfiles })
{
    var response = await login.GetAuthenticationConfigurationAsync(
        new GetAuthenticationConfigurationRequest
        {
            VaultGuid = vault ?? "",
            HostName = _host,
            Type = accountType,
        }, cancellationToken: cancellationToken);
    if (response.PluginInfos.Any(p => p.AssemblyName == OAuthSignIn.OAuthAssembly
        && (pluginName is null || p.Name == pluginName)))
        return OAuthSignIn.FromPlugins(response.PluginInfos, pluginName);
    offered.AddRange(response.PluginInfos);
}

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

// The authorization code flow with PKCE.
var parameters = new Dictionary<string, string>
{
    ["response_type"] = "code",
    ["client_id"] = config.ClientId,
    ["redirect_uri"] = redirectUri,
    ["scope"] = string.Join(' ', config.Scopes),
    ["state"] = state,
    ["code_challenge"] = challenge,
    ["code_challenge_method"] = "S256",
};
// v1 endpoints (AD FS, Entra ID v1) name the API by resource instead of by scope.
if (config.Resource != "" && !config.AuthorizationEndpoint.Contains("/v2.0/"))
    parameters["resource"] = config.Resource;

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/OAuthSignIn.cs

// PKCE, and a random state that ties the answer to this request.
options ??= new BrowserSignInOptions();
var (verifier, challenge) = CreatePkce();
string state = RandomText(16);

// Listen for the browser's redirect on the loopback address, and open the sign-in page.
using var listener = LoopbackListener.Start(config.RedirectUri, options.ExactRedirectUri);
string url = AuthorizationUrl(config, listener.RedirectUri, state, challenge);
await options.Output.WriteLineAsync(
    $"Opening the browser to sign in. If it does not open, visit:\n  {url}");
await OpenBrowserAsync(options, url);

// Wait for the answer, and accept only the one to this request.
var query = await listener.WaitAsync(options.Timeout, cancellationToken);
string code = ParseCallback(query, state);

// Exchange the code for tokens. A native client has no secret: PKCE proves that it
// started the flow.
return await PostTokenRequestAsync(config, options.HttpClient, new()
{
    ["grant_type"] = "authorization_code",
    ["code"] = code,
    ["redirect_uri"] = listener.RedirectUri,
    ["client_id"] = config.ClientId,
    ["code_verifier"] = verifier,
}, cancellationToken);

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/OAuthSignIn.cs

// No secret and no PKCE: the refresh token itself is the proof.
return PostTokenRequestAsync(config, httpClient, new()
{
    ["grant_type"] = "refresh_token",
    ["refresh_token"] = refreshToken,
    ["client_id"] = config.ClientId,
}, cancellationToken);

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/OAuthSignIn.cs

// The token goes to the plugin with its name, configuration scope and vault.
string token = await OAuthSignIn.AcquireTokenAsync(config, options,
    TokenCache.EntryName(_host, target), cancellationToken);
return await LogInWithTokenAsync(target, token, config.PluginName, config.ConfigurationScope,
    clientName, cancellationToken, config.VaultGuid);

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

Go

// Users who sign in through an identity provider have Windows-type login accounts, and a
// vault can limit its configuration to that type; ask for it first, then for M-Files ones.
var offered []*mfiles.PluginInfo
for _, accountType := range []mfiles.AccountType{
	mfiles.AccountType_ACCOUNT_TYPE_WINDOWS, mfiles.AccountType_ACCOUNT_TYPE_MFILES,
} {
	response, err := mfiles.NewIRPCLoginClient(c.Conn).GetAuthenticationConfiguration(ctx,
		&mfiles.GetAuthenticationConfigurationRequest{
			VaultGuid: vault, HostName: c.host, Type: accountType,
		})
	if err != nil {
		return nil, err
	}
	if cfg, err := OAuthConfigFromPlugins(response.GetPluginInfos(), name); err == nil {
		return cfg, nil
	}
	offered = append(offered, response.GetPluginInfos()...)
}

Full source: mfiles-grpc-go/mfilesclient/oauth.go

// The authorization code flow with PKCE.
parameters := url.Values{
	"response_type":         {"code"},
	"client_id":             {cfg.ClientID},
	"redirect_uri":          {redirectURI},
	"scope":                 {strings.Join(cfg.Scopes, " ")},
	"state":                 {state},
	"code_challenge":        {challenge},
	"code_challenge_method": {"S256"},
}
// v1 endpoints (AD FS, Entra ID v1) name the API by resource instead of by scope.
if cfg.Resource != "" && !strings.Contains(cfg.AuthorizationEndpoint, "/v2.0/") {
	parameters.Set("resource", cfg.Resource)
}

Full source: mfiles-grpc-go/mfilesclient/oauth.go

// PKCE, and a random state that ties the answer to this request.
verifier, challenge, err := NewPKCE()
if err != nil {
	return Tokens{}, err
}
state, err := randomText(16)
if err != nil {
	return Tokens{}, err
}

// Listen for the browser's redirect on the loopback address, and open the sign-in page.
callback, err := listenForCallback(cfg.RedirectURI, opts.ExactRedirectURI)
if err != nil {
	return Tokens{}, err
}
defer callback.close()
address, err := AuthorizationURL(cfg, callback.redirectURI, state, challenge)
if err != nil {
	return Tokens{}, err
}
fmt.Fprintf(opts.messages(), "Opening the browser to sign in. If it does not open, visit:\n  %s\n",
	address)
if err := opts.openBrowser(address); err != nil {
	fmt.Fprintf(opts.messages(), "Could not open the browser: %v\n", err)
}

// Wait for the answer, and accept only the one to this request.
query, err := callback.wait(ctx, opts.timeout())
if err != nil {
	return Tokens{}, err
}
code, err := ParseCallback(query, state)
if err != nil {
	return Tokens{}, err
}

// Exchange the code for tokens. A native client has no secret: PKCE proves that it started
// the flow.
return postTokenRequest(ctx, cfg, opts.httpClient(), url.Values{
	"grant_type":    {"authorization_code"},
	"code":          {code},
	"redirect_uri":  {callback.redirectURI},
	"client_id":     {cfg.ClientID},
	"code_verifier": {verifier},
})

Full source: mfiles-grpc-go/mfilesclient/oauth.go

// No secret and no PKCE: the refresh token itself is the proof.
return postTokenRequest(ctx, cfg, BrowserSignIn{HTTPClient: httpClient}.httpClient(),
	url.Values{
		"grant_type":    {"refresh_token"},
		"refresh_token": {refreshToken},
		"client_id":     {cfg.ClientID},
	})

Full source: mfiles-grpc-go/mfilesclient/oauth.go

// The token goes to the plugin with its name, configuration scope and vault.
token, err := AcquireToken(ctx, cfg, opts, TokenCacheEntry(c.host, vault))
if err != nil {
	return nil, err
}
auth := TokenAuth(token, cfg.PluginName, cfg.ConfigurationScope)
auth.GetData().GetPlugin().VaultGuid = cfg.VaultGUID
return c.LogInWith(ctx, vault, auth, clientName)

Full source: mfiles-grpc-go/mfilesclient/oauth.go

Programs that run without a person

A service or scheduled job cannot open a browser. With M-Files Login Service it signs in once interactively and then renews its tokens with the refresh token:

So a program that renews logins unattended must:

The refresh token's own lifetime, and how conditional-access policies of the user's organization affect it, are set by the Login Service and the identity provider; plan for an occasional interactive sign-in.

Single sign-on (plugin authentication)

This works with any authentication plugin; M-Files Login Service above is one of them. The server does not run the identity provider's sign-in for you. Your client obtains a token from the identity provider and hands it to LogIn:

  1. Discover, anonymously: GetAuthenticationConfiguration with host_name set to the host you connect to (or with vault_guid), and type set to ACCOUNT_TYPE_WINDOWS: users who sign in through an identity provider have Windows-type login accounts, and a vault can limit its configuration to that account type (configuration scope *:WINDOWS:). Such a vault returns no plugin when type is left out. The response names the plugin (plugin_infos[].name, for example MFLoginService.Default, assembly MFiles.AuthenticationProviders.OAuth). Its plugin_configuration holds the identity provider settings (AuthorizationEndpoint, TokenEndpoint, ClientID, Scope, RedirectURI, UsePkceWithAuthorizationCode, UseAccessTokenInWeb, ...) and its system_configuration holds Scope (the configuration scope) and VaultGUID.
  2. Sign in at the identity provider with those settings (for OAuth: authorization code flow, with PKCE when UsePkceWithAuthorizationCode says so) and get the token.
  3. Log in with type: AUTH_DATA_TYPE_PLUGIN and data.plugin:
Field Value
plugin_name plugin_infos[].name
configuration_scope system_configuration value Scope
vault_guid system_configuration value VaultGUID, when present
authentication_attempt_identifier.data 32 zero bytes in the first call
data_format PLUGIN_AUTH_DATA_FORMAT_UNENCRYPTED
auth_data One named value: key Token, a DATATYPE_TEXT typed value holding the token

The token is the access token, or the ID token when the plugin's configuration says so: UseIdTokenAsAccessToken true, or UseAccessTokenInWeb false. With neither setting, M-Files' web client sends the ID token.

A plugin can ask for more steps; the response then has data.plugin.is_done false and no session. Continue with the loop above. The session you get is the same kind as from a password login.

Most vaults have one plugin, so a client can discover it rather than ask the user. The samples' helpers do this when MFILES_AUTH_PLUGIN or MFILES_AUTH_SCOPE is not set, and use the plugin marked as the default when there are several. Then they build the authentication data:

Python

# Users who sign in through an identity provider have Windows-type login accounts. A
# vault can limit its configuration to that account type, and then answers only when the
# type is given.
response = self.login.GetAuthenticationConfiguration(
    IRPCLogin_pb2.GetAuthenticationConfigurationRequest(
        vault_guid=self.config.vault, host_name=self.config.host,
        type=enums_pb2.ACCOUNT_TYPE_WINDOWS))
plugins = [p for p in response.plugin_infos if not name or p.name == name]
if len(plugins) > 1:
    plugins = [p for p in plugins if p.is_default]
if len(plugins) != 1:
    offered = ", ".join(p.name for p in response.plugin_infos) or "none"
    raise SystemExit("Set MFILES_AUTH_PLUGIN and MFILES_AUTH_SCOPE; "
                     f"the vault's authentication plugins: {offered}")
system = {v.key: v.value.data.text for v in plugins[0].system_configuration.value}

Full source: mfiles-grpc-python/src/mfiles_grpc/client.py

# Plugin authentication data, with the token as the single named value "Token".
plugin_data = structs_pb2.AuthDataClientUnion.PluginData(
    plugin_name=plugin,
    configuration_scope=scope,
    vault_guid=plugin_vault,
    authentication_attempt_identifier=structs_pb2.AuthenticationAttemptIdentifier(
        data=bytes(32)),
    data_format=enums_pb2.PLUGIN_AUTH_DATA_FORMAT_UNENCRYPTED,
    auth_data=[structs_pb2.NamedValue(key="Token", value=structs_pb2.TypedValue(
        type=enums_pb2.DATATYPE_TEXT, data=structs_pb2.TypedValueUnion(text=token)))])
authentication = structs_pb2.AuthDataClient(
    type=enums_pb2.AUTH_DATA_TYPE_PLUGIN,
    data=structs_pb2.AuthDataClientUnion(plugin=plugin_data))

Full source: mfiles-grpc-python/src/mfiles_grpc/client.py

C#

// Get the vault's authentication plugins. Users who sign in through an identity provider
// have Windows-type login accounts. A vault can limit its configuration to that account
// type, and then answers only when the type is given.
var login = new IRPCLogin.IRPCLoginClient(CallInvoker);
var response = await login.GetAuthenticationConfigurationAsync(
    new GetAuthenticationConfigurationRequest
    {
        VaultGuid = vault,
        HostName = _host,
        Type = AccountType.Windows,
    }, cancellationToken: cancellationToken);

// Choose one plugin: the one with the given name, the only one, or the default one.
var plugins = response.PluginInfos.Where(p => name is null || p.Name == name).ToList();
if (plugins.Count > 1)
    plugins = plugins.Where(p => p.IsDefault).ToList();
if (plugins.Count != 1)
{
    string offered = string.Join(", ", response.PluginInfos.Select(p => p.Name));
    throw new InvalidOperationException("Set MFILES_AUTH_PLUGIN and MFILES_AUTH_SCOPE; " +
        $"the vault's authentication plugins: {(offered.Length > 0 ? offered : "none")}.");
}

// The plugin's system configuration holds its scope and vault as text values.
var system = plugins[0].SystemConfiguration.Value
    .ToDictionary(v => v.Key, v => v.Value.Data.Text);

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

// The authentication data: the token, for the vault's authentication plugin.
var authentication = new AuthDataClient
{
    Type = AuthDataType.Plugin,
    Data = new AuthDataClientUnion
    {
        Plugin = new AuthDataClientUnion.Types.PluginData
        {
            // A one-step exchange: an all-zero 32-byte attempt ID.
            AuthenticationAttemptIdentifier = new AuthenticationAttemptIdentifier
            {
                Data = ByteString.CopyFrom(new byte[32]),
            },
            PluginName = pluginName,
            ConfigurationScope = configurationScope,
            VaultGuid = pluginVault,
            DataFormat = PluginAuthDataFormat.Unencrypted,
            // The token is the only named value, "Token".
            AuthData =
            {
                new NamedValue
                {
                    Key = "Token",
                    Value = new TypedValue
                    {
                        Type = Datatype.Text,
                        Data = new TypedValueUnion { Text = token },
                    },
                },
            },
        },
    },
};

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

Go

// Users who sign in through an identity provider have Windows-type login accounts. A vault can
// limit its configuration to that account type, and then answers only when the type is given.
response, err := mfiles.NewIRPCLoginClient(c.Conn).GetAuthenticationConfiguration(ctx,
	&mfiles.GetAuthenticationConfigurationRequest{
		VaultGuid: vault,
		HostName:  c.host,
		Type:      mfiles.AccountType_ACCOUNT_TYPE_WINDOWS,
	})
if err != nil {
	return AuthPlugin{}, err
}

// Of the plugins called name (all of them when name is ""), use the only one, or else the
// only default one.
var plugins, defaults []*mfiles.PluginInfo
for _, p := range response.GetPluginInfos() {
	if name == "" || p.GetName() == name {
		plugins = append(plugins, p)
		if p.GetIsDefault() {
			defaults = append(defaults, p)
		}
	}
}
if len(plugins) > 1 {
	plugins = defaults
}
if len(plugins) != 1 {
	offered := "none"
	if names := pluginNames(response.GetPluginInfos()); len(names) > 0 {
		offered = strings.Join(names, ", ")
	}
	return AuthPlugin{}, fmt.Errorf("set MFILES_AUTH_PLUGIN and MFILES_AUTH_SCOPE; "+
		"the vault's authentication plugins: %s", offered)
}

// The scope and the plugin's vault GUID are values of its system configuration.
found := AuthPlugin{Name: plugins[0].GetName()}
for _, v := range plugins[0].GetSystemConfiguration().GetValue() {
	switch v.GetKey() {
	case "Scope":
		found.Scope = v.GetValue().GetData().GetText()
	case "VaultGUID":
		found.Vault = v.GetValue().GetData().GetText()
	}
}

Full source: mfiles-grpc-go/mfilesclient/client.go


// TokenAuth is the authentication data of a token from the vault's identity provider (SSO):
// the token is the only named value, "Token", for the vault's authentication plugin.
//   - token: the token from the identity provider.
//   - plugin: the authentication plugin's name.
//   - scope: the plugin's configuration scope.
func TokenAuth(token, plugin, scope string) *mfiles.AuthDataClient {
	return &mfiles.AuthDataClient{
		Type: mfiles.AuthDataType_AUTH_DATA_TYPE_PLUGIN,
		Data: &mfiles.AuthDataClientUnion{Data: &mfiles.AuthDataClientUnion_Plugin{
			Plugin: &mfiles.AuthDataClientUnion_PluginData{
				AuthenticationAttemptIdentifier: &mfiles.AuthenticationAttemptIdentifier{
					Data: make([]byte, 32),
				},
				PluginName:         plugin,
				ConfigurationScope: scope,
				DataFormat:         mfiles.PluginAuthDataFormat_PLUGIN_AUTH_DATA_FORMAT_UNENCRYPTED,
				AuthData:           []*mfiles.NamedValue{{Key: "Token", Value: Text(token)}},
			},
		}},
	}
}

Full source: mfiles-grpc-go/mfilesclient/client.go

User name and password

One call. Fill authentication_data.data.credentials (username, password, type, and domain for Windows accounts) and set authentication_data.type to AUTH_DATA_TYPE_CREDENTIALS:

Python

# M-Files credentials: an M-Files user's name and password.
authentication = structs_pb2.AuthDataClient(
    type=enums_pb2.AUTH_DATA_TYPE_CREDENTIALS,
    data=structs_pb2.AuthDataClientUnion(credentials=structs_pb2.Credentials(
        type=enums_pb2.CREDENTIALS_TYPE_MFILES, username=username, password=password)))

Full source: mfiles-grpc-python/src/mfiles_grpc/client.py

C#

// The authentication data: an M-Files user name and password.
var authentication = new AuthDataClient
{
    Type = AuthDataType.Credentials,
    Data = new AuthDataClientUnion
    {
        Credentials = new Credentials
        {
            Username = username,
            Password = password,
            Type = CredentialsType.Mfiles,  // M-Files authentication
        },
    },
};

Full source: mfiles-grpc-dotnet/src/MFiles.Grpc/MFilesConnection.cs

Go


// PasswordAuth is the authentication data of an M-Files user name and password.
//   - username, password: the credentials of an M-Files user account.
func PasswordAuth(username, password string) *mfiles.AuthDataClient {
	return &mfiles.AuthDataClient{
		Type: mfiles.AuthDataType_AUTH_DATA_TYPE_CREDENTIALS,
		Data: &mfiles.AuthDataClientUnion{Data: &mfiles.AuthDataClientUnion_Credentials{
			Credentials: &mfiles.Credentials{
				Type:     mfiles.CredentialsType_CREDENTIALS_TYPE_MFILES,
				Username: username,
				Password: password,
			},
		}},
	}
}

Full source: mfiles-grpc-go/mfilesclient/client.go

Windows authentication (SSPI)

The client runs the Windows SSPI handshake and relays its tokens through LogIn. The server accepts tokens of the Negotiate package (Kerberos or NTLM); M-Files' C# client library uses NTLM. The loop:

  1. Initialize an SSPI client context; it produces the first token.
  2. LogIn with type: AUTH_DATA_TYPE_WINDOWS and data.windows.auth_data = the token. Leave authentication_attempt_identifier unset in the first call.
  3. The response has no session yet. Feed response.authentication_data.data.windows.auth_data to SSPI to get the next token, and send it with data.windows.authentication_attempt_identifier = the attempt identifier from the response.
  4. Stop when the response has session_data.session_id (and data.windows.is_done is true).

With NTLM and Negotiate against a local server, the login completed in two LogIn calls. If the Windows user has no account in the vault, the last call fails with E_MFILES_ACCESS_DENIED ("You do not have a user account in this document vault").

Anonymous

type: AUTH_DATA_TYPE_ANONYMOUS with an empty data.anonymous. It succeeds only for vaults that allow anonymous access; otherwise it fails with E_MFILES_AUTHENTICATION_FAILED.

Binding the session to a vault

login_data.vault_guid decides what the session is for:

vault_guid Result
The vault's GUID, {7BBEA0BC-40D8-4BCB-A67D-8A3ACFBDB575} A vault session: use it for vault calls.
{00000000-0000-0000-0000-000000000000} A server-level session: server calls such as GetVaults only. Vault calls fail with E_MFILES_LOGIN_REQUIRED ("Login required.").
Empty string Fails with E_MFILES_INVALID_VAULT_GUID_X_DESC (Invalid Vault GUID: "").
Unknown GUID Fails with E_MFILES_UNKNOWN_VAULT.

Set login_data.server_hostname to the host name you connected to. On servers with vault-level login accounts (M-Files Cloud), a server-level login uses it to find the vault whose accounts apply.

Two ways to reach a vault:

Both were verified against a server: the vault session from LogInWithSession has its own 48-byte ID, and logging it out leaves the server-level session alive.

Keeping the session alive

session_data.keep_alive_interval_in_seconds (450 seconds on a server with default settings) is how often to call KeepAlive. The server drops a session after its session timeout without a KeepAlive call: 15 minutes by default (twice the interval). A vault session can ask for a longer timeout, at most 7 days, with login_data.client_session_timeout_in_seconds; a shorter or longer value is ignored. Other calls do not extend the session: a program that is busy making calls must still call KeepAlive on a timer.

Upload sessions have their own interval, keep_upload_session_alive_interval_in_seconds; see Files.

When a call answers UNAUTHENTICATED

UNAUTHENTICATED means the server does not accept the session: it was never valid, expired, was logged out, the mfiles-session-id-bin header is missing, or it appears more than once. The status carries a fixed message ("The current session with M-Files Server is no longer valid...") and no error trailers.

Log in again with LogIn and continue with the new session_id.

Logging out

LogOut with the session in mfiles-session-id-bin ends the session and releases the license it holds; a session that is not logged out holds its license until it times out. Every later call with that session ID, including KeepAlive and a second LogOut, answers UNAUTHENTICATED.

Session assertions

Some methods also accept a session assertion in the metadata x-mf-session-assertion instead of mfiles-session-id-bin (SESSION_REQUIREMENT_SESSION_OR_ASSERTION in the reference). Session assertions are for M-Files' own services; applications use the session ID.