Authentication

Password hashing

JWT (JSON web token)

It is an open standard (RFC 7519). Compact: - small size. JWT can be sent through a URL, POST param, inside a header. Self-contained: The payload contains all required info about the user, avoiding the need to query the DB more than once

JWT can be signed: - using a secret (with the HMAC algorithm) - using public/private key pair using RSA or ECDSA

When to use

  • Authorization (most common scenario). SSO.

  • Information exchange.

Structure

  • Header

    • type of the token, which is JWT

    • signing algorithm being used (HMAC|SHA256|RSA)

    • {
        "alg": "HS256",
        "typ": "JWT"
      }
    • => JSON is base64Url encoded

  • Payload

    • contains claims. Claim = statement about an entity (e.g. user) + additional data

    • types of claims

      • registered

        • iss (issuer)

        • exp (expiration time)

        • sub (subject)

        • aud (audience)

        • and others

      • public

        • to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains collision resistant namespace

      • private

        • custom claims to be used between parties (neither registered nor public)

    • example payload:

    • {
        "sub": "1234567890",
        "name": "John Doe",
        "admin": true
      }

      The payload is then Base64Url encoded

    • for signed tokens this information, though protected against tampering, is readable by anyone. Do not put secret information in the payload or header elements of a JWT unless it is encrypted.

  • Signature

    • HMACSHA256(
        base64UrlEncode(header) + "." +
        base64UrlEncode(payload),
        secret)
        
        // example
    • Signature is used to verify that the message was not changed along the way

    • if (signed with private key) => verify that sender of JWT is who it says it is

Separated by dot => xxxxx.yyyyy.zzzzz .

+

-

Fast

Compromised Secret key

Stateless

No visibility to logged in users

Used across many services

Token can be stolen

Compact

Separate lib is used. LINK

Form based auth

  • username & password

  • standart in most websites

  • Can logout

  • HTTPS recommended

  • Store sessions in DB or Redis.

    • If (in memory) => sessions are lost after restart.

  • default SpringSecurity login page can be substituted

Last updated