update oauth
This commit is contained in:
@@ -1,8 +1,30 @@
|
||||
'use client';
|
||||
|
||||
import { oauthExamples } from '@/lib/oauth-examples';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { buildOAuthExamples } from '@/lib/oauth-examples';
|
||||
import { fetchPublicSettingsClient } from '@/lib/api';
|
||||
import { resolveOAuthApiBase } from '@/lib/oauth-url';
|
||||
import { CodeExampleTabs } from '@/components/code-example-tabs';
|
||||
|
||||
export function OAuthCodeTabs() {
|
||||
return <CodeExampleTabs examples={oauthExamples} />;
|
||||
const [apiBase, setApiBase] = useState('http://localhost:3000');
|
||||
|
||||
useEffect(() => {
|
||||
void fetchPublicSettingsClient()
|
||||
.then((settings) => setApiBase(resolveOAuthApiBase(settings)))
|
||||
.catch(() => undefined);
|
||||
}, []);
|
||||
|
||||
const examples = useMemo(() => buildOAuthExamples(apiBase), [apiBase]);
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-zinc-500 dark:text-zinc-400">
|
||||
Базовый URL API (issuer): <code className="rounded bg-zinc-100 px-1.5 py-0.5 dark:bg-zinc-800">{apiBase}</code>
|
||||
{' — '}
|
||||
берётся из настройки <strong>PUBLIC_API_URL</strong> или <strong>Домен IdP</strong> в админ-панели.
|
||||
</p>
|
||||
<CodeExampleTabs examples={examples} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ export const apiReference: ApiTagGroup[] = [
|
||||
{
|
||||
tag: 'OAuth 2.0',
|
||||
endpoints: [
|
||||
{ method: 'GET', path: '/.well-known/openid-configuration', summary: 'OpenID Connect Discovery' },
|
||||
{ method: 'GET', path: '/oauth/authorize', summary: 'Создать authorization code' },
|
||||
{ method: 'POST', path: '/oauth/token', summary: 'Выдать OAuth токены (code / refresh_token)' },
|
||||
{ method: 'GET', path: '/oauth/userinfo', summary: 'Профиль по OAuth access token', auth: true }
|
||||
|
||||
@@ -40,7 +40,7 @@ export const docPages: DocPage[] = [
|
||||
type: 'callout',
|
||||
variant: 'info',
|
||||
title: 'Домен',
|
||||
text: 'Production-домен: id.lendry.ru. Локально API доступен на порту 3000, frontend — 3002, документация — 3003.'
|
||||
text: 'Production-домен задаётся в админке (PROJECT_DOMAIN и PUBLIC_API_URL). Локально API — порт 3000, frontend — 3002, документация — 3003. При same-origin деплое PUBLIC_API_URL обычно https://ваш-домен/idp-api.'
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -767,7 +767,13 @@ curl -X POST http://localhost:3000/auth/otp/verify \\
|
||||
blocks: [
|
||||
{
|
||||
type: 'paragraph',
|
||||
text: '1) Пользователь авторизуется в Lendry ID. 2) Ваше приложение перенаправляет на GET /oauth/authorize с clientId, redirectUri, scope, userId. 3) IdP возвращает redirectUrl с authorization code. 4) Backend обменивает code на токены через POST /oauth/token. 5) GET /oauth/userinfo возвращает профиль.'
|
||||
text: '1) Пользователь авторизуется в IdP. 2) Ваше приложение перенаправляет на GET /oauth/authorize с clientId, redirectUri, scope, userId. 3) IdP возвращает redirectUrl с authorization code. 4) Backend обменивает code на токены через POST /oauth/token. 5) GET /oauth/userinfo возвращает профиль. Базовый URL (issuer) берётся из настройки PUBLIC_API_URL в админ-панели — примеры кода ниже подставляют его автоматически.'
|
||||
},
|
||||
{
|
||||
type: 'callout',
|
||||
variant: 'info',
|
||||
title: 'OpenID Connect Discovery',
|
||||
text: 'Метаданные провайдера: GET {PUBLIC_API_URL}/.well-known/openid-configuration. В стороннем сервисе укажите issuer = PUBLIC_API_URL (например https://sso.example.ru/idp-api), а не URL authorization endpoint. Если API доступен через /idp-api на домене frontend, issuer тоже должен включать этот путь.'
|
||||
},
|
||||
{
|
||||
type: 'callout',
|
||||
|
||||
@@ -5,14 +5,15 @@ export interface OAuthExample {
|
||||
code: string;
|
||||
}
|
||||
|
||||
const API_BASE = 'https://id.lendry.ru';
|
||||
export function buildOAuthExamples(apiBase: string): OAuthExample[] {
|
||||
const API_BASE = apiBase.replace(/\/+$/, '');
|
||||
|
||||
export const oauthExamples: OAuthExample[] = [
|
||||
{
|
||||
id: 'javascript',
|
||||
label: 'JavaScript',
|
||||
language: 'javascript',
|
||||
code: `// Authorization Code Flow (Node.js / браузер)
|
||||
return [
|
||||
{
|
||||
id: 'javascript',
|
||||
label: 'JavaScript',
|
||||
language: 'javascript',
|
||||
code: `// Authorization Code Flow (Node.js / браузер)
|
||||
const clientId = 'YOUR_CLIENT_ID';
|
||||
const redirectUri = 'https://app.example.com/oauth/callback';
|
||||
const scope = 'openid profile email';
|
||||
@@ -27,6 +28,9 @@ authorizeUrl.searchParams.set('scope', scope);
|
||||
authorizeUrl.searchParams.set('state', state);
|
||||
window.location.href = authorizeUrl.toString();
|
||||
|
||||
// OIDC Discovery (issuer = PUBLIC_API_URL из настроек админки)
|
||||
// GET ${API_BASE}/.well-known/openid-configuration
|
||||
|
||||
// Шаг 2: обменять code на токены (на backend!)
|
||||
const tokenResponse = await fetch('${API_BASE}/oauth/token', {
|
||||
method: 'POST',
|
||||
@@ -45,20 +49,21 @@ const tokens = await tokenResponse.json();
|
||||
const profile = await fetch('${API_BASE}/oauth/userinfo', {
|
||||
headers: { Authorization: \`Bearer \${tokens.accessToken}\` }
|
||||
}).then((r) => r.json());`
|
||||
},
|
||||
{
|
||||
id: 'typescript-next',
|
||||
label: 'Next.js',
|
||||
language: 'typescript',
|
||||
code: `// app/api/oauth/callback/route.ts
|
||||
},
|
||||
{
|
||||
id: 'typescript-next',
|
||||
label: 'Next.js',
|
||||
language: 'typescript',
|
||||
code: `// app/api/oauth/callback/route.ts
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
const ISSUER = '${API_BASE}';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const code = request.nextUrl.searchParams.get('code');
|
||||
const state = request.nextUrl.searchParams.get('state');
|
||||
if (!code) return NextResponse.redirect('/login?error=oauth');
|
||||
|
||||
const tokenRes = await fetch('${API_BASE}/oauth/token', {
|
||||
const tokenRes = await fetch(\`\${ISSUER}/oauth/token\`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
@@ -75,12 +80,12 @@ export async function GET(request: NextRequest) {
|
||||
response.cookies.set('access_token', tokens.accessToken, { httpOnly: true, secure: true });
|
||||
return response;
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'python',
|
||||
label: 'Python',
|
||||
language: 'python',
|
||||
code: `import requests
|
||||
},
|
||||
{
|
||||
id: 'python',
|
||||
label: 'Python',
|
||||
language: 'python',
|
||||
code: `import requests
|
||||
from urllib.parse import urlencode
|
||||
|
||||
API_BASE = '${API_BASE}'
|
||||
@@ -88,7 +93,9 @@ 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,
|
||||
@@ -98,7 +105,6 @@ params = urlencode({
|
||||
})
|
||||
authorize_url = f'{API_BASE}/oauth/authorize?{params}'
|
||||
|
||||
# Обмен authorization code на токены
|
||||
token_response = requests.post(f'{API_BASE}/oauth/token', json={
|
||||
'grantType': 'authorization_code',
|
||||
'code': 'AUTHORIZATION_CODE',
|
||||
@@ -108,24 +114,25 @@ token_response = requests.post(f'{API_BASE}/oauth/token', json={
|
||||
}, timeout=15)
|
||||
tokens = token_response.json()
|
||||
|
||||
# UserInfo
|
||||
profile = requests.get(
|
||||
f'{API_BASE}/oauth/userinfo',
|
||||
headers={'Authorization': f"Bearer {tokens['accessToken']}"},
|
||||
timeout=15
|
||||
).json()`
|
||||
},
|
||||
{
|
||||
id: 'php',
|
||||
label: 'PHP',
|
||||
language: 'php',
|
||||
code: `<?php
|
||||
$apiBase = '${API_BASE}';
|
||||
},
|
||||
{
|
||||
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';
|
||||
|
||||
// Redirect пользователя
|
||||
// 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,
|
||||
@@ -134,41 +141,13 @@ $params = http_build_query([
|
||||
'state' => bin2hex(random_bytes(16)),
|
||||
]);
|
||||
header('Location: ' . $apiBase . '/oauth/authorize?' . $params);
|
||||
exit;
|
||||
|
||||
// Callback: обмен code -> token
|
||||
$payload = json_encode([
|
||||
'grantType' => 'authorization_code',
|
||||
'code' => $_GET['code'],
|
||||
'clientId' => $clientId,
|
||||
'clientSecret' => $clientSecret,
|
||||
'redirectUri' => $redirectUri,
|
||||
]);
|
||||
|
||||
$ch = curl_init($apiBase . '/oauth/token');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_POSTFIELDS => $payload,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
]);
|
||||
$tokens = json_decode(curl_exec($ch), true);
|
||||
curl_close($ch);
|
||||
|
||||
// UserInfo
|
||||
$ch = curl_init($apiBase . '/oauth/userinfo');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $tokens['accessToken']],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
]);
|
||||
$profile = json_decode(curl_exec($ch), true);
|
||||
curl_close($ch);`
|
||||
},
|
||||
{
|
||||
id: 'go',
|
||||
label: 'Go',
|
||||
language: 'go',
|
||||
code: `package main
|
||||
exit;`
|
||||
},
|
||||
{
|
||||
id: 'go',
|
||||
label: 'Go',
|
||||
language: 'go',
|
||||
code: `package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -187,63 +166,33 @@ func buildAuthorizeURL(userID, clientID, redirectURI, scope, state string) strin
|
||||
q.Set("scope", scope)
|
||||
q.Set("state", state)
|
||||
return apiBase + "/oauth/authorize?" + q.Encode()
|
||||
}
|
||||
|
||||
func exchangeCode(code, clientID, clientSecret, redirectURI string) (map[string]any, error) {
|
||||
body, _ := json.Marshal(map[string]string{
|
||||
"grantType": "authorization_code",
|
||||
"code": code,
|
||||
"clientId": clientID,
|
||||
"clientSecret": clientSecret,
|
||||
"redirectUri": redirectURI,
|
||||
})
|
||||
resp, err := http.Post(apiBase+"/oauth/token", "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var tokens map[string]any
|
||||
return tokens, json.NewDecoder(resp.Body).Decode(&tokens)
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'csharp',
|
||||
label: 'C#',
|
||||
language: 'csharp',
|
||||
code: `using System.Net.Http.Json;
|
||||
},
|
||||
{
|
||||
id: 'csharp',
|
||||
label: 'C#',
|
||||
language: 'csharp',
|
||||
code: `using System.Net.Http.Json;
|
||||
|
||||
var apiBase = "${API_BASE}";
|
||||
var clientId = Environment.GetEnvironmentVariable("OAUTH_CLIENT_ID");
|
||||
var clientSecret = Environment.GetEnvironmentVariable("OAUTH_CLIENT_SECRET");
|
||||
var redirectUri = "https://app.example.com/oauth/callback";
|
||||
|
||||
// Authorization URL
|
||||
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";
|
||||
$"&redirectUri={Uri.EscapeDataString(redirectUri)}&scope=openid profile email&state=xyz";`
|
||||
},
|
||||
{
|
||||
id: 'curl',
|
||||
label: 'cURL',
|
||||
language: 'bash',
|
||||
code: `# OIDC Discovery (issuer = ${API_BASE})
|
||||
curl ${API_BASE}/.well-known/openid-configuration
|
||||
|
||||
using var http = new HttpClient();
|
||||
|
||||
// Token exchange
|
||||
var tokenResponse = await http.PostAsJsonAsync($"{apiBase}/oauth/token", new {
|
||||
grantType = "authorization_code",
|
||||
code = "AUTHORIZATION_CODE",
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri
|
||||
});
|
||||
var tokens = await tokenResponse.Content.ReadFromJsonAsync<Dictionary<string, object>>();
|
||||
|
||||
// UserInfo
|
||||
http.DefaultRequestHeaders.Authorization =
|
||||
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", tokens!["accessToken"].ToString());
|
||||
var profile = await http.GetFromJsonAsync<object>($"{apiBase}/oauth/userinfo");`
|
||||
},
|
||||
{
|
||||
id: 'curl',
|
||||
label: 'cURL',
|
||||
language: 'bash',
|
||||
code: `# Authorization (браузер пользователя)
|
||||
# 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"
|
||||
|
||||
# Обмен code на токены
|
||||
@@ -259,15 +208,10 @@ curl -X POST ${API_BASE}/oauth/token \\
|
||||
|
||||
# UserInfo
|
||||
curl ${API_BASE}/oauth/userinfo \\
|
||||
-H "Authorization: Bearer ACCESS_TOKEN"
|
||||
-H "Authorization: Bearer ACCESS_TOKEN"`
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
# Refresh token
|
||||
curl -X POST ${API_BASE}/oauth/token \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{
|
||||
"grantType": "refresh_token",
|
||||
"refreshToken": "REFRESH_TOKEN",
|
||||
"clientId": "CLIENT_ID"
|
||||
}'`
|
||||
}
|
||||
];
|
||||
/** @deprecated Используйте buildOAuthExamples(apiBase) */
|
||||
export const oauthExamples = buildOAuthExamples('http://localhost:3000');
|
||||
|
||||
41
apps/docs/lib/oauth-url.ts
Normal file
41
apps/docs/lib/oauth-url.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
export function normalizeBaseUrl(url: string) {
|
||||
return url.trim().replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
export function resolveOAuthApiBase(settings: Record<string, string>, fallback = 'http://localhost:3000') {
|
||||
const publicApi = settings.PUBLIC_API_URL?.trim();
|
||||
if (publicApi) {
|
||||
return normalizeBaseUrl(publicApi);
|
||||
}
|
||||
|
||||
const domain = settings.PROJECT_DOMAIN?.trim();
|
||||
if (domain) {
|
||||
if (domain.startsWith('http://') || domain.startsWith('https://')) {
|
||||
return normalizeBaseUrl(domain);
|
||||
}
|
||||
return `https://${domain.replace(/^\/+/, '')}`;
|
||||
}
|
||||
|
||||
return normalizeBaseUrl(fallback);
|
||||
}
|
||||
|
||||
export interface OAuthEndpoints {
|
||||
issuer: string;
|
||||
authorizationEndpoint: string;
|
||||
tokenEndpoint: string;
|
||||
userInfoEndpoint: string;
|
||||
openIdConfigurationUrl: string;
|
||||
jwksUrl: string;
|
||||
}
|
||||
|
||||
export function buildOAuthEndpoints(apiBase: string): OAuthEndpoints {
|
||||
const base = normalizeBaseUrl(apiBase);
|
||||
return {
|
||||
issuer: base,
|
||||
authorizationEndpoint: `${base}/oauth/authorize`,
|
||||
tokenEndpoint: `${base}/oauth/token`,
|
||||
userInfoEndpoint: `${base}/oauth/userinfo`,
|
||||
openIdConfigurationUrl: `${base}/.well-known/openid-configuration`,
|
||||
jwksUrl: `${base}/.well-known/jwks.json`
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,28 @@
|
||||
import type { NextConfig } from 'next';
|
||||
|
||||
const nextConfig: NextConfig = {};
|
||||
const internalApiUrl = (
|
||||
process.env.INTERNAL_API_URL ??
|
||||
process.env.NEXT_PUBLIC_API_URL ??
|
||||
'http://localhost:3000'
|
||||
).replace(/\/$/, '');
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: '/idp-api/:path*',
|
||||
destination: `${internalApiUrl}/:path*`
|
||||
},
|
||||
{
|
||||
source: '/oauth/:path*',
|
||||
destination: `${internalApiUrl}/oauth/:path*`
|
||||
},
|
||||
{
|
||||
source: '/.well-known/:path*',
|
||||
destination: `${internalApiUrl}/.well-known/:path*`
|
||||
}
|
||||
];
|
||||
}
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
Reference in New Issue
Block a user