OpenID Connect

142 阅读9分钟

1. Difference between Oauth 2 and OpenID Connect?

OAuth 2.0 and OpenID Connect (OIDC) are both open standards for authentication and authorization but serve different purposes and are designed to solve different problems. Here's a breakdown of the main differences between them:

Purpose

  • OAuth 2.0 is a framework that allows third-party services to grant server-to-server or client-to-server authorization on behalf of the user, without sharing the user's credentials. It is primarily focused on access delegation. For example, OAuth 2.0 enables an application to access resources from another application on behalf of a user.

  • OpenID Connect is built on top of OAuth 2.0 and adds an identity layer, allowing clients to verify the identity of the end-user and obtain basic profile information in an interoperable and REST-like manner. OIDC enables clients to authenticate users and thereby know who they are.

Tokens

  • OAuth 2.0 uses access tokens for granting access to resources and optionally refresh tokens to obtain new access tokens. The access token is sent to the resource server to access protected resources on behalf of the user.

  • OpenID Connect introduces an additional token, the ID token, which is a JWT (JSON Web Token) and contains claims about the authentication of the user. The ID token provides information about the user and how, when, and by whom the user was authenticated.

Flow

  • OAuth 2.0 provides multiple flows (grant types) for different types of clients, including Authorization Code Flow, Implicit Flow, Resource Owner Password Credentials Flow, and Client Credentials Flow, each designed for different scenarios.

  • OpenID Connect extends OAuth 2.0 by adding the ID token and using a specific flow called the Authorization Code Flow with PKCE (Proof Key for Code Exchange), which enhances security, especially for public clients such as mobile and single-page applications. OIDC also defines the Hybrid Flow and Implicit Flow for specific use cases.

Use Cases

  • OAuth 2.0 is used when an application needs to act on behalf of a user. For example, accessing user data from another service (like reading email from Gmail or posting to Twitter on a user's behalf) without the user needing to share their password with the third-party application.

  • OpenID Connect is used when an application needs to authenticate a user and possibly get basic profile information about them. OIDC is used in scenarios where knowing the identity of the user is essential, such as in login systems.

Standards and Protocols

  • OAuth 2.0 is defined by the IETF in several RFCs, with the core framework described in RFC 6749.

  • OpenID Connect is a standard developed by the OpenID Foundation, building on OAuth 2.0 and aiming to standardize how identity information is provided.

In summary, OAuth 2.0 is about authorization and granting access to resources without sharing the user's credentials, while OpenID Connect is about authentication, enabling the application to understand who the user is. OpenID Connect can be thought of as an identity layer on top of OAuth 2.0.

2. ID Token vs access token vs refresh token

In the context of OAuth 2.0 and OpenID Connect, ID tokens, access tokens, and refresh tokens serve distinct purposes related to authentication and authorization processes. Understanding the differences and roles of each is crucial for implementing secure and efficient access control in web and mobile applications.

ID Token

  • Purpose: The ID token is specific to OpenID Connect, which builds on OAuth 2.0. Its primary role is to provide authentication information about the user. It tells the client application that the user has successfully authenticated.

  • Contents: ID tokens are JSON Web Tokens (JWTs) and contain claims (assertions) about the user's identity. Standard claims include information like the user's identifier (sub), the issuing authority (iss), the audience (aud), and the token's expiration time (exp).

  • Use Case: ID tokens are used by a client application to understand who the user is and to perform user authentication. For example, when a user logs in using their Google account, the ID token issued by Google contains information about the user's Google identity.

Access Token

  • Purpose: Access tokens are used in both OAuth 2.0 and OpenID Connect. Their primary role is to grant access to a protected resource, like an API. They act as a type of "key" that allows the application to access resources on behalf of the user.

  • Contents: Access tokens can be opaque strings or JWTs, depending on the implementation. They do not necessarily contain readable information about the user or the authentication event but are understood and validated by the resource server.

  • Use Case: Access tokens are sent in HTTP requests to access APIs. For instance, an application might use an access token to fetch a user's profile data from a resource server after the user has authenticated.

Refresh Token

  • Purpose: Refresh tokens are used in OAuth 2.0 to obtain new access tokens without requiring the user to authenticate again. They are long-lived compared to access tokens and help maintain a user's session securely.

  • Contents: Refresh tokens are usually opaque strings that do not contain readable information. They are issued to the application alongside an access token and are used solely to obtain new access tokens.

  • Use Case: When an access token expires, the application can use a refresh token to securely request a new access token from the authorization server. This process is done without user interaction, improving the user experience by avoiding repeated logins.

Key Differences and Relationship

  • Authentication vs. Authorization: The ID token is about authentication (verifying who the user is), while the access token is about authorization (granting access to resources). The refresh token supports authorization by allowing long-lived sessions.

  • Lifespan: ID tokens and access tokens usually have a short lifespan, whereas refresh tokens are designed to last longer to enable applications to obtain new access tokens without user interaction.

  • Intended Audience: The ID token is consumed by the client application to authenticate the user. The access token is intended for the resource server to authorize access to its resources. The refresh token is used with the authorization server to get new access tokens.

In practice, the flow often starts with the user authenticating and the application receiving an ID token (to authenticate the user), an access token (to access resources), and optionally a refresh token (to maintain the session by obtaining new access tokens as needed).

3. How to get access to each token: ID Token , access token and refresh token

To obtain ID tokens, access tokens, and refresh tokens, we typically use OAuth 2.0 and OpenID Connect protocols. The specific flow to acquire these tokens depends on the type of application you're developing (e.g., web application, single-page application, mobile app). Here's a general overview of the process using the Authorization Code Flow, which is recommended for most types of applications, especially those that can securely maintain a client secret.

Prerequisites

  1. Register Your Application: Before starting, you need to register your application with the identity provider (e.g., Google, Facebook, Auth0). During registration, you'll receive a client ID and client secret (the secret is not issued for public clients like mobile or single-page apps).

  2. Redirect URI: You also need to specify a redirect URI, which is the endpoint in your application where the identity provider will send the user after authentication.

Authorization Code Flow with PKCE (for public clients)

  1. User Authentication Request: Direct the user to the authorization server's authorization endpoint, including parameters such as the client ID, response_type (set to code), scope (including openid for OIDC), redirect_uri, and code_challenge (for PKCE). The code_challenge is derived from a code verifier that the client generates.

  2. Authentication and Authorization: The user authenticates with the identity provider and grants your application permission to access the specified resources (scopes).

  3. Authorization Response: Upon successful authentication and consent, the authorization server redirects the user back to your application using the redirect_uri, including an authorization code in the query parameters.

  4. Exchange Authorization Code for Tokens: Your application extracts the authorization code and makes a request to the token endpoint of the authorization server. This request includes the authorization code, client ID, code_verifier (for PKCE), redirect_uri, and grant_type (set to authorization_code). If your application is confidential (can securely maintain a client secret), this request also includes the client secret.

  5. Receive Tokens: The authorization server responds with a JSON object containing the access token, ID token (if the openid scope was requested), and optionally a refresh token, depending on the scopes and the server's configuration.

Example Request to Token Endpoint

The request to the token endpoint typically looks like this (for PKCE, without a client secret):

POST /token HTTP/1.1Host: authorization-server.comContent-Type: application/x-www-form-urlencoded​grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=YOUR_REDIRECT_URI&client_id=YOUR_CLIENT_ID&code_verifier=YOUR_CODE_VERIFIER

For confidential clients, we would also include a client_secret parameter.

Handling Tokens

  • ID Token: Use this token to authenticate the user. You can decode it to obtain user information (claims).

  • Access Token: Send this token in the Authorization header when making requests to protected resources.

  • Refresh Token: Use this token to obtain new access tokens by sending it to the token endpoint with the grant_type set to refresh_token. This step is essential for maintaining a user session without asking the user to re-authenticate.

Each identity provider and authorization server may have specific requirements and extensions to this flow, so it's crucial to refer to the documentation of the provider you're using.

4.PKCE: What PKCE resolved in OpenID Connect with the Authorization Code Flow

PKCE (Proof Key for Code Exchange) resolves a significant security issue in the OpenID Connect with Authorization Code Flow, especially in environments where the client cannot securely store secrets, such as public clients including mobile and single-page web applications.

Background

OpenID Connect, an identity layer on top of the OAuth 2.0 protocol, uses Authorization Code Flow for secure authorization, especially for server-side applications. This flow involves exchanging an authorization code for a token. Initially, this required the client to authenticate when exchanging the code for a token, typically using a client secret. However, this model posed security risks for public clients that cannot securely store these secrets due to the risk of exposure.

The Security Issue

The main issue PKCE addresses is the interception and unauthorized exchange of authorization codes by malicious actors. In environments where the client cannot securely maintain a secret (like mobile or SPA environments), using a client secret for authentication during the code exchange phase is impractical. This vulnerability could allow an attacker to intercept the authorization code and exchange it for an access token if they can mimic the client's identity.

How PKCE Resolves This Issue

PKCE enhances the security of the Authorization Code Flow by:

  1. Dynamic Secret Creation: It requires the client to generate a secret (code verifier) at the beginning of the authentication process.

  2. Challenge Method: The client then uses this secret to create a code challenge, typically through S256 (SHA256) method, which is sent to the authorization server during the initial authorization request.

  3. Code Verifier: When the client receives the authorization code, it must present the original code verifier (not the challenge) to the authorization server during the token exchange. The server then compares the received verifier with the previously received challenge to ensure they match after applying the same transformation (e.g., SHA256).

This process ensures that even if an authorization code is intercepted, without the corresponding code verifier (which is not transmitted in the initial request and is difficult to guess), the attacker cannot exchange the code for an access token. PKCE effectively mitigates the risk of authorization code interception and unauthorized exchange, enhancing the security of public clients using OpenID Connect with Authorization Code Flow.

5.Say we have three roles, End User, WeChat Pay and Google. Now WeChat Pay uses Google as OpenID Connect provider. WeChat Pay also has its protected resources in there resource server, will WeChat Pay use access token from Google OpenID Connect provider to access the protected resources in there resource server? If yes, why and please draw the sequence diagram using mermaid. If no, tell me why and how a reply party access their resource server

No, WeChat Pay will not use the access token from Google's OpenID Connect provider to access the protected resources in its own resource server. The main reason is the principle of token audience and scope. Tokens (especially access tokens) are issued for a specific audience, which in this case, is the Google ecosystem. An access token provided by Google is intended for accessing Google's protected resources on behalf of the authenticated user, not for accessing WeChat Pay's resources.

How It Works:

  1. User Authentication and Authorization: When WeChat Pay uses Google as an OpenID Connect provider, it directs the end user to authenticate with Google. After successful authentication, Google issues an ID token and an access token to WeChat Pay. The ID token is used by WeChat Pay to authenticate the user, confirming their identity using the information provided by Google. The access token could be used by WeChat Pay to access Google's resources on behalf of the user, such as user profile information, if needed.

  2. Accessing WeChat Pay's Resources: For WeChat Pay to access its own protected resources, it would typically issue its own tokens (access and possibly refresh tokens) following an internal or a separate OAuth 2.0/OpenID Connect flow, scoped specifically to its services and resources. This might involve WeChat Pay's own authentication and authorization layer or leveraging the authentication information obtained from Google to establish the user's session and permissions within the WeChat Pay ecosystem.

  3. Token Use: Therefore, when accessing WeChat Pay's protected resources, WeChat Pay uses its own access tokens, not the ones issued by Google. This ensures proper scoping, security, and compliance with the OAuth 2.0 and OpenID Connect standards.

Sequence Diagram

Since WeChat Pay would not use Google's access token to access its own resources, the sequence diagram for this scenario would illustrate the user authenticating with Google, WeChat Pay receiving tokens from Google, and then WeChat Pay using its own mechanism for resource access. Here's a simplified view using Mermaid notation, focusing on authentication and internal token issuance:

sequenceDiagram    autonumber    participant User    participant WeChatPay as WeChat Pay    participant Google    participant WeChatResourceServer as WeChat Pay Resource Server​    User->>+WeChatPay: Access WeChat Pay service    WeChatPay->>+Google: Redirect User to Google for authentication    Google-->>-User: Authenticate and consent    User->>+Google: Provide credentials    Google-->>-WeChatPay: Return ID token & Access token for User    WeChatPay->>WeChatPay: Validate ID token & create session    WeChatPay-->>-User: Issue internal access token to User    User->>+WeChatPay: Request access to protected resource with internal access token    WeChatPay->>+WeChatResourceServer: Validate token and request resource    WeChatResourceServer-->>-WeChatPay: Provide requested resource    WeChatPay-->>-User: Display resource content

mermaid.live/edit#pako:e…

UserUserWeChatPayWeChatPayGoogleGoogleWeChatResourceServerWeChatResourceServerAccess WeChat Pay serviceRedirect User to Google for authenticationAuthenticate and consentProvide credentialsReturn ID token & Access token for UserValidate ID token & create sessionRequest access to protected resource with WeChat Pay access tokenProvide requested resourceDisplay resource content

UserUserWeChatPayWeChatPayGoogleGoogleWeChatResourceServerWeChatResourceServerAccess WeChat Pay serviceRedirect User to Google for authenticationAuthenticate and consentProvide credentialsReturn ID token & Access token for UserValidate ID token & create sessionIssue internal access token to UserRequest access to protected resource with internal access tokenValidate token and request resourceProvide requested resourceDisplay resource content

In this diagram:

  • The user initiates the process by trying to access a service provided by WeChat Pay.

  • WeChat Pay redirects the user to Google for authentication.

  • After authentication, Google returns an ID token and an access token to WeChat Pay.

  • WeChat Pay validates the ID token to authenticate the user and may initiate its internal process to issue its own access token for accessing its protected resources.

  • When accessing its own resources, WeChat Pay uses its internally issued access token, not Google's.

This process ensures that tokens are correctly scoped to the resource they're intended to access, maintaining security and proper authorization practices.