Working towards OpenID - Connect
- Adding id_token support - Adding bearer token header support for client api auth
This commit is contained in:
parent
40b134ace7
commit
8edfaba134
@ -5,6 +5,7 @@ import { GetUserMiddleware } from "../middlewares/user";
|
|||||||
import { createJWT } from "../../keys";
|
import { createJWT } from "../../keys";
|
||||||
import Client from "../../models/client";
|
import Client from "../../models/client";
|
||||||
import RequestError, { HttpStatusCode } from "../../helper/request_error";
|
import RequestError, { HttpStatusCode } from "../../helper/request_error";
|
||||||
|
import config from "../../config";
|
||||||
|
|
||||||
|
|
||||||
const ClientRouter = Router();
|
const ClientRouter = Router();
|
||||||
@ -33,7 +34,13 @@ ClientRouter.get("/user", Stacker(GetClientAuthMiddleware(false), GetUserMiddlew
|
|||||||
uid: req.user.uid,
|
uid: req.user.uid,
|
||||||
username: req.user.username,
|
username: req.user.username,
|
||||||
state: state
|
state: state
|
||||||
}, 30); //after 30 seconds this token is invalid
|
}, {
|
||||||
|
expiresIn: 30,
|
||||||
|
issuer: config.core.url,
|
||||||
|
algorithm: "RS256",
|
||||||
|
subject: req.user.uid,
|
||||||
|
audience: req.client.client_id
|
||||||
|
}); //after 30 seconds this token is invalid
|
||||||
res.redirect(redirect_uri + "?jwt=" + jwt + (state ? `&state=${state}` : ""));
|
res.redirect(redirect_uri + "?jwt=" + jwt + (state ? `&state=${state}` : ""));
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
@ -12,10 +12,10 @@ export function GetClientAuthMiddleware(checksecret = true, internal = false, ch
|
|||||||
let client_id = req.query.client_id || req.body.client_id;
|
let client_id = req.query.client_id || req.body.client_id;
|
||||||
let client_secret = req.query.client_secret || req.body.client_secret;
|
let client_secret = req.query.client_secret || req.body.client_secret;
|
||||||
|
|
||||||
if(!client_id && !client_secret && req.headers.authorization) {
|
if (!client_id && !client_secret && req.headers.authorization) {
|
||||||
let header = req.headers.authorization;
|
let header = req.headers.authorization;
|
||||||
let [type, val] = header.split(" ");
|
let [type, val] = header.split(" ");
|
||||||
if(val) {
|
if (val) {
|
||||||
let str = Buffer.from(val, "base64").toString("utf-8");
|
let str = Buffer.from(val, "base64").toString("utf-8");
|
||||||
let [id, secret] = str.split(":");
|
let [id, secret] = str.split(":");
|
||||||
client_id = id;
|
client_id = id;
|
||||||
@ -53,10 +53,13 @@ export function GetClientApiAuthMiddleware(permissions?: string[]) {
|
|||||||
return async (req: Request, res: Response, next: NextFunction) => {
|
return async (req: Request, res: Response, next: NextFunction) => {
|
||||||
try {
|
try {
|
||||||
const invalid_err = new RequestError(req.__("You are not logged in or your login is expired"), HttpStatusCode.UNAUTHORIZED);
|
const invalid_err = new RequestError(req.__("You are not logged in or your login is expired"), HttpStatusCode.UNAUTHORIZED);
|
||||||
let token = req.query.access_token || req.headers.authorization;
|
let token: string = req.query.access_token || req.headers.authorization;
|
||||||
if (!token)
|
if (!token)
|
||||||
throw invalid_err;
|
throw invalid_err;
|
||||||
|
|
||||||
|
if (token.toLowerCase().startsWith("bearer "))
|
||||||
|
token = token.substring(7);
|
||||||
|
|
||||||
let data: OAuthJWT;
|
let data: OAuthJWT;
|
||||||
try {
|
try {
|
||||||
data = await validateJWT(token);
|
data = await validateJWT(token);
|
||||||
|
@ -4,7 +4,7 @@ import RequestError, { HttpStatusCode } from "../../helper/request_error";
|
|||||||
import RefreshToken from "../../models/refresh_token";
|
import RefreshToken from "../../models/refresh_token";
|
||||||
import User from "../../models/user";
|
import User from "../../models/user";
|
||||||
import Client from "../../models/client";
|
import Client from "../../models/client";
|
||||||
import getOAuthJWT from "../../helper/jwt";
|
import { getAccessTokenJWT } from "../../helper/jwt";
|
||||||
|
|
||||||
const JWTRoute = promiseMiddleware(async (req: Request, res: Response) => {
|
const JWTRoute = promiseMiddleware(async (req: Request, res: Response) => {
|
||||||
let { refreshtoken } = req.query;
|
let { refreshtoken } = req.query;
|
||||||
@ -22,7 +22,7 @@ const JWTRoute = promiseMiddleware(async (req: Request, res: Response) => {
|
|||||||
|
|
||||||
let client = await Client.findById(token.client);
|
let client = await Client.findById(token.client);
|
||||||
|
|
||||||
let jwt = await getOAuthJWT({ user, permissions: token.permissions, client });
|
let jwt = await getAccessTokenJWT({ user, permissions: token.permissions, client });
|
||||||
res.json({ token: jwt });
|
res.json({ token: jwt });
|
||||||
})
|
})
|
||||||
export default JWTRoute;
|
export default JWTRoute;
|
@ -2,14 +2,14 @@ import { Request, Response } from "express";
|
|||||||
import RequestError, { HttpStatusCode } from "../../helper/request_error";
|
import RequestError, { HttpStatusCode } from "../../helper/request_error";
|
||||||
import User from "../../models/user";
|
import User from "../../models/user";
|
||||||
import Client from "../../models/client";
|
import Client from "../../models/client";
|
||||||
import getOAuthJWT from "../../helper/jwt";
|
import { getAccessTokenJWT, getIDToken, AccessTokenJWTExp } from "../../helper/jwt";
|
||||||
import Stacker from "../middlewares/stacker";
|
import Stacker from "../middlewares/stacker";
|
||||||
import { GetClientAuthMiddleware } from "../middlewares/client"
|
import { GetClientAuthMiddleware } from "../middlewares/client"
|
||||||
import ClientCode from "../../models/client_code";
|
import ClientCode from "../../models/client_code";
|
||||||
import Mail from "../../models/mail";
|
import Mail from "../../models/mail";
|
||||||
import { randomBytes } from "crypto";
|
import { randomBytes } from "crypto";
|
||||||
import moment = require("moment");
|
import moment = require("moment");
|
||||||
import { JWTExpDur } from "../../keys";
|
// import { JWTExpDur } from "../../keys";
|
||||||
import RefreshToken from "../../models/refresh_token";
|
import RefreshToken from "../../models/refresh_token";
|
||||||
import { getEncryptionKey } from "../../helper/user_key";
|
import { getEncryptionKey } from "../../helper/user_key";
|
||||||
|
|
||||||
@ -29,6 +29,8 @@ const RefreshTokenRoute = Stacker(GetClientAuthMiddleware(false, false, true), a
|
|||||||
let grant_type = req.query.grant_type || req.body.grant_type;
|
let grant_type = req.query.grant_type || req.body.grant_type;
|
||||||
if (!grant_type || grant_type === "authorization_code") {
|
if (!grant_type || grant_type === "authorization_code") {
|
||||||
let code = req.query.code || req.body.code;
|
let code = req.query.code || req.body.code;
|
||||||
|
let nonce = req.query.nonce || req.body.nonce;
|
||||||
|
|
||||||
let c = await ClientCode.findOne({ code: code })
|
let c = await ClientCode.findOne({ code: code })
|
||||||
if (!c || moment(c.validTill).isBefore()) {
|
if (!c || moment(c.validTill).isBefore()) {
|
||||||
throw new RequestError(req.__("Invalid code"), HttpStatusCode.BAD_REQUEST);
|
throw new RequestError(req.__("Invalid code"), HttpStatusCode.BAD_REQUEST);
|
||||||
@ -56,19 +58,20 @@ const RefreshTokenRoute = Stacker(GetClientAuthMiddleware(false, false, true), a
|
|||||||
res.json({
|
res.json({
|
||||||
refresh_token: token.token,
|
refresh_token: token.token,
|
||||||
token: token.token,
|
token: token.token,
|
||||||
access_token: await getOAuthJWT({
|
access_token: await getAccessTokenJWT({
|
||||||
client: client,
|
client: client,
|
||||||
user: user,
|
user: user,
|
||||||
permissions: c.permissions
|
permissions: c.permissions
|
||||||
}),
|
}),
|
||||||
token_type: "bearer",
|
token_type: "bearer",
|
||||||
expires_in: JWTExpDur.asSeconds(),
|
expires_in: AccessTokenJWTExp.asSeconds(),
|
||||||
profile: {
|
profile: {
|
||||||
uid: user.uid,
|
uid: user.uid,
|
||||||
email: mail ? mail.mail : "",
|
email: mail ? mail.mail : "",
|
||||||
name: user.name,
|
name: user.name,
|
||||||
enc_key: getEncryptionKey(user, client)
|
enc_key: getEncryptionKey(user, client)
|
||||||
}
|
},
|
||||||
|
id_token: getIDToken(user, client.client_id, nonce)
|
||||||
});
|
});
|
||||||
} else if (grant_type === "refresh_token") {
|
} else if (grant_type === "refresh_token") {
|
||||||
let refresh_token = req.query.refresh_token || req.body.refresh_token;
|
let refresh_token = req.query.refresh_token || req.body.refresh_token;
|
||||||
@ -83,8 +86,8 @@ const RefreshTokenRoute = Stacker(GetClientAuthMiddleware(false, false, true), a
|
|||||||
|
|
||||||
let user = await User.findById(token.user);
|
let user = await User.findById(token.user);
|
||||||
let client = await Client.findById(token.client)
|
let client = await Client.findById(token.client)
|
||||||
let jwt = await getOAuthJWT({ user, client, permissions: token.permissions });
|
let jwt = await getAccessTokenJWT({ user, client, permissions: token.permissions });
|
||||||
res.json({ access_token: jwt, expires_in: JWTExpDur.asSeconds() });
|
res.json({ access_token: jwt, expires_in: AccessTokenJWTExp.asSeconds() });
|
||||||
} else {
|
} else {
|
||||||
throw new RequestError("invalid grant_type", HttpStatusCode.BAD_REQUEST);
|
throw new RequestError("invalid grant_type", HttpStatusCode.BAD_REQUEST);
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
import { IUser } from "../models/user";
|
import { IUser, Gender } from "../models/user";
|
||||||
import { ObjectID } from "bson";
|
import { ObjectID } from "bson";
|
||||||
import { createJWT } from "../keys";
|
import { createJWT } from "../keys";
|
||||||
import { IClient } from "../models/client";
|
import { IClient } from "../models/client";
|
||||||
|
import config from "../config";
|
||||||
|
import * as moment from "moment";
|
||||||
|
|
||||||
export interface OAuthJWT {
|
export interface OAuthJWT {
|
||||||
user: string;
|
user: string;
|
||||||
@ -10,11 +12,39 @@ export interface OAuthJWT {
|
|||||||
application: string
|
application: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function getOAuthJWT(token: { user: IUser, permissions: ObjectID[], client: IClient }) {
|
const issuer = config.core.url;
|
||||||
|
|
||||||
|
export const IDTokenJWTExp = moment.duration(30, "m").asSeconds();
|
||||||
|
export function getIDToken(user: IUser, client_id: string, nonce: string) {
|
||||||
|
return createJWT({
|
||||||
|
user: user.uid,
|
||||||
|
name: user.name,
|
||||||
|
nickname: user.username,
|
||||||
|
username: user.username,
|
||||||
|
preferred_username: user.username,
|
||||||
|
gender: Gender[user.gender],
|
||||||
|
nonce
|
||||||
|
}, {
|
||||||
|
expiresIn: IDTokenJWTExp,
|
||||||
|
issuer,
|
||||||
|
algorithm: "RS256",
|
||||||
|
subject: user.uid,
|
||||||
|
audience: client_id
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const AccessTokenJWTExp = moment.duration(6, "h");
|
||||||
|
export function getAccessTokenJWT(token: { user: IUser, permissions: ObjectID[], client: IClient }) {
|
||||||
return createJWT(<OAuthJWT>{
|
return createJWT(<OAuthJWT>{
|
||||||
user: token.user.uid,
|
user: token.user.uid,
|
||||||
username: token.user.username,
|
username: token.user.username,
|
||||||
permissions: token.permissions.map(p => p.toHexString()),
|
permissions: token.permissions.map(p => p.toHexString()),
|
||||||
application: token.client.client_id
|
application: token.client.client_id
|
||||||
|
}, {
|
||||||
|
expiresIn: AccessTokenJWTExp.asSeconds(),
|
||||||
|
issuer,
|
||||||
|
algorithm: "RS256",
|
||||||
|
subject: token.user.uid,
|
||||||
|
audience: token.client.client_id
|
||||||
})
|
})
|
||||||
}
|
}
|
56
src/jwt.ts
56
src/jwt.ts
@ -1,56 +0,0 @@
|
|||||||
interface AccessToken {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
interface IDToken {
|
|
||||||
/**
|
|
||||||
* REQUIRED. Issuer Identifier for the Issuer of the response. The iss value is a case sensitive URL using the https scheme that contains scheme, host, and optionally, port number and path components and no query or fragment components.
|
|
||||||
*/
|
|
||||||
iss: string
|
|
||||||
|
|
||||||
/**
|
|
||||||
* REQUIRED. Subject Identifier. A locally unique and never reassigned identifier within the Issuer for the End-User, which is intended to be consumed by the Client, e.g., 24400320 or AItOawmwtWwcT0k51BayewNvutrJUqsvl6qs7A4. It MUST NOT exceed 255 ASCII characters in length. The sub value is a case sensitive string.
|
|
||||||
*/
|
|
||||||
sub: string
|
|
||||||
|
|
||||||
/**
|
|
||||||
* REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.
|
|
||||||
*/
|
|
||||||
aud: string
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
REQUIRED. Expiration time on or after which the ID Token MUST NOT be accepted for processing. The processing of this parameter requires that the current date/time MUST be before the expiration date/time listed in the value. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.
|
|
||||||
*/
|
|
||||||
exp: number
|
|
||||||
|
|
||||||
/**
|
|
||||||
* REQUIRED. Time at which the JWT was issued. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time.
|
|
||||||
*/
|
|
||||||
iat: number
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Time when the End-User authentication occurred. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. When a max_age request is made or when auth_time is requested as an Essential Claim, then this Claim is REQUIRED; otherwise, its inclusion is OPTIONAL. (The auth_time Claim semantically corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] auth_time response parameter.)
|
|
||||||
*/
|
|
||||||
auth_time: number
|
|
||||||
|
|
||||||
/**
|
|
||||||
* String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. If present in the ID Token, Clients MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent in the Authentication Request. If present in the Authentication Request, Authorization Servers MUST include a nonce Claim in the ID Token with the Claim Value being the nonce value sent in the Authentication Request. Authorization Servers SHOULD perform no other processing on nonce values used. The nonce value is a case sensitive string.
|
|
||||||
*/
|
|
||||||
nonce: string
|
|
||||||
|
|
||||||
/**
|
|
||||||
* OPTIONAL. Authentication Context Class Reference. String specifying an Authentication Context Class Reference value that identifies the Authentication Context Class that the authentication performed satisfied. The value "0" indicates the End-User authentication did not meet the requirements of ISO/IEC 29115 [ISO29115] level 1. Authentication using a long-lived browser cookie, for instance, is one example where the use of "level 0" is appropriate. Authentications with level 0 SHOULD NOT be used to authorize access to any resource of any monetary value. (This corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] nist_auth_level 0.) An absolute URI or an RFC 6711 [RFC6711] registered name SHOULD be used as the acr value; registered names MUST NOT be used with a different meaning than that which is registered. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The acr value is a case sensitive string.
|
|
||||||
*/
|
|
||||||
acr?: string
|
|
||||||
|
|
||||||
/**
|
|
||||||
* OPTIONAL. Authentication Methods References. JSON array of strings that are identifiers for authentication methods used in the authentication. For instance, values might indicate that both password and OTP authentication methods were used. The definition of particular values to be used in the amr Claim is beyond the scope of this specification. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The amr value is an array of case sensitive strings.
|
|
||||||
*/
|
|
||||||
amr?: string[]
|
|
||||||
|
|
||||||
/**
|
|
||||||
* OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.
|
|
||||||
*/
|
|
||||||
azp?: string
|
|
||||||
}
|
|
10
src/keys.ts
10
src/keys.ts
@ -15,16 +15,10 @@ export let public_key: string;
|
|||||||
|
|
||||||
import * as jwt from "jsonwebtoken";
|
import * as jwt from "jsonwebtoken";
|
||||||
import config from "./config";
|
import config from "./config";
|
||||||
import * as moment from "moment";
|
|
||||||
|
|
||||||
export const JWTExpDur = moment.duration(6, "h");
|
export function createJWT(payload: any, options: jwt.SignOptions) {
|
||||||
export function createJWT(data: any, expiration?: number) {
|
|
||||||
return new Promise<string>((resolve, reject) => {
|
return new Promise<string>((resolve, reject) => {
|
||||||
return jwt.sign(data, private_key, {
|
return jwt.sign(payload, private_key, options, (err, token) => {
|
||||||
expiresIn: expiration || JWTExpDur.asSeconds(),
|
|
||||||
issuer: config.core.name,
|
|
||||||
algorithm: "RS256"
|
|
||||||
}, (err, token) => {
|
|
||||||
if (err) reject(err)
|
if (err) reject(err)
|
||||||
else resolve(token)
|
else resolve(token)
|
||||||
});
|
});
|
||||||
|
@ -1,7 +1,5 @@
|
|||||||
import DB from "../database";
|
import DB from "../database";
|
||||||
import { ModelDataBase } from "@hibas123/safe_mongo/lib/model";
|
import { ModelDataBase } from "@hibas123/safe_mongo";
|
||||||
import { ObjectID } from "mongodb";
|
|
||||||
import { v4 } from "uuid";
|
|
||||||
|
|
||||||
export interface IMail extends ModelDataBase {
|
export interface IMail extends ModelDataBase {
|
||||||
mail: string;
|
mail: string;
|
||||||
|
Loading…
Reference in New Issue
Block a user