OAuth2 etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
OAuth2 etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

6 Aralık 2024 Cuma

OAuth2 Token Exchange

Giriş
Açıklaması şöyle
OAuth Token Exchange is specifically designed to exchange one type of token for another, typically for trusted clients to acquire a different kind of token without requiring user involvement. It’s used for various scenarios where a client application needs a specific token to access a resource, such as swapping an access token for a security token or an identity token.
Açıklaması şöyle
In OAuth Token Exchange, user involvement is minimized or absent. The exchange is typically performed by trusted clients or services that have the necessary authorization, and it’s often done without requiring the user to re-authenticate or provide consent.
Şeklen şöyle

Token Issuer
İlk token'ı veren servis

Token Exchange Service
Açıklaması şöyle
The token exchange service validates the request, ensuring that the client is authorized to make the exchange. It may also perform additional checks, such as verifying the original access token’s scope or expiration time.
İlk token doğrulandıktan sonra açıklaması şöyle
Once the request is validated, the token exchange service issues the new token and sends it back to the client. The client can now use the newly acquired token to access the resource or perform the desired action. This token is suitable for the specific resource, and the client doesn’t need to undergo a full authentication and authorization process again.
Örnek
Şöyledir
POST /oauth2/token HTTP/1.1
Host: https://localhost:9443
Content-Type: application/x-www-form-urlencoded
Authorization: Basic <base64-encoded-clientId:clientSecret>

grant_type=urn:ietf:params:oauth:grant-type:token-exchange
&subject_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
&subject_token_type=urn:ietf:params:oauth:token-type:access_token
&audience=http://localhost:8080
&resource=resource-server.com/api/resource
&scope=read write
Açıklaması şöyle
Here are the key parameters that should be present in a token exchange request

Grant Type
The grant_type parameter specifies the type of token exchange being requested. In the context of Token Exchange, this is usually set to "urn:ietf:params:oauth:grant-type:token-exchange". This indicates the intent to exchange tokens.

Subject Token
The subject_token parameter contains the token that the client application currently holds and wishes to exchange. This token can be an OAuth access token or another type of token.

Subject Token Type
The subject_token_type parameter specifies the type or format of the subject token. Common values include "urn:ietf:params:oauth:token-type:access_token" for OAuth access tokens, but it can vary based on the token being exchanged.

Apart from these, there are a few additional optional parameters

Audience
The audienceparameter specifies the intended audience for the exchanged token. The audience can indicate the resource or service for which the exchanged token will be used.

Resource
The resource parameter is used to specify the target resource server or service where the exchanged token will be presented. It can help ensure that the exchanged token is valid for that resource.

Scope
If scopes are applicable to the token exchange, the scope parameter can be used to define the desired permissions associated with the exchanged token. The scope value may restrict the actions the token can perform.

14 Eylül 2023 Perşembe

OAuth2 Refresh Token Grant

Giriş
Eğer Expired 401 hatası alıyorsak bu grant tipi ile token'ın yenilenmesi istenir. Açıklaması şöyle.
The authorization server will respond with a JSON object containing the following properties:

- token_type with the value Bearer
- expires_in with an integer representing the TTL of the access token
- access_token the access token itself
- refresh_token a refresh token that can be used to acquire a new access token when the original expires
Şeklen şöyle



OAuth2 Client Credentials Grant - Sunucular Arasında Kullanılır

Giriş
Açıklaması şöyle.
Intended for the server-to-server authentication, this flow describes an approach when the client application acts on its own behalf rather than on behalf of any individual user. In most scenarios, this flow provides the means to allow users to specify their credentials in the client application, so it can access the resources under the client’s control.
Açıklaması şöyle. İnsan müdahalesi olmadan bilgisayarlar arasında kullanılır.
The OAuth 2.0 Client Credentials Grant type is exclusively used for scenarios in which no user exists (CRON jobs, scheduled tasks, other data workloads, etc.).
...
The goal of the Client Credentials Grant is to allow two machines to communicate securely. In this grant type, you have a client (think of this as your application) making API requests to another service (this is your resource server).
Bundan önce Basic Authentication vardı. Açıklaması şöyle.
Before OAuth 2.0, the way developers handled server-to-server authentication was with HTTP Basic Auth. Essentially, this boiled down to a developer that would send over a server’s unique username and password (often referred to as an ID and secret) on each request. The API service would then validate this username and password on every request by connecting to a user store (database, LDAP, etc.) in order to validate the credentials.
Akış şöyle
     +---------+                                  +---------------+
     |         |                                  |               |
     |         |>--(A)- Client Authentication --->| Authorization |
     | Client  |                                  |     Server    |
     |         |<--(B)---- Access Token ---------<|               |
     |         |                                  |               |
     +---------+                                  +---------------+
Örnek
URL'ye şöyle yazarız. Yani Client Credentials gönderiyoruz
localhost:8080/oauth/token?grant_type=client_credentials&scope=any
Diğer parametreleri de eklemek gerekir. Açıklaması şöyle
Please make sure you've added your clientId and client secret in the basic auth header of the authorization tab in postman and you get a successful response like this.
Yani Authorization sekmesinde Basic Auth seçilir. Username Password alanları doldurulur

Cevap olarak şuna benzer bir şey alırız. Yani Access Token alıyruz
{
  "access_token": "qbE0ipKzzX5FNj3OVe8LWu40T_s",
  "token_type": "bearer",
  "expires_in": 43199,
  "scope": "any"
}

OAuth2 Authorization Code Grant

Giriş
Sunucu tarafındaki uygulamalar tarafından kullanılır. Yani server-side applications içindir.

Authorization Code Grant Nedir?
Açıklaması şöyle.
The flow works this way, you visit a third-party site and it redirects you to the authorization server's login page, and you log in there, the authorization server redirects you back to the site issuing the authorization code. The client application then uses the authorization code to get the access token for accessing your protected resources on the resource server.
Akış şöyle
     +--------+                               +---------------+
     |        |--(A)- Authorization Request ->|   Resource    |
     |        |                               |     Owner     |
     |        |<-(B)-- Authorization Grant ---|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(C)-- Authorization Grant -->| Authorization |
     | Client |                               |     Server    |
     |        |<-(D)----- Access Token -------|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(E)----- Access Token ------>|    Resource   |
     |        |                               |     Server    |
     |        |<-(F)--- Protected Resource ---|               |
     +--------+                               +---------------+

Authorization Request
Örnek
/oauth/authorize 
   ?client_id=a17c21ed 
   &response_type=code 
   &state=5ca75bd30 
   &redirect_uri=https://example.com/cb 
   &scope=photos
Açıklaması şöyle
Once the authorization server receives the request it should perform the following steps:
1. Verify user identity for example against access token. The request contains users' consent so it must be secured with user identity.

2. Validate request parameters:
  - client_id should be registered to authorization server with exact redirect_uri
  - response_type specifies which OAuth 2.0 flow is requested; for authorization code flow it should be equal to code
  - state contains a random string generated on the client to be verified against the one returned in response; they should be equal
  - scope contains a list of scopes requested by the client

3. Generate authorization code: This should be a random string secure enough to not be guessed.
4. Store in DB request data: The authorization code and user data (probably from token) to use them while token issuance
Authorization Request İçin Authorization Response
Örnek
Şöyledir Burada authorization code cevabını alıyoruz
https://example.com/cb ?state=txcSDMn3Q5bZ-w32 &code=EVOcNHq7TBVaxVw
Açıklaması şöyle
The authorization response is a redirect back to the client to the redirect_uri specified in the authorization request. The code parameter contains the authorization code and the state originally passed by the client.
Açıklaması şöyle
After successful user authentication, the Authorization Server sends the client Authorization Code. The Authorization Code can be used only once by the client to get access token. It doesn’t matter whether the request by the client was successful or not, once the Authorization Code is consumed by the Authorization Server it cannot be used anymore.
Token Exchange Request - Yani Exchange Authorization Code For Tokens
Şöyledir. Burada backend de de çalışan uygulamamız authorization code + client credentials gönderiyor
/token ?code=EVOcNHq7TBVaxVw &grant_type=authorization_code &redirect_uri=https://example.com/cb &client_id=a17c21ed &client_secret=ZGVmMjMz
Açıklaması şöyle
The /token endpoint receives parameters needed to issue access token:
code contains authorization code generated as a result of authorization request; it's a key by which authorization server should look for data in DB.
grant_type specifies which way the server should issue access tokens; code means the token should be issued based on the authorization code.
client_id and client_secret (or code_verifier in case of using PKCE) are needed to authorize the request since just authorization code validation is not enough because it might be intercepted.
- Get data from DB by the authorization code, the most important of which are user id and scopes requested. Therefore, the access token issued should represent the users and should be limited to scopes they confirmed giving consent.
- Issue tokens (most probably your would like to issue refresh token alongside with access one)
Token Exchange Response 
Şöyledir. Burada access token alıyoruz
{ "token_type": "Bearer", "expires_in": 86400, "access_token": "sjmHG1EywNbSDAelt", "refresh_token": "Qb6kKM4BWPIwq" }
Delegated Authorization vs Federated Authentication
Authorization Code Grant akışına "Delegated Authorization" denilir. Çünkü sadece bir kaynağa (resource) belli bir erişim hakkı veriyoruz. "OpenID Connect" ile ayrıldıkları nokta burası, çünkü "OpenID Connect"  "Delegated Authorization" yerine "Federated Authentication" kullanıyor. Açıklaması şöyle. Yani authorization (yetkilendirme) yerine, authentication (doğrulama) yapılıyor
Note that Federated Authentication is different from Delegated Authorization.

Federated Authentication allows you to login to a site using your facebook or google account.

Delegated Authorization is the ability of an external app to access resources. This use case would be for example Spotify trying to access your google contacts list to import it into Spotify.

OAuth 2.0 was designed primarily for delegated authorization, OpenId Connect is the few additional steps added over OAuth 2.0 to extend OAuth 2.0 for Federated Authentication.
Fark aslında çok basit bir şeyden kaynaklanıyor. Open ID access token'a ilave olarak bir de id_token kullanıyor. Açıklaması şöyle
1. it introduces a completely new token (id_token) with radically different semantics than the OAuth 2.0 access_token and a standardized format that is understood by the Client as opposed to the access_token which is opaque to the Client

2. it "twists" the role of the Client, now becoming the "audience" (or: intended recipient) of a token (i.e. the id_token) whilst the audience of the access_token is still a remote entity (aka. Resource Server) and the Client is only the "presenter" of the latter

The 2nd item is the primary source of confusion between OAuth 2.0 and OpenID Connect.