From 10d2b9056706d6626dcf00d12764f4bfee8def87 Mon Sep 17 00:00:00 2001
From: Denys Konovalov <kontakt@denyskon.de>
Date: Wed, 31 May 2023 22:35:40 +0200
Subject: [PATCH 1/8] fix pkce + add pkce docs

---
 .../doc/development/oauth2-provider.en-us.md  | 66 ++++++++++++++++++-
 routers/web/auth/oauth.go                     |  2 +-
 2 files changed, 66 insertions(+), 2 deletions(-)

diff --git a/docs/content/doc/development/oauth2-provider.en-us.md b/docs/content/doc/development/oauth2-provider.en-us.md
index cf045ac2fe677..90643467bcd83 100644
--- a/docs/content/doc/development/oauth2-provider.en-us.md
+++ b/docs/content/doc/development/oauth2-provider.en-us.md
@@ -87,7 +87,9 @@ Gitea supports both confidential and public client types, [as defined by RFC 674
 
 For public clients, a redirect URI of a loopback IP address such as `http://127.0.0.1/` allows any port. Avoid using `localhost`, [as recommended by RFC 8252](https://datatracker.ietf.org/doc/html/rfc8252#section-8.3).
 
-## Example
+## Examples
+
+### Confidential client
 
 **Note:** This example does not use PKCE.
 
@@ -139,3 +141,65 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
    The `REDIRECT_URI` in the `access_token` request must match the `REDIRECT_URI` in the `authorize` request.
 
 3. Use the `access_token` to make [API requests](https://docs.gitea.io/en-us/api-usage#oauth2) to access the user's resources.
+
+### Public client (PKCE)
+
+PKCE (Proof Key for Code Exchange) is an extension to the OAuth flow which allows for a secure credential exchange without the requirement to provide a client secret.
+
+To achieve this, you have to provide a `code_verifier` for every authorization request. A `code_verifier` has to be a random string with a minimum length of 43 characters and a maximum length of 128 characters. It can contain alphanumeric characters as well as the characters `-`, `.`, `_`  and `~`.
+
+Using this `code_verifier` string, a new one called `code_challenge` is created by using one of two methods:
+
+  - If you have the required functionality on your client, set `code_challenge` to be an URL-safe base64-encoded string of the SHA256 hash of `code_verifier`. In that case, your `code_challenge_method` becomes `S256`.
+  - If you are unable to do so, you can provide your `code_verifier` as a plain string to `code_challenge`. Then you have to set your `code_challenge_method` as `plain`.
+
+After you have generated this values, you can continue with your request.
+
+1. Redirect to user to the authorization endpoint in order to get their consent for accessing the resources:
+
+   ```curl
+   https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&code_challenge_method=CODE_CHALLENGE_METHOD&code_challenge=CODE_CHALLENGE&state=STATE
+   ```
+
+   The `CLIENT_ID` can be obtained by registering an application in the settings.
+   
+   The `STATE` is a random string that will be send back to your application after the user authorizes. The `state` parameter is optional but should be used to prevent CSRF attacks.
+
+   ![Authorization Page](/authorize.png)
+
+   The user will now be asked to authorize your application. If they authorize it, the user will be redirected to the `REDIRECT_URL`, for example:
+
+   ```curl
+   https://[REDIRECT_URI]?code=RETURNED_CODE&state=STATE
+   ```
+
+2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoints accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
+
+   ```curl
+   POST https://[YOUR-GITEA-URL]/login/oauth/access_token
+   ```
+
+   ```json
+   {
+     "client_id": "YOUR_CLIENT_ID",
+     "code": "RETURNED_CODE",
+     "grant_type": "authorization_code",
+     "redirect_uri": "REDIRECT_URI",
+     "code_verifier": "CODE_VERIFIER",
+   }
+   ```
+
+   Response:
+
+   ```json
+   {
+     "access_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJnbnQiOjIsInR0IjowLCJleHAiOjE1NTUxNzk5MTIsImlhdCI6MTU1NTE3NjMxMn0.0-iFsAwBtxuckA0sNZ6QpBQmywVPz129u75vOM7wPJecw5wqGyBkmstfJHAjEOqrAf_V5Z-1QYeCh_Cz4RiKug",
+     "token_type": "bearer",
+     "expires_in": 3600,
+     "refresh_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJnbnQiOjIsInR0IjoxLCJjbnQiOjEsImV4cCI6MTU1NzgwNDMxMiwiaWF0IjoxNTU1MTc2MzEyfQ.S_HZQBy4q9r5SEzNGNIoFClT43HPNDbUdHH-GYNYYdkRfft6XptJBkUQscZsGxOW975Yk6RbgtGvq1nkEcklOw"
+   }
+   ```
+
+   The `REDIRECT_URI` in the `access_token` request must match the `REDIRECT_URI` in the `authorize` request.
+
+3. Use the `access_token` to make [API requests](https://docs.gitea.io/en-us/api-usage#oauth2) to access the user's resources.
diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go
index 92a06e7c14a03..d8b0181c70a3c 100644
--- a/routers/web/auth/oauth.go
+++ b/routers/web/auth/oauth.go
@@ -753,7 +753,7 @@ func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, s
 		})
 		return
 	}
-	if !app.ValidateClientSecret([]byte(form.ClientSecret)) {
+	if form.CodeVerifier == "" && !app.ValidateClientSecret([]byte(form.ClientSecret)) {
 		errorDescription := "invalid client secret"
 		if form.ClientSecret == "" {
 			errorDescription = "invalid empty client secret"

From d4c20eaf704313b939f5c911599f24ba15ebdd42 Mon Sep 17 00:00:00 2001
From: Denys Konovalov <kontakt@denyskon.de>
Date: Thu, 1 Jun 2023 07:26:01 +0200
Subject: [PATCH 2/8] fix tests, correct docs

---
 .../doc/development/oauth2-provider.en-us.md  | 18 ++++----
 routers/web/auth/oauth.go                     |  2 +-
 tests/integration/oauth_test.go               | 43 +++++++++++--------
 3 files changed, 37 insertions(+), 26 deletions(-)

diff --git a/docs/content/doc/development/oauth2-provider.en-us.md b/docs/content/doc/development/oauth2-provider.en-us.md
index 90643467bcd83..3b800ef50ccdb 100644
--- a/docs/content/doc/development/oauth2-provider.en-us.md
+++ b/docs/content/doc/development/oauth2-provider.en-us.md
@@ -93,13 +93,13 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
 
 **Note:** This example does not use PKCE.
 
-1. Redirect to user to the authorization endpoint in order to get their consent for accessing the resources:
+1. Redirect the user to the authorization endpoint in order to get their consent for accessing the resources:
 
    ```curl
    https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&state=STATE
    ```
 
-   The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be send back to your application after the user authorizes. The `state` parameter is optional but should be used to prevent CSRF attacks.
+   The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be sent back to your application after the user authorizes. The `state` parameter is optional, but should be used to prevent CSRF attacks.
 
    ![Authorization Page](/authorize.png)
 
@@ -109,7 +109,7 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
    https://[REDIRECT_URI]?code=RETURNED_CODE&state=STATE
    ```
 
-2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoints accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
+2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoint accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
 
    ```curl
    POST https://[YOUR-GITEA-URL]/login/oauth/access_token
@@ -136,7 +136,7 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
    }
    ```
 
-   The `CLIENT_SECRET` is the unique secret code generated for this application. Please note that the secret will only be visible after you created/registered the application with Gitea and cannot be recovered. If you lose the secret you must regenerate the secret via the application's settings.
+   The `CLIENT_SECRET` is the unique secret code generated for this application. Please note that the secret will only be visible after you created/registered the application with Gitea and cannot be recovered. If you lose the secret, you must regenerate the secret via the application's settings.
 
    The `REDIRECT_URI` in the `access_token` request must match the `REDIRECT_URI` in the `authorize` request.
 
@@ -146,16 +146,18 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
 
 PKCE (Proof Key for Code Exchange) is an extension to the OAuth flow which allows for a secure credential exchange without the requirement to provide a client secret.
 
+**Note**: Please ensure you have registered your OAuth application as a public client.
+
 To achieve this, you have to provide a `code_verifier` for every authorization request. A `code_verifier` has to be a random string with a minimum length of 43 characters and a maximum length of 128 characters. It can contain alphanumeric characters as well as the characters `-`, `.`, `_`  and `~`.
 
 Using this `code_verifier` string, a new one called `code_challenge` is created by using one of two methods:
 
-  - If you have the required functionality on your client, set `code_challenge` to be an URL-safe base64-encoded string of the SHA256 hash of `code_verifier`. In that case, your `code_challenge_method` becomes `S256`.
+  - If you have the required functionality on your client, set `code_challenge` to be a URL-safe base64-encoded string of the SHA256 hash of `code_verifier`. In that case, your `code_challenge_method` becomes `S256`.
   - If you are unable to do so, you can provide your `code_verifier` as a plain string to `code_challenge`. Then you have to set your `code_challenge_method` as `plain`.
 
 After you have generated this values, you can continue with your request.
 
-1. Redirect to user to the authorization endpoint in order to get their consent for accessing the resources:
+1. Redirect the user to the authorization endpoint in order to get their consent for accessing the resources:
 
    ```curl
    https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&code_challenge_method=CODE_CHALLENGE_METHOD&code_challenge=CODE_CHALLENGE&state=STATE
@@ -163,7 +165,7 @@ After you have generated this values, you can continue with your request.
 
    The `CLIENT_ID` can be obtained by registering an application in the settings.
    
-   The `STATE` is a random string that will be send back to your application after the user authorizes. The `state` parameter is optional but should be used to prevent CSRF attacks.
+   The `STATE` is a random string that will be sent back to your application after the user authorizes. The `state` parameter is optional, but should be used to prevent CSRF attacks.
 
    ![Authorization Page](/authorize.png)
 
@@ -173,7 +175,7 @@ After you have generated this values, you can continue with your request.
    https://[REDIRECT_URI]?code=RETURNED_CODE&state=STATE
    ```
 
-2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoints accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
+2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoint accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
 
    ```curl
    POST https://[YOUR-GITEA-URL]/login/oauth/access_token
diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go
index d8b0181c70a3c..11392c86b8bb4 100644
--- a/routers/web/auth/oauth.go
+++ b/routers/web/auth/oauth.go
@@ -753,7 +753,7 @@ func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, s
 		})
 		return
 	}
-	if form.CodeVerifier == "" && !app.ValidateClientSecret([]byte(form.ClientSecret)) {
+	if !app.ConfidentialClient && !app.ValidateClientSecret([]byte(form.ClientSecret)) {
 		errorDescription := "invalid client secret"
 		if form.ClientSecret == "" {
 			errorDescription = "invalid empty client secret"
diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go
index 9649b256a9000..034d6eaec3dbb 100644
--- a/tests/integration/oauth_test.go
+++ b/tests/integration/oauth_test.go
@@ -120,6 +120,30 @@ func TestAccessTokenExchange(t *testing.T) {
 	assert.True(t, len(parsed.RefreshToken) > 10)
 }
 
+func TestAccessTokenExchangeWithoutSecret(t *testing.T) {
+	defer tests.PrepareTestEnv(t)()
+	// using pkce, secret not required
+	req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
+		"grant_type":    "authorization_code",
+		"client_id":     "da7da3ba-9a13-4167-856f-3899de0b0138",
+		"redirect_uri":  "a",
+		"code":          "authcode",
+		"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt",
+	})
+	resp := MakeRequest(t, req, http.StatusOK)
+	type response struct {
+		AccessToken  string `json:"access_token"`
+		TokenType    string `json:"token_type"`
+		ExpiresIn    int64  `json:"expires_in"`
+		RefreshToken string `json:"refresh_token"`
+	}
+	parsed := new(response)
+
+	assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed))
+	assert.True(t, len(parsed.AccessToken) > 10)
+	assert.True(t, len(parsed.RefreshToken) > 10)
+}
+
 func TestAccessTokenExchangeJSON(t *testing.T) {
 	defer tests.PrepareTestEnv(t)()
 	req := NewRequestWithJSON(t, "POST", "/login/oauth/access_token", map[string]string{
@@ -177,21 +201,6 @@ func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) {
 	assert.Equal(t, "invalid_client", string(parsedError.ErrorCode))
 	assert.Equal(t, "cannot load client with client id: '???'", parsedError.ErrorDescription)
 
-	// invalid client secret
-	req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
-		"grant_type":    "authorization_code",
-		"client_id":     "da7da3ba-9a13-4167-856f-3899de0b0138",
-		"client_secret": "???",
-		"redirect_uri":  "a",
-		"code":          "authcode",
-		"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt",
-	})
-	resp = MakeRequest(t, req, http.StatusBadRequest)
-	parsedError = new(auth.AccessTokenError)
-	assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError))
-	assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode))
-	assert.Equal(t, "invalid client secret", parsedError.ErrorDescription)
-
 	// invalid redirect uri
 	req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
@@ -260,7 +269,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
 	assert.True(t, len(parsed.AccessToken) > 10)
 	assert.True(t, len(parsed.RefreshToken) > 10)
 
-	// use wrong client_secret
+	// not use client secret, PKCE
 	req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
 		"redirect_uri":  "a",
@@ -272,7 +281,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
 	parsedError := new(auth.AccessTokenError)
 	assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError))
 	assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode))
-	assert.Equal(t, "invalid client secret", parsedError.ErrorDescription)
+	assert.Equal(t, "client is not authorized", parsedError.ErrorDescription)
 
 	// missing header
 	req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{

From b73bd1c207bbd6ca2facb8a5d76d0c4795fdeeff Mon Sep 17 00:00:00 2001
From: Denys Konovalov <kontakt@denyskon.de>
Date: Thu, 1 Jun 2023 07:55:53 +0200
Subject: [PATCH 3/8] restore test

---
 routers/web/auth/oauth.go       |  2 +-
 tests/integration/oauth_test.go | 43 +++++++++++++--------------------
 2 files changed, 18 insertions(+), 27 deletions(-)

diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go
index 11392c86b8bb4..38b743dc1f54b 100644
--- a/routers/web/auth/oauth.go
+++ b/routers/web/auth/oauth.go
@@ -753,7 +753,7 @@ func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, s
 		})
 		return
 	}
-	if !app.ConfidentialClient && !app.ValidateClientSecret([]byte(form.ClientSecret)) {
+	if app.ConfidentialClient && !app.ValidateClientSecret([]byte(form.ClientSecret)) {
 		errorDescription := "invalid client secret"
 		if form.ClientSecret == "" {
 			errorDescription = "invalid empty client secret"
diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go
index 034d6eaec3dbb..9649b256a9000 100644
--- a/tests/integration/oauth_test.go
+++ b/tests/integration/oauth_test.go
@@ -120,30 +120,6 @@ func TestAccessTokenExchange(t *testing.T) {
 	assert.True(t, len(parsed.RefreshToken) > 10)
 }
 
-func TestAccessTokenExchangeWithoutSecret(t *testing.T) {
-	defer tests.PrepareTestEnv(t)()
-	// using pkce, secret not required
-	req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
-		"grant_type":    "authorization_code",
-		"client_id":     "da7da3ba-9a13-4167-856f-3899de0b0138",
-		"redirect_uri":  "a",
-		"code":          "authcode",
-		"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt",
-	})
-	resp := MakeRequest(t, req, http.StatusOK)
-	type response struct {
-		AccessToken  string `json:"access_token"`
-		TokenType    string `json:"token_type"`
-		ExpiresIn    int64  `json:"expires_in"`
-		RefreshToken string `json:"refresh_token"`
-	}
-	parsed := new(response)
-
-	assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed))
-	assert.True(t, len(parsed.AccessToken) > 10)
-	assert.True(t, len(parsed.RefreshToken) > 10)
-}
-
 func TestAccessTokenExchangeJSON(t *testing.T) {
 	defer tests.PrepareTestEnv(t)()
 	req := NewRequestWithJSON(t, "POST", "/login/oauth/access_token", map[string]string{
@@ -201,6 +177,21 @@ func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) {
 	assert.Equal(t, "invalid_client", string(parsedError.ErrorCode))
 	assert.Equal(t, "cannot load client with client id: '???'", parsedError.ErrorDescription)
 
+	// invalid client secret
+	req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
+		"grant_type":    "authorization_code",
+		"client_id":     "da7da3ba-9a13-4167-856f-3899de0b0138",
+		"client_secret": "???",
+		"redirect_uri":  "a",
+		"code":          "authcode",
+		"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt",
+	})
+	resp = MakeRequest(t, req, http.StatusBadRequest)
+	parsedError = new(auth.AccessTokenError)
+	assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError))
+	assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode))
+	assert.Equal(t, "invalid client secret", parsedError.ErrorDescription)
+
 	// invalid redirect uri
 	req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
@@ -269,7 +260,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
 	assert.True(t, len(parsed.AccessToken) > 10)
 	assert.True(t, len(parsed.RefreshToken) > 10)
 
-	// not use client secret, PKCE
+	// use wrong client_secret
 	req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
 		"grant_type":    "authorization_code",
 		"redirect_uri":  "a",
@@ -281,7 +272,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
 	parsedError := new(auth.AccessTokenError)
 	assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError))
 	assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode))
-	assert.Equal(t, "client is not authorized", parsedError.ErrorDescription)
+	assert.Equal(t, "invalid client secret", parsedError.ErrorDescription)
 
 	// missing header
 	req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{

From 6908ed7134f78f78d339fd4127b602a39b273cfe Mon Sep 17 00:00:00 2001
From: Denys Konovalov <kontakt@denyskon.de>
Date: Thu, 1 Jun 2023 08:42:14 +0200
Subject: [PATCH 4/8] fix md lint

---
 docs/content/doc/development/oauth2-provider.en-us.md | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/docs/content/doc/development/oauth2-provider.en-us.md b/docs/content/doc/development/oauth2-provider.en-us.md
index 3b800ef50ccdb..121072e360bfc 100644
--- a/docs/content/doc/development/oauth2-provider.en-us.md
+++ b/docs/content/doc/development/oauth2-provider.en-us.md
@@ -1,5 +1,5 @@
 ---
-date: "2019-04-19:44:00+01:00"
+date: "2023-06-01T08:40:00+08:00"
 title: "OAuth2 provider"
 slug: "oauth2-provider"
 weight: 41
@@ -152,8 +152,8 @@ To achieve this, you have to provide a `code_verifier` for every authorization r
 
 Using this `code_verifier` string, a new one called `code_challenge` is created by using one of two methods:
 
-  - If you have the required functionality on your client, set `code_challenge` to be a URL-safe base64-encoded string of the SHA256 hash of `code_verifier`. In that case, your `code_challenge_method` becomes `S256`.
-  - If you are unable to do so, you can provide your `code_verifier` as a plain string to `code_challenge`. Then you have to set your `code_challenge_method` as `plain`.
+- If you have the required functionality on your client, set `code_challenge` to be a URL-safe base64-encoded string of the SHA256 hash of `code_verifier`. In that case, your `code_challenge_method` becomes `S256`.
+- If you are unable to do so, you can provide your `code_verifier` as a plain string to `code_challenge`. Then you have to set your `code_challenge_method` as `plain`.
 
 After you have generated this values, you can continue with your request.
 
@@ -163,9 +163,7 @@ After you have generated this values, you can continue with your request.
    https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&code_challenge_method=CODE_CHALLENGE_METHOD&code_challenge=CODE_CHALLENGE&state=STATE
    ```
 
-   The `CLIENT_ID` can be obtained by registering an application in the settings.
-   
-   The `STATE` is a random string that will be sent back to your application after the user authorizes. The `state` parameter is optional, but should be used to prevent CSRF attacks.
+   The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be sent back to your application after the user authorizes. The `state` parameter is optional, but should be used to prevent CSRF attacks.
 
    ![Authorization Page](/authorize.png)
 

From 9637b739d73e1877d1bad4da758856e55ac8329f Mon Sep 17 00:00:00 2001
From: Denys Konovalov <kontakt@denyskon.de>
Date: Fri, 2 Jun 2023 16:05:17 +0200
Subject: [PATCH 5/8] allow for refresh token usage without client secret

---
 routers/web/auth/oauth.go | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go
index 38b743dc1f54b..80f149d8061fc 100644
--- a/routers/web/auth/oauth.go
+++ b/routers/web/auth/oauth.go
@@ -695,7 +695,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server
 	}
 	// "The authorization server MUST ... require client authentication for confidential clients"
 	// https://datatracker.ietf.org/doc/html/rfc6749#section-6
-	if !app.ValidateClientSecret([]byte(form.ClientSecret)) {
+	if app.ConfidentialClient && !app.ValidateClientSecret([]byte(form.ClientSecret)) {
 		errorDescription := "invalid client secret"
 		if form.ClientSecret == "" {
 			errorDescription = "invalid empty client secret"

From 47cdf7df8ca4161bcb5f06fc62395ac3844b2253 Mon Sep 17 00:00:00 2001
From: Denys Konovalov <kontakt@denyskon.de>
Date: Fri, 2 Jun 2023 16:31:15 +0200
Subject: [PATCH 6/8] add pkce test for public client

---
 tests/integration/oauth_test.go | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go
index 9649b256a9000..e9b69f5f149b3 100644
--- a/tests/integration/oauth_test.go
+++ b/tests/integration/oauth_test.go
@@ -120,6 +120,29 @@ func TestAccessTokenExchange(t *testing.T) {
 	assert.True(t, len(parsed.RefreshToken) > 10)
 }
 
+func TestAccessTokenExchangeWithPublicClient(t *testing.T) {
+	defer tests.PrepareTestEnv(t)()
+	req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
+		"grant_type":    "authorization_code",
+		"client_id":     "ce5a1322-42a7-11ed-b878-0242ac120002",
+		"redirect_uri":  "http://127.0.0.1",
+		"code":          "authcodepublic",
+		"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt",
+	})
+	resp := MakeRequest(t, req, http.StatusOK)
+	type response struct {
+		AccessToken  string `json:"access_token"`
+		TokenType    string `json:"token_type"`
+		ExpiresIn    int64  `json:"expires_in"`
+		RefreshToken string `json:"refresh_token"`
+	}
+	parsed := new(response)
+
+	assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed))
+	assert.True(t, len(parsed.AccessToken) > 10)
+	assert.True(t, len(parsed.RefreshToken) > 10)
+}
+
 func TestAccessTokenExchangeJSON(t *testing.T) {
 	defer tests.PrepareTestEnv(t)()
 	req := NewRequestWithJSON(t, "POST", "/login/oauth/access_token", map[string]string{

From 4ef353cef86c9579bf89a78e80760950df5adb1b Mon Sep 17 00:00:00 2001
From: 6543 <6543@obermui.de>
Date: Sat, 3 Jun 2023 02:57:40 +0200
Subject: [PATCH 7/8] mention oauthdebugger.com in docs too ;)

---
 docs/content/doc/development/oauth2-provider.en-us.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/docs/content/doc/development/oauth2-provider.en-us.md b/docs/content/doc/development/oauth2-provider.en-us.md
index 121072e360bfc..c226544d789ea 100644
--- a/docs/content/doc/development/oauth2-provider.en-us.md
+++ b/docs/content/doc/development/oauth2-provider.en-us.md
@@ -40,7 +40,7 @@ At the moment Gitea only supports the [**Authorization Code Grant**](https://too
 - [Proof Key for Code Exchange (PKCE)](https://tools.ietf.org/html/rfc7636)
 - [OpenID Connect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth)
 
-To use the Authorization Code Grant as a third party application it is required to register a new application via the "Settings" (`/user/settings/applications`) section of the settings.
+To use the Authorization Code Grant as a third party application it is required to register a new application via the "Settings" (`/user/settings/applications`) section of the settings. To test or debug you use the web-tool https://oauthdebugger.com/.
 
 ## Scopes
 

From f5dcd7d5d3e6d78ee4160ff055648d9341618495 Mon Sep 17 00:00:00 2001
From: 6543 <6543@obermui.de>
Date: Sat, 3 Jun 2023 02:58:26 +0200
Subject: [PATCH 8/8] wording

---
 docs/content/doc/development/oauth2-provider.en-us.md | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/docs/content/doc/development/oauth2-provider.en-us.md b/docs/content/doc/development/oauth2-provider.en-us.md
index c226544d789ea..5f9960a477751 100644
--- a/docs/content/doc/development/oauth2-provider.en-us.md
+++ b/docs/content/doc/development/oauth2-provider.en-us.md
@@ -40,7 +40,7 @@ At the moment Gitea only supports the [**Authorization Code Grant**](https://too
 - [Proof Key for Code Exchange (PKCE)](https://tools.ietf.org/html/rfc7636)
 - [OpenID Connect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth)
 
-To use the Authorization Code Grant as a third party application it is required to register a new application via the "Settings" (`/user/settings/applications`) section of the settings. To test or debug you use the web-tool https://oauthdebugger.com/.
+To use the Authorization Code Grant as a third party application it is required to register a new application via the "Settings" (`/user/settings/applications`) section of the settings. To test or debug you can use the web-tool https://oauthdebugger.com/.
 
 ## Scopes