接入 NJFUer ID 统一认证
NJFUer ID 使用标准 OAuth 2.0 授权码模式,并支持 OpenID Connect 的 ID Token。应用不需要接触用户密码,只需要在用户同意后拿到授权码,再用授权码换取访问令牌。
client_secret;纯前端或小程序请选择公开客户端并使用 PKCE。概览
统一认证目前接入在 https://auth.njfuer.com,提供以下能力:
- 一个 NJFUer ID 登录所有接入站点,支持手机号 邮箱 身份号。
- OAuth 2.0 授权码 + PKCE,适合服务端、SPA、小程序和桌面端。
- OpenID Connect 发现文档、JWKS 和 RS256 ID Token。
- 用户可在「我的身份」查看并撤销应用授权。
端点
| 用途 | 地址 |
|---|---|
| 授权 | https://auth.njfuer.com/oauth/authorize |
| 令牌 | https://auth.njfuer.com/oauth/token.php |
| 用户信息 | https://auth.njfuer.com/oauth/userinfo.php |
| 撤销令牌 | https://auth.njfuer.com/oauth/revoke.php |
| 退出登录 | https://auth.njfuer.com/logout |
| OIDC 发现 | https://auth.njfuer.com/.well-known/openid-configuration |
| JWKS | https://auth.njfuer.com/.well-known/jwks.json |
| 会话检查(同域) | https://auth.njfuer.com/api/session.php |
授权流程
- 应用把用户重定向到授权端点,带上
client_id、redirect_uri、scope、state和 PKCE 参数。 - 用户未登录时,统一认证先让用户登录;已登录则直接进入授权确认(官方应用自动通过)。
- 统一认证把
code和原样的state追加到回调地址。 - 应用在服务端用
code换取access_token和refresh_token。 - 应用用
Authorization: Bearer请求用户信息,或校验 ID Token。
1. 发起授权
把用户浏览器重定向到:
https://auth.njfuer.com/oauth/authorize?
response_type=code&
client_id=njf_xxxxxxxx&
redirect_uri=https%3A%2F%2Fexample.com%2Foauth%2Fcallback&
scope=openid%20profile%20email&
state=RANDOM_STATE&
code_challenge=BASE64URL_SHA256_VERIFIER&
code_challenge_method=S256
| 参数 | 必填 | 说明 |
|---|---|---|
response_type | 是 | 固定为 code。 |
client_id | 是 | 应用列表里的 client_id。 |
redirect_uri | 是 | 必须与应用登记的回调地址完全一致。 |
scope | 否 | 空格分隔,默认使用应用登记的全部 scope。 |
state | 强烈建议 | 随机值,回调时原样返回,用于防 CSRF。 |
code_challenge | 公开客户端必填 | PKCE 的 S256 challenge。 |
code_challenge_method | 配合 PKCE | 固定 S256。 |
nonce | 可选 | 会写入 ID Token,用于防重放。 |
prompt | 可选 | 填 consent 强制显示确认页,官方应用也适用。 |
2. 换取令牌
服务端向令牌端点发送 application/x-www-form-urlencoded POST。保密客户端用 HTTP Basic 或表单传 client_secret;公开客户端只传 client_id 和 code_verifier。
POST /oauth/token.php
Content-Type: application/x-www-form-urlencoded
Authorization: Basic base64(client_id:client_secret)
grant_type=authorization_code&
code=CODE&
redirect_uri=https%3A%2F%2Fexample.com%2Foauth%2Fcallback
成功响应:
{
"access_token": "njf_at_...",
"token_type": "Bearer",
"expires_in": 7200,
"refresh_token": "njf_rt_...",
"scope": "openid profile email",
"id_token": "eyJhbGciOiJSUzI1NiIs..."
}
授权码 5 分钟有效且只能使用一次。令牌端点的响应带 Cache-Control: no-store,不要缓存。
3. 读取用户信息
GET /oauth/userinfo.php
Authorization: Bearer njf_at_...
{
"sub": "NJF20260001",
"name": "张三",
"nickname": "张三",
"preferred_username": "NJF20260001",
"email": "zhangsan@example.com",
"email_verified": false
}
sub 是稳定的用户标识,请用它作为本地账号的关联键,不要用昵称或邮箱。
4. 刷新令牌
POST /oauth/token.php
grant_type=refresh_token&
refresh_token=njf_rt_...&
client_id=njf_xxxxxxxx&
client_secret=...
刷新会轮换 refresh_token:旧令牌立即失效,请保存响应里的新令牌。刷新令牌默认 30 天有效。
5. 退出登录
跳转到 /logout 会清除统一认证会话。可带 next 指定站内返回地址。RP-Initiated Logout 可带 client_id 与 post_logout_redirect_uri,后者必须与应用登记的回调地址完全一致。
https://auth.njfuer.com/logout?next=%2Flogin.php
Scope
| scope | 返回内容 |
|---|---|
openid | sub,并签发 ID Token。 |
profile | name、nickname、preferred_username。 |
email | email、email_verified。 |
phone | phone_number、phone_number_verified。 |
只申请业务真正需要的 scope。用户可以在「我的身份」看到每个应用拿到的信息。
错误码
| 错误 | 说明 |
|---|---|
invalid_request | 缺少参数或参数格式不正确。 |
invalid_client | client_id 或 client_secret 不正确,或应用被停用。 |
invalid_grant | 授权码或 refresh_token 无效、过期、已使用。 |
invalid_scope | 请求了应用未开通的 scope。 |
access_denied | 用户拒绝了授权。 |
unsupported_grant_type | 只支持 authorization_code 和 refresh_token。 |
授权端点出错时会重定向回 redirect_uri 并带上 error、error_description 和 state;令牌端点返回 JSON。
安全清单
- 校验
state,防止登录 CSRF。 - 回调地址逐字匹配,不要用通配符或开放重定向。
client_secret只放服务端环境变量,绝不写进前端。- 公开客户端必须使用 PKCE S256,并校验
code_verifier。 - 用
sub关联本地账号;不要信任未校验的邮箱。 - 把令牌存在服务端会话或加密存储中,不要放进 URL、日志或 localStorage。
- 校验 ID Token 的
iss、aud、exp和签名(JWKS)。
PHP 服务端示例
下面是最小可用的授权码流程(保密客户端)。生产环境请使用 cURL 并校验 TLS。
<?php
session_start();
$clientId = getenv('NJFUER_CLIENT_ID');
$clientSecret = getenv('NJFUER_CLIENT_SECRET');
$redirect = 'https://example.com/oauth/callback';
if (!isset($_GET['code'])) {
$state = bin2hex(random_bytes(16));
$_SESSION['oauth_state'] = $state;
$url = 'https://auth.njfuer.com/oauth/authorize?' . http_build_query([
'response_type' => 'code',
'client_id' => $clientId,
'redirect_uri' => $redirect,
'scope' => 'openid profile email',
'state' => $state,
]);
header('Location: ' . $url);
exit;
}
if (!hash_equals($_SESSION['oauth_state'] ?? '', $_GET['state'] ?? '')) {
exit('state 校验失败');
}
$ch = curl_init('https://auth.njfuer.com/oauth/token.php');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $clientId . ':' . $clientSecret,
CURLOPT_POSTFIELDS => http_build_query([
'grant_type' => 'authorization_code',
'code' => $_GET['code'],
'redirect_uri' => $redirect,
]),
]);
$token = json_decode((string) curl_exec($ch), true);
curl_close($ch);
$ch = curl_init('https://auth.njfuer.com/oauth/userinfo.php');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $token['access_token']],
]);
$user = json_decode((string) curl_exec($ch), true);
curl_close($ch);
// $user['sub'] 是稳定的 NJFUer ID
前端 PKCE 示例
// 生成 verifier 和 challenge
const verifier = [...crypto.getRandomValues(new Uint8Array(32))]
.map(b => b.toString(16).padStart(2, '0')).join('');
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
const challenge = btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
sessionStorage.setItem('pkce_verifier', verifier);
location.href = 'https://auth.njfuer.com/oauth/authorize?' + new URLSearchParams({
response_type: 'code',
client_id: 'njf_xxxxxxxx',
redirect_uri: location.origin + '/callback',
scope: 'openid profile',
state: crypto.randomUUID(),
code_challenge: challenge,
code_challenge_method: 'S256',
});
回调时用同一个 code_verifier 换取令牌。公开客户端不需要 client_secret;令牌请求由后端代理更安全。