global update and global fix
This commit is contained in:
@@ -13,7 +13,7 @@ export function buildOAuthExamples(apiBase: string): OAuthExample[] {
|
||||
id: 'javascript',
|
||||
label: 'JavaScript',
|
||||
language: 'javascript',
|
||||
code: `// Authorization Code Flow (Node.js / браузер)
|
||||
code: `// Authorization Code Flow — стандартный OIDC (RFC 6749)
|
||||
const clientId = 'YOUR_CLIENT_ID';
|
||||
const redirectUri = 'https://app.example.com/oauth/callback';
|
||||
const scope = 'openid profile email';
|
||||
@@ -21,34 +21,63 @@ const state = crypto.randomUUID();
|
||||
|
||||
// Шаг 1: перенаправить пользователя на IdP
|
||||
const authorizeUrl = new URL('${API_BASE}/oauth/authorize');
|
||||
authorizeUrl.searchParams.set('userId', 'USER_ID_AFTER_LOGIN');
|
||||
authorizeUrl.searchParams.set('clientId', clientId);
|
||||
authorizeUrl.searchParams.set('redirectUri', redirectUri);
|
||||
authorizeUrl.searchParams.set('client_id', clientId);
|
||||
authorizeUrl.searchParams.set('redirect_uri', redirectUri);
|
||||
authorizeUrl.searchParams.set('response_type', 'code');
|
||||
authorizeUrl.searchParams.set('scope', scope);
|
||||
authorizeUrl.searchParams.set('state', state);
|
||||
window.location.href = authorizeUrl.toString();
|
||||
|
||||
// OIDC Discovery (issuer = PUBLIC_API_URL из настроек админки)
|
||||
// OIDC Discovery
|
||||
// GET ${API_BASE}/.well-known/openid-configuration
|
||||
|
||||
// Шаг 2: обменять code на токены (на backend!)
|
||||
const tokenResponse = await fetch('${API_BASE}/oauth/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
grantType: 'authorization_code',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code: 'AUTHORIZATION_CODE',
|
||||
clientId,
|
||||
clientSecret: 'YOUR_CLIENT_SECRET',
|
||||
redirectUri
|
||||
client_id: clientId,
|
||||
client_secret: 'YOUR_CLIENT_SECRET',
|
||||
redirect_uri: redirectUri
|
||||
})
|
||||
});
|
||||
const tokens = await tokenResponse.json();
|
||||
// tokens.access_token, tokens.id_token, tokens.refresh_token
|
||||
|
||||
// Шаг 3: получить профиль
|
||||
const profile = await fetch('${API_BASE}/oauth/userinfo', {
|
||||
headers: { Authorization: \`Bearer \${tokens.accessToken}\` }
|
||||
headers: { Authorization: \`Bearer \${tokens.access_token}\` }
|
||||
}).then((r) => r.json());`
|
||||
},
|
||||
{
|
||||
id: 'php',
|
||||
label: 'PHP (OIDC)',
|
||||
language: 'php',
|
||||
code: `<?php
|
||||
// composer require jumbojett/openid-connect-php
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
use Jumbojett\\OpenIDConnectClient;
|
||||
|
||||
$issuer = '${API_BASE}'; // PUBLIC_API_URL из админки Lendry ID
|
||||
$clientId = getenv('OAUTH_CLIENT_ID');
|
||||
$clientSecret = getenv('OAUTH_CLIENT_SECRET');
|
||||
$redirectUri = 'https://app.example.com/oauth/callback';
|
||||
|
||||
$oidc = new OpenIDConnectClient($issuer, $clientId, $clientSecret);
|
||||
$oidc->setRedirectURL($redirectUri);
|
||||
$oidc->addScope(['openid', 'profile', 'email']);
|
||||
|
||||
// Библиотека сама использует discovery, client_id, redirect_uri, response_type=code
|
||||
$oidc->authenticate();
|
||||
|
||||
$sub = $oidc->requestUserInfo('sub');
|
||||
$name = $oidc->requestUserInfo('name');
|
||||
$email = $oidc->requestUserInfo('email');
|
||||
|
||||
// userId передавать НЕ нужно — IdP определяет пользователя после входа`
|
||||
},
|
||||
{
|
||||
id: 'typescript-next',
|
||||
@@ -65,19 +94,19 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
const tokenRes = await fetch(\`\${ISSUER}/oauth/token\`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
grantType: 'authorization_code',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
clientId: process.env.OAUTH_CLIENT_ID,
|
||||
clientSecret: process.env.OAUTH_CLIENT_SECRET,
|
||||
redirectUri: process.env.OAUTH_REDIRECT_URI
|
||||
client_id: process.env.OAUTH_CLIENT_ID!,
|
||||
client_secret: process.env.OAUTH_CLIENT_SECRET!,
|
||||
redirect_uri: process.env.OAUTH_REDIRECT_URI!
|
||||
})
|
||||
});
|
||||
|
||||
const tokens = await tokenRes.json();
|
||||
const response = NextResponse.redirect('/dashboard');
|
||||
response.cookies.set('access_token', tokens.accessToken, { httpOnly: true, secure: true });
|
||||
response.cookies.set('access_token', tokens.access_token, { httpOnly: true, secure: true });
|
||||
return response;
|
||||
}`
|
||||
},
|
||||
@@ -86,125 +115,61 @@ export async function GET(request: NextRequest) {
|
||||
label: 'Python',
|
||||
language: 'python',
|
||||
code: `import requests
|
||||
from urllib.parse import urlencode
|
||||
|
||||
API_BASE = '${API_BASE}'
|
||||
CLIENT_ID = 'YOUR_CLIENT_ID'
|
||||
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
|
||||
REDIRECT_URI = 'https://app.example.com/oauth/callback'
|
||||
|
||||
# OIDC Discovery
|
||||
discovery = requests.get(f'{API_BASE}/.well-known/openid-configuration', timeout=15).json()
|
||||
|
||||
params = urlencode({
|
||||
'userId': 'USER_ID',
|
||||
'clientId': CLIENT_ID,
|
||||
'redirectUri': REDIRECT_URI,
|
||||
'scope': 'openid profile email',
|
||||
'state': 'random-state'
|
||||
})
|
||||
authorize_url = f'{API_BASE}/oauth/authorize?{params}'
|
||||
# Authorization URL — стандартные параметры, userId не нужен
|
||||
authorize_url = (
|
||||
f"{discovery['authorization_endpoint']}"
|
||||
f"?client_id={CLIENT_ID}"
|
||||
f"&redirect_uri={requests.utils.quote(REDIRECT_URI, safe='')}"
|
||||
f"&response_type=code"
|
||||
f"&scope=openid%20profile%20email"
|
||||
f"&state=random-state"
|
||||
)
|
||||
|
||||
token_response = requests.post(f'{API_BASE}/oauth/token', json={
|
||||
'grantType': 'authorization_code',
|
||||
'code': 'AUTHORIZATION_CODE',
|
||||
'clientId': CLIENT_ID,
|
||||
'clientSecret': CLIENT_SECRET,
|
||||
'redirectUri': REDIRECT_URI
|
||||
}, timeout=15)
|
||||
token_response = requests.post(
|
||||
discovery['token_endpoint'],
|
||||
data={
|
||||
'grant_type': 'authorization_code',
|
||||
'code': 'AUTHORIZATION_CODE',
|
||||
'client_id': CLIENT_ID,
|
||||
'client_secret': CLIENT_SECRET,
|
||||
'redirect_uri': REDIRECT_URI,
|
||||
},
|
||||
timeout=15,
|
||||
)
|
||||
tokens = token_response.json()
|
||||
|
||||
profile = requests.get(
|
||||
f'{API_BASE}/oauth/userinfo',
|
||||
headers={'Authorization': f"Bearer {tokens['accessToken']}"},
|
||||
timeout=15
|
||||
discovery['userinfo_endpoint'],
|
||||
headers={'Authorization': f"Bearer {tokens['access_token']}"},
|
||||
timeout=15,
|
||||
).json()`
|
||||
},
|
||||
{
|
||||
id: 'php',
|
||||
label: 'PHP',
|
||||
language: 'php',
|
||||
code: `<?php
|
||||
$apiBase = '${API_BASE}'; // issuer = PUBLIC_API_URL из админки
|
||||
$clientId = getenv('OAUTH_CLIENT_ID');
|
||||
$clientSecret = getenv('OAUTH_CLIENT_SECRET');
|
||||
$redirectUri = 'https://app.example.com/oauth/callback';
|
||||
|
||||
// OIDC Discovery — используйте issuer, а не authorization endpoint
|
||||
$discovery = json_decode(file_get_contents($apiBase . '/.well-known/openid-configuration'), true);
|
||||
|
||||
$params = http_build_query([
|
||||
'userId' => 'USER_ID',
|
||||
'clientId' => $clientId,
|
||||
'redirectUri' => $redirectUri,
|
||||
'scope' => 'openid profile email',
|
||||
'state' => bin2hex(random_bytes(16)),
|
||||
]);
|
||||
header('Location: ' . $apiBase . '/oauth/authorize?' . $params);
|
||||
exit;`
|
||||
},
|
||||
{
|
||||
id: 'go',
|
||||
label: 'Go',
|
||||
language: 'go',
|
||||
code: `package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const apiBase = "${API_BASE}"
|
||||
|
||||
func buildAuthorizeURL(userID, clientID, redirectURI, scope, state string) string {
|
||||
q := url.Values{}
|
||||
q.Set("userId", userID)
|
||||
q.Set("clientId", clientID)
|
||||
q.Set("redirectUri", redirectURI)
|
||||
q.Set("scope", scope)
|
||||
q.Set("state", state)
|
||||
return apiBase + "/oauth/authorize?" + q.Encode()
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'csharp',
|
||||
label: 'C#',
|
||||
language: 'csharp',
|
||||
code: `using System.Net.Http.Json;
|
||||
|
||||
var apiBase = "${API_BASE}";
|
||||
var clientId = Environment.GetEnvironmentVariable("OAUTH_CLIENT_ID");
|
||||
var redirectUri = "https://app.example.com/oauth/callback";
|
||||
|
||||
var discovery = await new HttpClient().GetFromJsonAsync<Dictionary<string, object>>(
|
||||
$"{apiBase}/.well-known/openid-configuration");
|
||||
|
||||
var authorizeUrl =
|
||||
$"{apiBase}/oauth/authorize?userId=USER_ID&clientId={clientId}" +
|
||||
$"&redirectUri={Uri.EscapeDataString(redirectUri)}&scope=openid profile email&state=xyz";`
|
||||
},
|
||||
{
|
||||
id: 'curl',
|
||||
label: 'cURL',
|
||||
language: 'bash',
|
||||
code: `# OIDC Discovery (issuer = ${API_BASE})
|
||||
code: `# OIDC Discovery
|
||||
curl ${API_BASE}/.well-known/openid-configuration
|
||||
|
||||
# Authorization (браузер пользователя)
|
||||
open "${API_BASE}/oauth/authorize?userId=USER_ID&clientId=CLIENT_ID&redirectUri=https%3A%2F%2Fapp.example.com%2Fcallback&scope=openid%20profile%20email&state=xyz"
|
||||
# Authorization (браузер пользователя, стандартный OIDC)
|
||||
open "${API_BASE}/oauth/authorize?client_id=CLIENT_ID&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&response_type=code&scope=openid%20profile%20email&state=xyz"
|
||||
|
||||
# Обмен code на токены
|
||||
# Обмен code на токены (form-urlencoded)
|
||||
curl -X POST ${API_BASE}/oauth/token \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"grantType": "authorization_code",
|
||||
"code": "AUTHORIZATION_CODE",
|
||||
"clientId": "CLIENT_ID",
|
||||
"clientSecret": "CLIENT_SECRET",
|
||||
"redirectUri": "https://app.example.com/callback"
|
||||
}'
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \\
|
||||
-d "grant_type=authorization_code" \\
|
||||
-d "code=AUTHORIZATION_CODE" \\
|
||||
-d "client_id=CLIENT_ID" \\
|
||||
-d "client_secret=CLIENT_SECRET" \\
|
||||
-d "redirect_uri=https://app.example.com/callback"
|
||||
|
||||
# UserInfo
|
||||
curl ${API_BASE}/oauth/userinfo \\
|
||||
|
||||
Reference in New Issue
Block a user