274 lines
8.0 KiB
TypeScript
274 lines
8.0 KiB
TypeScript
export interface OAuthExample {
|
|
id: string;
|
|
label: string;
|
|
language: string;
|
|
code: string;
|
|
}
|
|
|
|
const API_BASE = 'https://id.lendry.ru';
|
|
|
|
export const oauthExamples: OAuthExample[] = [
|
|
{
|
|
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';
|
|
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('scope', scope);
|
|
authorizeUrl.searchParams.set('state', state);
|
|
window.location.href = authorizeUrl.toString();
|
|
|
|
// Шаг 2: обменять code на токены (на backend!)
|
|
const tokenResponse = await fetch('${API_BASE}/oauth/token', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
grantType: 'authorization_code',
|
|
code: 'AUTHORIZATION_CODE',
|
|
clientId,
|
|
clientSecret: 'YOUR_CLIENT_SECRET',
|
|
redirectUri
|
|
})
|
|
});
|
|
const tokens = await tokenResponse.json();
|
|
|
|
// Шаг 3: получить профиль
|
|
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
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
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', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
grantType: 'authorization_code',
|
|
code,
|
|
clientId: process.env.OAUTH_CLIENT_ID,
|
|
clientSecret: process.env.OAUTH_CLIENT_SECRET,
|
|
redirectUri: 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 });
|
|
return response;
|
|
}`
|
|
},
|
|
{
|
|
id: 'python',
|
|
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'
|
|
|
|
# Ссылка для входа пользователя
|
|
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 code на токены
|
|
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)
|
|
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}';
|
|
$clientId = getenv('OAUTH_CLIENT_ID');
|
|
$clientSecret = getenv('OAUTH_CLIENT_SECRET');
|
|
$redirectUri = 'https://app.example.com/oauth/callback';
|
|
|
|
// Redirect пользователя
|
|
$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;
|
|
|
|
// 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
|
|
|
|
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()
|
|
}
|
|
|
|
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;
|
|
|
|
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 authorizeUrl =
|
|
$"{apiBase}/oauth/authorize?userId=USER_ID&clientId={clientId}" +
|
|
$"&redirectUri={Uri.EscapeDataString(redirectUri)}&scope=openid profile email&state=xyz";
|
|
|
|
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 (браузер пользователя)
|
|
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 на токены
|
|
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"
|
|
}'
|
|
|
|
# UserInfo
|
|
curl ${API_BASE}/oauth/userinfo \\
|
|
-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"
|
|
}'`
|
|
}
|
|
];
|