Thursday, January 12, 2017

Using JWT with Spring Security OAuth2


I recently implemented OAuth2 with JWT in Spring Restful Services.

Code implementation can be found from below git repository.
https://github.com/saurabh-ranu/ShareYourViewsServices


OAUTH2.0 Specification: 

Introduction

   In the traditional client-server authentication model, the client
   requests an access-restricted resource (protected resource) on the
   server by authenticating with the server using the resource owner's
   credentials.  In order to provide third-party applications access to
   restricted resources, the resource owner shares its credentials with
   the third party.  This creates several problems and limitations:
 
   o  Third-party applications are required to store the resource
      owner's credentials for future use, typically a password in
      clear-text.
 
   o  Servers are required to support password authentication, despite
      the security weaknesses inherent in passwords.
 
   o  Third-party applications gain overly broad access to the resource
      owner's protected resources, leaving resource owners without any
      ability to restrict duration or access to a limited subset of
      resources.
 
   o  Resource owners cannot revoke access to an individual third party
      without revoking access to all third parties, and must do so by
      changing the third party's password.
 
 
   o  Compromise of any third-party application results in compromise of
      the end-user's password and all of the data protected by that
      password.
 
   OAuth addresses these issues by introducing an authorization layer
   and separating the role of the client from that of the resource
   owner.  In OAuth, the client requests access to resources controlled
   by the resource owner and hosted by the resource server, and is
   issued a different set of credentials than those of the resource
   owner.
 
   Instead of using the resource owner's credentials to access protected
   resources, the client obtains an access token -- a string denoting a
   specific scope, lifetime, and other access attributes.  Access tokens
   are issued to third-party clients by an authorization server with the
   approval of the resource owner.  The client uses the access token to
   access the protected resources hosted by the resource server.
 

  Roles

   OAuth defines four roles:
 
   resource owner
      An entity capable of granting access to a protected resource.
      When the resource owner is a person, it is referred to as an
      end-user.
 
   resource server
      The server hosting the protected resources, capable of accepting
      and responding to protected resource requests using access tokens.
 
   client
      An application making protected resource requests on behalf of the
      resource owner and with its authorization.  The term "client" does
      not imply any particular implementation characteristics (e.g.,
      whether the application executes on a server, a desktop, or other
      devices).
 
   authorization server
      The server issuing access tokens to the client after successfully
      authenticating the resource owner and obtaining authorization.
 
   The interaction between the authorization server and resource server
   is beyond the scope of this specification.  The authorization server
   may be the same server as the resource server or a separate entity.
   A single authorization server may issue access tokens accepted by
   multiple resource servers.
 

Protocol Flow

 
     +--------+                               +---------------+
     |        |--(A)- Authorization Request ->|   Resource    |
     |        |                               |     Owner(or End User)     |
     |        |<-(B)-- Authorization Grant ---|               |
     |        |        (Credentials)          +
     |        |                               +---------------+
     |        |--(C)-- Authorization Grant -->| Authorization |
     | Client |                               |     Server    |
     |        |<-(D)----- Access Token -------|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(E)----- Access Token ------>|    Resource   |
     |        |                               |     Server    |
     |        |<-(F)--- Protected Resource ---|               |
     +--------+                               +---------------+
 
                     Figure 1: Abstract Protocol Flow
 
   The abstract OAuth 2.0 flow illustrated in Figure 1 describes the
   interaction between the four roles and includes the following steps:
 
   (A)  The client requests authorization from the resource owner.  The
        authorization request can be made directly to the resource owner
        (as shown), or preferably indirectly via the authorization
        server as an intermediary.
 
   (B)  The client receives an authorization grant, which is a
        credential representing the resource owner's authorization,
        expressed using one of four grant types defined in this
        specification or using an extension grant type.  The
        authorization grant type depends on the method used by the
        client to request authorization and the types supported by the
        authorization server.
 
   (C)  The client requests an access token by authenticating with the
        authorization server and presenting the authorization grant.
 
   (D)  The authorization server authenticates the client and validates
        the authorization grant, and if valid, issues an access token.
 

Authorization Grant

   An authorization grant is a credential representing the resource
   owner's authorization (to access its protected resources) used by the
   client to obtain an access token.  This specification defines four
   grant types -- authorization code, implicit, resource owner password
   credentials, and client credentials -- as well as an extensibility
   mechanism for defining additional types.
 

1.  Authorization Code

   The authorization code is obtained by using an authorization server
   as an intermediary between the client and resource owner.  Instead of
   requesting authorization directly from the resource owner, the client
   directs the resource owner to an authorization server (via its
   user-agent as defined in [RFC2616]), which in turn directs the
   resource owner back to the client with the authorization code.
 
   Before directing the resource owner back to the client with the
   authorization code, the authorization server authenticates the
   resource owner and obtains authorization.  Because the resource owner
   only authenticates with the authorization server, the resource
   owner's credentials are never shared with the client.
 
   The authorization code provides a few important security benefits,
   such as the ability to authenticate the client, as well as the
   transmission of the access token directly to the client without
   passing it through the resource owner's user-agent and potentially
   exposing it to others, including the resource owner.
 
 
   The authorization code grant type is used to obtain both access
   tokens and refresh tokens and is optimized for confidential clients.
   Since this is a redirection-based flow, the client must be capable of
   interacting with the resource owner's user-agent (typically a web
   browser) and capable of receiving incoming requests (via redirection)
   from the authorization server.
 
     +----------+
     | Resource |
     |   Owner  |
     |          |
     +----------+
          ^
          |
         (B)
     +----|-----+          Client Identifier      +---------------+
     |         -+----(A)-- & Redirection URI ---->|               |
     |  User-   |                                 | Authorization |
     |  Agent  -+----(B)-- User authenticates --->|     Server    |
     |          |                                 |               |
     |         -+----(C)-- Authorization Code ---<|               |
     +-|----|---+                                 +---------------+
       |    |                                         ^      v
      (A)  (C)                                        |      |
       |    |                                         |      |
       ^    v                                         |      |
     +---------+                                      |      |
     |         |>---(D)-- Authorization Code ---------'      |
     |  Client |          & Redirection URI                  |
     |         |                                             |
     |         |<---(E)----- Access Token -------------------'
     +---------+       (w/ Optional Refresh Token)
The flow illustrated in Figure 3 includes the following steps:
 
   (A)  The client initiates the flow by directing the resource owner's
        user-agent to the authorization endpoint.  The client includes
        its client identifier, requested scope, local state, and a
        redirection URI to which the authorization server will send the
        user-agent back once access is granted (or denied).
 
   (B)  The authorization server authenticates the resource owner (via
        the user-agent) and establishes whether the resource owner
        grants or denies the client's access request.
 
   (C)  Assuming the resource owner grants access, the authorization
        server redirects the user-agent back to the client using the
        redirection URI provided earlier (in the request or during
        client registration).  The redirection URI includes an
        authorization code and any local state provided by the client
        earlier.
 
   (D)  The client requests an access token from the authorization
        server's token endpoint by including the authorization code
        received in the previous step.  When making the request, the
        client authenticates with the authorization server.  The client
        includes the redirection URI used to obtain the authorization
        code for verification.
 
   (E)  The authorization server authenticates the client, validates the
        authorization code, and ensures that the redirection URI
        received matches the URI used to redirect the client in
        step (C).  If valid, the authorization server responds back with
        an access token and, optionally, a refresh token.
 
 2.  Implicit
 
 
   The implicit grant is a simplified authorization code flow optimized
   for clients implemented in a browser using a scripting language such
   as JavaScript.  In the implicit flow, instead of issuing the client
   an authorization code, the client is issued an access token directly
  (as the result of the resource owner authorization).  The grant type
   is implicit, as no intermediate credentials (such as an authorization
   code) are issued (and later used to obtain an access token).
 
   When issuing an access token during the implicit grant flow, the
   authorization server does not authenticate the client.  In some
   cases, the client identity can be verified via the redirection URI
   used to deliver the access token to the client.  The access token may
   be exposed to the resource owner or other applications with access to
   the resource owner's user-agent.
 
 
 
 
 
+----------+
     | Resource |
     |  Owner   |
     |          |
     +----------+
          ^
          |
         (B)
     +----|-----+          Client Identifier     +---------------+
     |         -+----(A)-- & Redirection URI --->|               |
     |  User-   |                                | Authorization |
     |  Agent  -|----(B)-- User authenticates -->|     Server    |
     |          |                                |               |
     |          |<---(C)--- Redirection URI ----<|               |
     |          |          with Access Token     +---------------+
     |          |            in Fragment
     |          |                                +---------------+
     |          |----(D)--- Redirection URI ---->|   Web-Hosted  |
     |          |          without Fragment      |     Client    |
     |          |                                |    Resource   |
     |     (F)  |<---(E)------- Script ---------<|               |
     |          |                                +---------------+
     +-|--------+
       |    |
      (A)  (G) Access Token
       |    |
       ^    v
     +---------+
     |         |
     |  Client |
     |         |
     +---------+
 

   (A)  The client initiates the flow by directing the resource owner's
        user-agent to the authorization endpoint.  The client includes
        its client identifier, requested scope, local state, and a
        redirection URI to which the authorization server will send the
        user-agent back once access is granted (or denied).
 
   (B)  The authorization server authenticates the resource owner (via
        the user-agent) and establishes whether the resource owner
        grants or denies the client's access request.
 
   (C)  Assuming the resource owner grants access, the authorization
        server redirects the user-agent back to the client using the
        redirection URI provided earlier.  The redirection URI includes
        the access token in the URI fragment.
 
   (D)  The user-agent follows the redirection instructions by making a
        request to the web-hosted client resource (which does not
        include the fragment per [RFC2616]).  The user-agent retains the
        fragment information locally.
 
   (E)  The web-hosted client resource returns a web page (typically an
        HTML document with an embedded script) capable of accessing the
        full redirection URI including the fragment retained by the
        user-agent, and extracting the access token (and other
        parameters) contained in the fragment.
 
   (F)  The user-agent executes the script provided by the web-hosted
        client resource locally, which extracts the access token.
 
   (G)  The user-agent passes the access token to the client.

3.  Resource Owner Password Credentials

The resource owner password credentials (i.e., username and password) can be used directly as an authorization grant to obtain an access

   token.  The credentials should only be used when there is a high
   degree of trust between the resource owner and the client (e.g., the
   client is part of the device operating system or a highly privileged
   application), and when other authorization grant types are not
   available (such as an authorization code).
 
   The resource owner password credentials grant type is suitable in
   cases where the resource owner has a trust relationship with the
   client, such as the device operating system or a highly privileged
   application.  The authorization server should take special care when
   enabling this grant type and only allow it when other flows are not
   viable.
 
   This grant type is suitable for clients capable of obtaining the
   resource owner's credentials (username and password, typically using
   an interactive form).  It is also used to migrate existing clients
   using direct authentication schemes such as HTTP Basic or Digest
   authentication to OAuth by converting the stored credentials to an
   access token.
 
     +----------+
     | Resource |
     |  Owner   |
     |          |
     +----------+
          v
          |    Resource Owner
         (A) Password Credentials
          |
          v
     +---------+                                  +---------------+
     |         |>--(B)---- Resource Owner ------->|               |
     |         |         Password Credentials     | Authorization |
     | Client  |                                  |     Server    |
     |         |<--(C)---- Access Token ---------<|               |
     |         |    (w/ Optional Refresh Token)   |               |
     +---------+                                  +---------------+
 
The flow illustrated in Figure includes the following steps:
 
   (A)  The resource owner provides the client with its username and
        password.
 
   (B)  The client requests an access token from the authorization
        server's token endpoint by including the credentials received
        from the resource owner.  When making the request, the client
        authenticates with the authorization server.
 
   (C)  The authorization server authenticates the client and validates
        the resource owner credentials, and if valid, issues an access
        token.
 
 4. Client Credentials
 
   The client credentials (or other forms of client authentication) can
   be used as an authorization grant when the authorization scope is
   limited to the protected resources under the control of the client,
   or to protected resources previously arranged with the authorization
   server.  Client credentials are used as an authorization grant
   typically when the client is acting on its own behalf (the client is
   also the resource owner) or is requesting access to protected
   resources based on an authorization previously arranged with the
   authorization server.
 
     +---------+                                  +---------------+
     |         |                                  |               |
     |         |>--(A)- Client Authentication --->| Authorization |
     | Client  |                                  |     Server    |
     |         |<--(B)---- Access Token ---------<|               |
     |         |                                  |               |
     +---------+                                  +---------------+
 
                     Figure : Client Credentials Flow
 
   The flow illustrated in Figure 6 includes the following steps:
 
   (A)  The client authenticates with the authorization server and
        requests an access token from the token endpoint.
 
   (B)  The authorization server authenticates the client, and if valid,
        issues an access token.
 

   Access Token

  Access tokens are credentials used to access protected resources. An
   access token is a string representing an authorization issued to the
   client.  The string is usually opaque to the client.  Tokens
   represent specific scopes and durations of access, granted by the
   resource owner, and enforced by the resource server and authorization
   server.
 
   The token may denote an identifier used to retrieve the authorization
   information or may self-contain the authorization information in a
   verifiable manner (i.e., a token string consisting of some data and a
   signature).  Additional authentication credentials, which are beyond
   the scope of this specification, may be required in order for the
   client to use a token.

Refresh Token

  Refresh tokens are credentials used to obtain access tokens.  Refresh
   tokens are issued to the client by the authorization server and are
   used to obtain a new access token when the current access token
   becomes invalid or expires, or to obtain additional access tokens
   with identical or narrower scope (access tokens may have a shorter
   lifetime and fewer permissions than authorized by the resource
   owner).  Issuing a refresh token is optional at the discretion of the
   authorization server.  If the authorization server issues a refresh
   token, it is included when issuing an access token (i.e., step (D) in
   Figure 1).
 



  +--------+                                           +---------------+
  |        |--(A)------- Authorization Grant --------->|               |
  |        |                                           |               |
  |        |<-(B)----------- Access Token -------------|               |
  |        |               & Refresh Token             |               |
  |        |                                           |               |
  |        |                            +----------+   |               |
  |        |--(C)---- Access Token ---->|          |   |               |
  |        |                            |          |   |               |
  |        |<-(D)- Protected Resource --| Resource |   | Authorization |
  | Client |                            |  Server  |   |     Server    |
  |        |--(E)---- Access Token ---->|          |   |               |
  |        |                            |          |   |               |
  |        |<-(F)- Invalid Token Error -|          |   |               |
  |        |                            +----------+   |               |
  |        |                                           |               |
  |        |--(G)----------- Refresh Token ----------->|               |
  |        |                                           |               |
  |        |<-(H)----------- Access Token -------------|               |
  +--------+           & Optional Refresh Token        +---------------+
 
 
 

Client Registration

  Before initiating the protocol, the client registers with the
   authorization server.  The means through which the client registers
   with the authorization server are beyond the scope of this
   specification but typically involve end-user interaction with an HTML
   registration form.
 
        When registering a client, the client developer SHALL:
 
   o  specify the client type.
 
   o  provide its client redirection URIs.
 
   o  include any other information required by the authorization server
      (e.g., application name, website, description, logo image, the
      acceptance of legal terms).
 

Client Types

  OAuth defines two client types, based on their ability to
   authenticate securely with the authorization server (i.e., ability to
   maintain the confidentiality of their client credentials):
 
   confidential
      Clients capable of maintaining the confidentiality of their
      credentials (e.g., client implemented on a secure server with
      restricted access to the client credentials), or capable of secure
      client authentication using other means.
 
   public
      Clients incapable of maintaining the confidentiality of their
      credentials (e.g., clients executing on the device used by the
      resource owner, such as an installed native application or a web
      browser-based application), and incapable of secure client
      authentication via any other means.
 
        This specification has been designed around the following client
        profiles:
 
web application
      A web application is a confidential client running on a web
      server.  Resource owners access the client via an HTML user
      interface rendered in a user-agent on the device used by the
      resource owner.  The client credentials as well as any access
      token issued to the client are stored on the web server and are
      not exposed to or accessible by the resource owner.
 
   user-agent-based application
      A user-agent-based application is a public client in which the
      client code is downloaded from a web server and executes within a
      user-agent (e.g., web browser) on the device used by the resource
      owner.  Protocol data and credentials are easily accessible (and
      often visible) to the resource owner.  Since such applications
      reside within the user-agent, they can make seamless use of the
      user-agent capabilities when requesting authorization.
 
   native application
      A native application is a public client installed and executed on
      the device used by the resource owner.  Protocol data and
      credentials are accessible to the resource owner.  It is assumed
      that any client authentication credentials included in the
      application can be extracted.  On the other hand, dynamically
      issued credentials such as access tokens or refresh tokens can
      receive an acceptable level of protection.  At a minimum, these
      credentials are protected from hostile servers with which the
      application may interact.  On some platforms, these credentials
      might be protected from other applications residing on the same
      device.
  

Client Identifier

   The authorization server issues the registered client a client
   identifier -- a unique string representing the registration
   information provided by the client.  The client identifier is not a
   secret; it is exposed to the resource owner and MUST NOT be used
   alone for client authentication.  The client identifier is unique to
   the authorization server.
 

Client Authentication

   If the client type is confidential, the client and authorization
   server establish a client authentication method suitable for the
   security requirements of the authorization server.  The authorization
   server MAY accept any form of client authentication meeting its
   security requirements.
 

Client Password

   Clients in possession of a client password MAY use the HTTP Basic
   authentication scheme

Alternatively, the authorization server MAY support including the
   client credentials in the request-body using the following
   parameters:
 
   client_id
         REQUIRED.  The client identifier issued to the client during
         the registration process.
 
   client_secret
         REQUIRED.  The client secret.  The client MAY omit the
         parameter if the client secret is an empty string.

3. Protocol Endpoints

The authorization process utilizes two authorization server endpoints
   (HTTP resources):
 
   o  Authorization endpoint - used by the client to obtain
      authorization from the resource owner via user-agent redirection.
 
   o  Token endpoint - used by the client to exchange an authorization
      grant for an access token, typically with client authentication.

Authorization Endpoint

   The authorization endpoint is used to interact with the resource
   owner and obtain an authorization grant.  The authorization server
   MUST first verify the identity of the resource owner.  The way in
   which the authorization server authenticates the resource owner
   (e.g., username and password login, session cookies) is beyond the
   scope of this specification.

Token Endpoint

   The token endpoint is used by the client to obtain an access token by
   presenting its authorization grant or refresh token.  The token
   endpoint is used with every authorization grant except for the
   implicit grant type (since an access token is issued directly).
 
   The means through which the client obtains the location of the token
   endpoint are beyond the scope of this specification, but the location
   is typically provided in the service documentation.


The client MUST use the HTTP "POST" method when making access token
   requests. 

Client Authentication

   Confidential clients or other clients issued client credentials MUST
   authenticate with the authorization server when making requests to the token endpoint.  Client
   authentication is used for:
 
   o  Enforcing the binding of refresh tokens and authorization codes to
      the client they were issued to.  Client authentication is critical
      when an authorization code is transmitted to the redirection
      endpoint over an insecure channel or when the redirection URI has
      not been registered in full.
 
   o  Recovering from a compromised client by disabling the client or
      changing its credentials, thus preventing an attacker from abusing
      stolen refresh tokens.  Changing a single set of client
      credentials is significantly faster than revoking an entire set of
      refresh tokens.
 
   o  Implementing authentication management best practices, which
      require periodic credential rotation.  Rotation of an entire set
      of refresh tokens can be challenging, while rotation of a single
      set of client credentials is significantly easier.

Security Considerations


   As a flexible and extensible framework, OAuth's security
   considerations depend on many factors.  The following sections
   provide implementers with security guidelines focused on the three
   client profiles described in Section 2.1: web application,
   user-agent-based application, and native application.
 
   A comprehensive OAuth security model and analysis, as well as
   background for the protocol design, is provided by
   [OAuth-THREATMODEL].
 

 

1.   Client Authentication

 
 
   The authorization server establishes client credentials with web
   application clients for the purpose of client authentication.  The
   authorization server is encouraged to consider stronger client
   authentication means than a client password.  Web application clients
   MUST ensure confidentiality of client passwords and other client
   credentials.

2.  Client Impersonation

   A malicious client can impersonate another client and obtain access
   to protected resources if the impersonated client fails to, or is
   unable to, keep its client credentials confidential.
 
   The authorization server MUST authenticate the client whenever
   possible.  If the authorization server cannot authenticate the client
   due to the client's nature, the authorization server MUST require the
   registration of any redirection URI used for receiving authorization
   responses and SHOULD utilize other means to protect resource owners
   from such potentially malicious clients.  For example, the
   authorization server can engage the resource owner to assist in
   identifying the client and its origin.

Access Tokens

   Access token credentials (as well as any confidential access token
   attributes) MUST be kept confidential in transit and storage, and
   only shared among the authorization server, the resource servers the
   access token is valid for, and the client to whom the access token is
   issued.  
 
Access token credentials MUST only be transmitted using TLS
When using the implicit grant type, the access token is transmitted
   in the URI fragment, which can expose it to unauthorized parties.
 
   The authorization server MUST ensure that access tokens cannot be
   generated, modified, or guessed to produce valid access tokens by


   unauthorized parties.


I will post further detail soon.
For any query you can reach me at saurabh.ranu@hotmail.com





No comments:

Post a Comment