NJFUer ID南京林业大学校园统一身份
DEVELOPER DOCS

接入 NJFUer ID 统一认证

NJFUer ID 使用标准 OAuth 2.0 授权码模式,并支持 OpenID Connect 的 ID Token。应用不需要接触用户密码,只需要在用户同意后拿到授权码,再用授权码换取访问令牌。

先创建应用。 在 管理后台 → 应用 创建客户端,登记回调地址和 scope。服务端应用会拿到一次性显示的 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
JWKShttps://auth.njfuer.com/.well-known/jwks.json
会话检查(同域)https://auth.njfuer.com/api/session.php

授权流程

  1. 应用把用户重定向到授权端点,带上 client_id、redirect_uri、scope、state 和 PKCE 参数。
  2. 用户未登录时,统一认证先让用户登录;已登录则直接进入授权确认(官方应用自动通过)。
  3. 统一认证把 code 和原样的 state 追加到回调地址。
  4. 应用在服务端用 code 换取 access_token 和 refresh_token。
  5. 应用用 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返回内容
openidsub,并签发 ID Token。
profilename、nickname、preferred_username。
emailemail、email_verified。
phonephone_number、phone_number_verified。

只申请业务真正需要的 scope。用户可以在「我的身份」看到每个应用拿到的信息。

错误码

错误说明
invalid_request缺少参数或参数格式不正确。
invalid_clientclient_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;令牌请求由后端代理更安全。

需要帮助? 发邮件到 service@njfuer.com,或先看看 在线演示 的完整流程。