Overview of authentication methods and protocols in web applications



    I’ll talk about using different authentication methods for web applications, including password authentication, certificates, one-time passwords, access keys and tokens. Touching on Single Sign-On technology, I will consider various authentication standards and protocols.

    Before we get into the technical details, let's refresh the terminology a bit.

    • Identification is a statement of who you are. Depending on the situation, this may be a name, email address, account number, etc.
    • Authentication - providing evidence that you really are the one who identified (from the word "authentic" - true, authentic).
    • Authorization - checking that you are allowed access to the requested resource.


    Например, при попытке попасть в закрытый клуб вас идентифицируют (спросят ваше имя и фамилию), аутентифицируют (попросят показать паспорт и сверят фотографию) и авторизуют (проверят, что фамилия находится в списке гостей), прежде чем пустят внутрь.

    Аналогично эти термины применяются в компьютерных системах, где традиционно под идентификацией понимают получение вашей учетной записи (identity) по username или email; под аутентификацией — проверку, что вы знаете пароль от этой учетной записи, а под авторизацией — проверку вашей роли в системе и решение о предоставлении доступа к запрошенной странице или ресурсу.

    However, in modern systems there are more complex authentication and authorization schemes, which I will discuss later. But let's start with a simple and understandable.

    Password Authentication

    This method is based on the fact that the user must provide username and password for successful identification and authentication in the system. The username / password pair is set by the user during his registration in the system, while the username can be the user's email address.

    With regard to web applications, there are several standard protocols for password authentication, which we will consider below.

    HTTP authentication

    This protocol, described in the HTTP 1.0 / 1.1 standards, has existed for a very long time and is still actively used in the corporate environment. For websites, it works as follows:

    1. The server, when an unauthorized client accesses a protected resource, sends the HTTP status “401 Unauthorized” and adds the header “WWW-Authenticate” indicating the authentication scheme and parameters.
    2. The browser, upon receipt of such a response, automatically displays the username and password input dialog. The user enters the details of his account.
    3. In all subsequent requests to this website, the browser automatically adds the “Authorization” HTTP header, which transmits user data for authentication by the server.
    4. The server authenticates the user according to the data from this header. The decision to grant access (authorization) is made separately based on the role of the user, ACL, or other account information.


    The whole process is standardized and well supported by all browsers and web servers. There are several authentication schemes that differ in security level:

    1. Basic is the simplest scheme, in which the username and password of the user are transmitted in the Authorization header in unencrypted form (base64-encoded). However, using the HTTPS (HTTP over SSL) protocol is relatively secure.

      An example of HTTP authentication using the Basic scheme.

    2. Digest is a challenge-response scheme in which the server sends a unique nonce value, and the browser sends the MD5 password hash of the user, calculated using the specified nonce. A safer alternative to the Basic scheme for insecure connections, but is subject to man-in-the-middle attacks (with replacing the scheme with basic). In addition, the use of this scheme does not allow the use of modern hash functions for storing user passwords on the server.
    3. NTLM (known as Windows authentication) is also based on the challenge-response approach, in which the password is not transmitted in its purest form. This scheme is not an HTTP standard, but is supported by most browsers and web servers. It is mainly used to authenticate Windows Active Directory users in web applications. Vulnerable to pass-the-hash attacks.
    4. Negotiate is another Windows authentication family scheme that allows the client to choose between NTLM and Kerberos authentication. Kerberos is a more secure Single Sign-On protocol. However, it can only function if both the client and server are in the intranet zone and are part of the Windows domain.

    It is worth noting that when using HTTP authentication, the user does not have the standard ability to exit the web application, except to close all browser windows.

    Forms authentication

    There is no specific standard for this protocol, therefore, all its implementations are specific for specific systems, and more specifically, for authentication modules of development frameworks.

    This works according to the following principle: an HTML form is included in the web application, in which the user must enter his username / password and send them to the server via HTTP POST for authentication. If successful, the web application creates a session token, which is usually placed in browser cookies. On subsequent web requests, the session token is automatically transferred to the server and allows the application to obtain information about the current user to authorize the request.


    Form authentication example.

    An application can create session token in two ways:

    1. As the identifier of the authenticated user session, which is stored in the server’s memory or in the database. The session should contain all the necessary information about the user for the possibility of authorization of his requests.
    2. As an encrypted and / or signed object containing data about the user, as well as the validity period. This approach allows you to implement a stateless server architecture, however, it requires a mechanism to update the session token after the expiration date. Several standard formats for such tokens are discussed in the section “Token Authentication”.

    You need to understand that session token interception often gives the same level of access as knowing username / password. Therefore, all communications between the client and server in the case of forms authentication should only be done over a secure HTTPS connection.

    Other password authentication protocols

    The two protocols described above are successfully used to authenticate users to websites. But when developing client-server applications using web services (for example, iOS or Android), along with HTTP authentication, non-standard protocols are often used in which data for authentication is transmitted in other parts of the request.

    There are only a few places where you can pass username and password in HTTP requests:

    1. URL query - considered an unsafe option, because URL strings can be remembered by browsers, proxies, and web servers.
    2. Request body is a safe option, but it is applicable only for requests containing the message body (such as POST, PUT, PATCH).
    3. HTTP header is the best option, and you can use the standard Authorization header (for example, with the Basic-scheme), and other arbitrary headers.


    Common Vulnerabilities and Implementation Errors
    Password authentication is not considered a very reliable way, since the password can often be found, and users tend to use simple and identical passwords in different systems, or write them on pieces of paper. If the attacker was able to figure out the password, then the user often does not know about it. In addition, application developers can make a number of conceptual errors that make it easier to hack accounts.

    The following is a list of the most common vulnerabilities when using password authentication:

    • The web application allows users to create simple passwords.
    • The web application is not protected against brute-force attacks.
    • The web application itself generates and distributes passwords to users, however, it does not require a password change after the first login (i.e. the current password is written somewhere).
    • The web application allows passwords to be transmitted over an insecure HTTP connection, or in a URL string.
    • The web application does not use secure hash functions to store user passwords.
    • The web application does not provide users with the ability to change the password or does not notify users of the change of their passwords.
    • The web application uses a vulnerable password recovery feature that can be used to gain unauthorized access to other accounts.
    • The web application does not require re-authentication of the user for important actions: changing the password, changing the address of the delivery of goods, etc.
    • The web application creates session tokens in such a way that they can be matched or predicted for other users.
    • The web application allows session tokens to be transmitted over an insecure HTTP connection or in a URL string.
    • The web application is vulnerable to session fixation attacks (that is, it does not replace session token when an anonymous user session is authenticated).
    • The web application does not set the HttpOnly and Secure flags for browser cookies containing session tokens.
    • The web application does not destroy user sessions after a short period of inactivity or does not provide a function to exit an authenticated session.


    Certificate Authentication

    A certificate is a set of attributes that identify the owner, signed by certificate authority (CA). CA acts as an intermediary that guarantees the authenticity of certificates (similar to the FMS issuing passports). The certificate is also cryptographically associated with the private key, which is stored by the certificate holder and allows you to clearly confirm the fact of certificate ownership.

    On the client side, the certificate together with the private key can be stored in the operating system, in the browser, in a file, on a separate physical device (smart card, USB token). Typically, the private key is additionally protected with a password or PIN.

    Web applications traditionally use X.509 certificates. Authentication with an X.509 certificate occurs at the time of connection to the server and is part of the SSL / TLS protocol. This mechanism is also well supported by browsers that allow the user to select and apply a certificate if the website allows this authentication method.


    Using a certificate for authentication.

    During authentication, the server verifies the certificate based on the following rules:

    1. The certificate must be signed by a trusted certification authority.
    2. The certificate must be valid for the current date (validation check).
    3. The certificate should not be revoked by the appropriate CA (check exclusion lists).



    Example X.509 certificate.

    After successful authentication, the web application can authorize the request based on certificate data such as subject (owner name), issuer (issuer), serial number (certificate serial number) or thumbprint (certificate public key fingerprint).

    Using certificates for authentication is a much more reliable method than password authentication. This is achieved by creating a digital signature in the authentication process, the presence of which proves the fact of using a private key in a specific situation (non-repudiation). However, difficulties with the distribution and support of certificates make this authentication method inaccessible in wide circles.

    One Time Password Authentication

    One-time password authentication is usually applied in addition to password authentication to implement two-factor authentication (2FA). In this concept, the user needs to provide two types of data for entering the system: something that he knows (for example, a password), and something that he owns (for example, a device for generating one-time passwords). The presence of two factors can significantly increase the level of security, which m. required for certain types of web applications.

    Another popular scenario for using one-time passwords is additional user authentication during the execution of important actions: transferring money, changing settings, etc.

    There are various sources for creating one-time passwords. Most popular:

    1. Hardware or software tokens that can generate one-time passwords based on the secret key entered into them and the current time. Secret keys of users, which are a factor of ownership, are also stored on the server, which allows you to check the entered one-time passwords. An example of hardware implementation of tokens - RSA SecurID ; software - Google Authenticator application .
    2. Randomly generated codes transmitted to the user via SMS or another communication channel. In this situation, the ownership factor is the user's phone (more precisely, a SIM card attached to a specific number).
    3. Printout or scratch card with a list of pre-formed one-time passwords. For each new login, you must enter a new one-time password with the specified number.



    The RSA SecurID hardware token generates a new code every 30 seconds.

    In web applications, this authentication mechanism is often implemented through the extension of forms authentication: after the primary authentication with a password, a user session is created, however, in the context of this session, the user does not have access to the application until he performs additional authentication with a one-time password.

    Access Key Authentication

    This method is most often used to authenticate devices, services, or other applications when accessing web services. Here, access keys ( access key, API key ) are used as a secret - long unique lines containing an arbitrary set of characters, essentially replacing the username / password combination.

    In most cases, the server generates access keys at the request of users, who then store these keys in client applications. When creating a key, it is also possible to limit the validity and access level that the client application will receive when authenticating with this key.

    A good example of applying key authentication is the Amazon Web Services cloud. Suppose a user has a web application that allows them to upload and view photos, and wants to use Amazon S3 to store files. In this case, the user through the AWS console can create a key that has limited access to the cloud: only read / write its files in Amazon S3. As a result, this key can be used to authenticate a web application in the AWS cloud.


    An example of applying key authentication.

    Using keys allows you to avoid passing the user's password to third-party applications (in the example above, the user saved not his password, but the access key in the web application). Keys have significantly greater entropy compared to passwords, so they are almost impossible to pick up. In addition, if the key was disclosed, this does not compromise the main user account - just cancel this key and create a new one.

    From a technical point of view, there is no single protocol here: keys can be transmitted in different parts of an HTTP request: URL query, request body or HTTP header. As with password authentication, the best option is to use an HTTP header. In some cases, they use the Bearer HTTP scheme to transfer the token in the header (Authorization: Bearer [token]). To avoid key interception, the connection to the server must be protected by SSL / TLS.


    Authentication example using the access key passed in the HTTP header.

    In addition, there are more complex key authentication schemes for insecure connections. In this case, the key usually consists of two parts: public and secret. The public part is used to identify the client, and the secret part allows you to generate a signature. For example, by analogy with the digest authentication scheme, the server can send a unique nonce or timestamp value to the client, and the client can return a hash or HMAC of this value calculated using the secret part of the key. This avoids the transfer of the entire key in its original form and protects against replay attacks.

    Token Authentication

    This authentication method is most often used when building Single Sign-On (SSO) distributed systems , where one application ( service provider or relying party ) delegates the user authentication function to another application ( identity provider or authentication service ). A typical example of this method is logging into the application through an account on social networks. Here, social networks are authentication services, and the application trusts the authentication function of users to social networks.

    The implementation of this method is that identity provider (IP) provides reliable user information in the form of a token, and the service provider (SP) application uses this token to identify, authenticate and authorize the user.
    At a general level, the whole process is as follows:

    1. The client authenticates with the identity provider in one of the ways specific to it (password, passkey, certificate, Kerberos, etc.).
    2. The client asks the identity provider to provide it with a token for a specific SP application. Identity provider generates a token and sends it to the client.
    3. The client authenticates to the SP application using this token.



    An example of authentication of an “active” client using a token transmitted through a Bearer scheme.

    The process described above reflects the authentication mechanism of the active client, i.e., one that can perform a programmed sequence of actions (for example, iOS / Android applications). The browser is a passive client in the sense that it can only display the pages requested by the user. In this case, authentication is achieved by automatically redirecting the browser between the identity provider and service provider web applications.


    An example of authenticating a “passive” client by redirecting requests.

    There are several standards that precisely define the protocol of interaction between clients (active and passive) and IP / SP applications and the format of supported tokens. Among the most popular standards are OAuth, OpenID Connect, SAML, and WS-Federation. Some information about these protocols is below in the article.

    The token itself is usually a data structure that contains information about who generated the token, who can be the recipient of the token, validity period, a set of information about the user (claims). In addition, the token is additionally signed to prevent unauthorized changes and guarantees of authenticity.

    When authenticating with a token, the SP application must perform the following checks:

    1. The token was issued by a trusted identity provider application (verification of the issuer field ).
    2. The token is intended for the current SP application (checking the audience field ).
    3. The token has not yet expired (checking the expiration date field ).
    4. The token is genuine and has not been changed (signature verification).


    In case of successful verification, the SP-application authorizes the request based on the user information contained in the token.

    Token Formats

    There are several common token formats for web applications:

    1. Simple Web Token (SWT) is the simplest format, which is a set of arbitrary name / value pairs in HTML form encoding format. The standard defines several reserved names: Issuer, Audience, ExpiresOn, and HMACSHA256. The token is signed using a symmetric key, so both IP and SP applications must have this key in order to be able to create / verify the token.

      An example of a SWT token (after decoding).
      Issuer = http: //auth.myservice.com&
      Audience = http: //myservice.com&
      ExpiresOn = 1435937883 &
      UserName = John Smith &
      UserRole = Admin &
      HMACSHA256 = KOUQRPSpy64rvT2KnYyQKtFFXUIggnesSpE7ADA4o9w

    2. JSON Web Token (JWT) - contains three blocks separated by periods: a header, a set of fields (claims) and a signature. The first two blocks are presented in JSON format and are additionally encoded in base64 format. The set of fields contains arbitrary name / value pairs, moreover, the JWT standard defines several reserved names (iss, aud, exp and others). A signature can be generated using both symmetric encryption algorithms and asymmetric ones. In addition, there is a separate standard that describes the format of an encrypted JWT token.

      An example of a signed JWT token (after decoding 1 and 2 blocks).
      {"Alg": "HS256", "typ": "JWT"}.
      {"Iss": " auth.myservice.com ", "aud": " myservice.com ", "exp": "1435937883", "userName": "John Smith", "userRole": "Admin"}.
      S9Zs / 8 / uEGGTVVtLggFTizCsMtwOJnRhjaQ2BMUQhcY


    3. Security Assertion Markup Language (SAML) - defines tokens (SAML assertions) in XML format, including information about the issuer, the subject, the necessary conditions for checking the token, a set of additional statements (statements) about the user. SAML tokens are signed using asymmetric cryptography. In addition, unlike previous formats, SAML tokens contain a mechanism for confirming token ownership, which helps to prevent interception of tokens through man-in-the-middle-attacks when using insecure connections.


    SAML standard

    The Security Assertion Markup Language (SAML) standard describes the interaction methods and protocols between an identity provider and a service provider for exchanging authentication and authorization data through tokens. Initially, versions 1.0 and 1.1 were released in 2002 - 2003, while version 2.0, which significantly extends the standard and is backward incompatible, was published in 2005.

    This fundamental standard is quite complex and supports many different scenarios of system integration. The main "building blocks" of the standard:

    1. Assertions - native SAML token format in XML format.
    2. Protocols - a set of supported messages between participants, including a request to create a new token, receive existing tokens, log out, manage user IDs, and others.
    3. Bindings are message passing mechanisms through various transport protocols. Supported methods are HTTP Redirect, HTTP POST, HTTP Artifact (link to messages), SAML SOAP, SAML URI (address to receive a message), and others.
    4. Profiles - typical scenarios for using the standard, defining the set of assertions, protocols and bindings necessary for their implementation, which allows to achieve better compatibility. Web Browser SSO is one example of such profiles.


    In addition, the standard defines a format for exchanging meta-information between participants, which includes a list of supported roles, protocols, attributes, encryption keys, etc.

    Let us consider a brief example of using SAML for the Single Sign-On scenario. The user wants to access the protected resource of the service provider (step No. 1 on the authentication diagram of passive clients). Since the user was not authenticated, SP sends him to the identity provider’s website to create a token (step No. 2). The following is an example SP response where the latter uses SAML HTTP Redirect binding to send a message with a token request:



    In the case of such a request, the identity provider authenticates the user (steps 3-4), and then generates the token. The following is an example of an IP response using HTTP POST binding (step # 5):



    After the browser automatically sends this form to the service provider’s website (step No. 6), the latter decodes the token and authenticates the user. Based on the results of successful authorization of the request, the user gains access to the requested resource (step No. 7).

    WS-Trust and WS-Federation Standards

    WS-Trust and WS-Federation are part of the WS- * standards group that describes SOAP / XML web services. These standards are developed by a group of companies that includes Microsoft, IBM, VeriSign and others. Along with SAML, these standards are quite complex, they are used mainly in corporate scenarios.

    The WS-Trust standard describes an authorization service interface called Secure Token Service (STS). This service runs on the SOAP protocol and supports the creation, updating and cancellation of tokens. At the same time, the standard allows the use of tokens of various formats, however, in practice, SAML tokens are mainly used. WS-Federation

    Standardconcerns the mechanisms of interaction between services between companies, in particular, token exchange protocols. At the same time, WS-Federation extends the functions and interface of the STS service described in the WS-Trust standard. Among other things, the WS-Federation standard defines:

    • Format and methods for exchanging metadata about services.
    • Single sign-out function for all systems.
    • Attribute service that provides additional information about the user.
    • An alias service that allows you to create alternate usernames.
    • Support for passive clients (browsers) through redirection.


    We can say that WS-Federation allows you to solve the same problems as SAML, but their approaches and implementation are somewhat different.

    OAuth and OpenID Connect Standards


    Unlike SAML and WS-Federation, the OAuth (Open Authorization) standard does not describe a user authentication protocol. Instead, it defines a mechanism for accessing one application to another on behalf of the user. However, there are schemes that allow user authentication based on this standard (more on that below).

    The first version of the standard was developed in 2007 - 2010, and the current version 2.0 was published in 2012. Version 2.0 significantly expands and at the same time simplifies the standard, but is not backward compatible with version 1.0. OAuth 2.0 is now very popular and is used universally to provide delegated access and third-party user authentication.

    To better understand the standard itself, consider an example web application that helps users plan their travels. As part of the functionality, it is able to analyze users' mail for the presence of letters with confirmation of reservations and automatically include them in the planned route. The question is, how can this web application access users ’mail, such as Gmail, safely?

    > Ask the user to enter their account information? Is a bad option.
    > Ask the user to create an access key? - possible, but very difficult.

    It is precisely this problem that the OAuth standard allows to solve: it describes how a travel application (client) can access user mail (resource server) with the permission of the user (resource owner). In general terms, the whole process consists of several steps:

    1. The user (resource owner) gives permission to the application (client) to access a specific resource in the form of a grant. What is a grant, consider below.
    2. The application contacts the authorization server and receives a resource access token in exchange for its grant. In our example, the authorization server is Google. When called, the application is additionally authenticated using the access key issued to it during pre-registration.
    3. The application uses this token to obtain the required data from the resource server (in our case, the Gmail service).



    Interoperability of components in the OAuth standard.

    The standard describes four types of grants that identify possible application scenarios:

    1. Authorization Code - the user can receive this grant from the authorization server after successful authentication and confirmation of consent to grant access. This method is most often used in web applications. The grant process is very similar to the passive client authentication mechanism in SAML and WS-Federation.
    2. Implicit - used when the application does not have the ability to safely receive a token from the authorization server (for example, a JavaScript application in the browser). In this case, the grant is a token received from the authorization server, and step No. 2 is excluded from the scenario above.
    3. Resource Owner Password Credentials — грант представляет собой пару username/password пользователя. Может применяться, если приложение является «интерфейсом» для сервера ресурсов (например, приложение — мобильный клиент для Gmail).
    4. Client Credentials — в этом случае нет никакого пользователя, а приложение получает доступ к своим ресурсам при помощи своих ключей доступа (исключается шаг № 1).


    The standard does not determine the format of the token that the application receives: in the scenarios addressed by the standard, the application does not need to analyze the token, since it is only used to gain access to resources. Therefore, neither the token, nor the grant alone can be used to authenticate the user. However, if the application needs to obtain reliable information about the user, there are several ways to do this:

    1. Often, the resource server API includes an operation that provides information about the user himself (for example, / me on the Facebook API). An application can perform this operation every time after receiving a token to identify the client. This method is sometimes called pseudo-authentication .
    2. Use the OpenID Connect standard , designed as a credential layer on top of OAuth (published in 2014). In accordance with this standard, the authorization server provides an additional identity token at step No. 2. This token in the JWT format will contain a set of certain fields (claims) with information about the user.


    It is worth noting that OpenID Connect, which replaced the previous versions of the OpenID 1.0 and 2.0 standard, also contains a set of optional add-ons for searching authorization servers, dynamic client registration and user session management.

    Conclusion


    In this article, we looked at various authentication methods in web applications. Below is a table that summarizes the described methods and protocols:

    Way


    Main application


    Protocols


    By password


    User authentication


    HTTP, Forms


    According to certificates


    Authentication of users in secure applications; service authentication


    SSL / TLS


    On one-time passwords


    Advanced user authentication (to achieve two-factor authentication)


    Forms


    By access keys


    Authentication of services and applications


    -


    By tokens


    Delegated user authentication delegated application authorization


    SAML, WS-Federation, OAuth, OpenID Connect




    I hope that the information was useful, and you can apply it in the design and development of new applications. See you soon!

    Posted by Dmitry Vyrostkov, Solutions Architect at DataArt.

    Also popular now: