@mvx/identity
Version:
identity is oidc for mvc, type-mvc is base on koa. Decorator, Ioc, AOP mvc framework on server.
231 lines (229 loc) • 8.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.JwtRequest = exports.JwtStrategy = void 0;
const tslib_1 = require("tslib");
const ioc_1 = require("@tsdi/ioc");
const components_1 = require("@tsdi/components");
const Strategy_1 = require("./Strategy");
const results_1 = require("./results");
const url = require("url");
const jwt = require("jsonwebtoken");
/**
* Jwt authenticate strategy
*/
let JwtStrategy = class JwtStrategy extends Strategy_1.Strategy {
async onAfterInit() {
if (!this.name) {
this.name = 'jwt';
}
if (this.secretOrKey) {
if (this.secretOrKeyProvider) {
throw new TypeError('JwtStrategy has been given both a secretOrKey and a secretOrKeyProvider');
}
this.secretOrKeyProvider = async (request, rawJwtToken) => {
return this.secretOrKey;
};
}
if (!this.secretOrKeyProvider) {
throw new TypeError('JwtStrategy requires a secret or key');
}
if (!this.verify) {
throw new TypeError('JwtStrategy requires a verify');
}
if (!this.jwtFromRequest) {
throw new TypeError('JwtStrategy requires a function to retrieve jwt from requests (see option jwtFromRequest)');
}
}
async authenticate(ctx, options) {
let token = this.jwtFromRequest(ctx.request);
if (!token) {
return new results_1.FailResult('No auth token', 401);
}
let secretOrKey = this.secretOrKey = await this.secretOrKeyProvider(ctx.request, token);
let payload = await new Promise((r, j) => {
jwt.verify(token, secretOrKey, {
audience: this.audience,
issuer: this.issuer,
algorithms: this.algorithms,
ignoreExpiration: this.ignoreExpiration
}, (err, decoded) => {
if (err) {
j(err);
}
else {
r(decoded);
}
});
});
let { user, info } = await this.verify(payload, ctx);
if (!user) {
// TODO, not sure 401 is the correct meaning
return new results_1.FailResult(info, 401);
}
return new results_1.SuccessResult(options, user, info);
}
sign(payload, secretOrKey, options) {
let defer = ioc_1.PromiseUtil.defer();
jwt.sign(payload, secretOrKey || this.secretOrKey, Object.assign({ audience: this.audience, issuer: this.issuer }, (options || {})
// ignoreExpiration: this.ignoreExpiration
), (err, decoded) => {
if (err) {
defer.reject(err);
}
else {
defer.resolve(decoded);
}
});
return defer.promise;
}
static ρAnn() {
return { "name": "JwtStrategy", "params": { "authenticate": ["ctx", "options"], "sign": ["payload", "secretOrKey", "options"] } };
}
};
tslib_1.__decorate([
components_1.Input(),
tslib_1.__metadata("design:type", Function)
], JwtStrategy.prototype, "verify", void 0);
tslib_1.__decorate([
components_1.Input(),
tslib_1.__metadata("design:type", String)
], JwtStrategy.prototype, "issuer", void 0);
tslib_1.__decorate([
components_1.Input(),
tslib_1.__metadata("design:type", Object)
], JwtStrategy.prototype, "audience", void 0);
tslib_1.__decorate([
components_1.Input(),
tslib_1.__metadata("design:type", Array)
], JwtStrategy.prototype, "algorithms", void 0);
tslib_1.__decorate([
components_1.Input(),
tslib_1.__metadata("design:type", Boolean)
], JwtStrategy.prototype, "ignoreExpiration", void 0);
tslib_1.__decorate([
components_1.Input(),
tslib_1.__metadata("design:type", Object)
], JwtStrategy.prototype, "secretOrKey", void 0);
tslib_1.__decorate([
components_1.Input(),
tslib_1.__metadata("design:type", Function)
], JwtStrategy.prototype, "secretOrKeyProvider", void 0);
tslib_1.__decorate([
components_1.Input(),
tslib_1.__metadata("design:type", Function)
], JwtStrategy.prototype, "jwtFromRequest", void 0);
JwtStrategy = tslib_1.__decorate([
components_1.Component({
selector: 'jwt'
})
], JwtStrategy);
exports.JwtStrategy = JwtStrategy;
const matcExp = /(\S+)\s+(\S+)/;
function parseAuthHeader(hdrValue) {
if (typeof hdrValue !== 'string') {
return null;
}
var matches = hdrValue.match(matcExp);
return matches && { scheme: matches[1], value: matches[2] };
}
// Note: express http converts all headers
// to lower case.
const AUTH_HEADER = 'authorization', LEGACY_AUTH_SCHEME = 'JWT', BEARER_AUTH_SCHEME = 'bearer';
var JwtRequest;
(function (JwtRequest) {
function fromHeader(headerName) {
return function (request) {
var token = null;
if (request.headers[headerName]) {
token = request.headers[headerName];
}
return token;
};
}
JwtRequest.fromHeader = fromHeader;
function fromBodyField(fieldName) {
return function (request) {
var token = null;
if (request.body && Object.prototype.hasOwnProperty.call(request.body, fieldName)) {
token = request.body[fieldName];
}
return token;
};
}
JwtRequest.fromBodyField = fromBodyField;
function fromUrlQueryParameter(paramName) {
return function (request) {
let token = null, parsedUrl = url.parse(request.url, true);
if (parsedUrl.query && Object.prototype.hasOwnProperty.call(parsedUrl.query, paramName)) {
token = parsedUrl.query[paramName];
}
return token;
};
}
JwtRequest.fromUrlQueryParameter = fromUrlQueryParameter;
function fromAuthHeaderWithScheme(authScheme) {
var authSchemeLower = authScheme.toLowerCase();
return function (request) {
var token = null;
if (request.headers[AUTH_HEADER]) {
var authParams = parseAuthHeader(request.headers[AUTH_HEADER]);
if (authParams && authSchemeLower === authParams.scheme.toLowerCase()) {
token = authParams.value;
}
}
return token;
};
}
JwtRequest.fromAuthHeaderWithScheme = fromAuthHeaderWithScheme;
function fromAuthHeaderAsBearerToken() {
return fromAuthHeaderWithScheme(BEARER_AUTH_SCHEME);
}
JwtRequest.fromAuthHeaderAsBearerToken = fromAuthHeaderAsBearerToken;
function fromExtractors(extractors) {
if (!Array.isArray(extractors)) {
throw new TypeError('export function fromExtractors expects an array');
}
return function (request) {
var token = null;
var index = 0;
while (!token && index < length) {
token = extractors[index].call(this, request);
index++;
}
return token;
};
}
JwtRequest.fromExtractors = fromExtractors;
/**
* This extractor mimics the behavior of the v1.*.* extraction logic.
*
* This extractor exists only to provide an easy transition from the v1.*.* API to the v2.0.0
* API.
*
* This extractor first checks the auth header, if it doesn't find a token there then it checks the
* specified body field and finally the url query parameters.
*
* @param options
* authScheme: Expected scheme when JWT can be found in HTTP Authorize header. Default is JWT.
* tokenBodyField: Field in request body containing token. Default is auth_token.
* tokenQueryParameterName: Query parameter name containing the token. Default is auth_token.
*/
function versionOneCompatibility(options) {
var authScheme = options.authScheme || LEGACY_AUTH_SCHEME, bodyField = options.tokenBodyField || 'auth_token', queryParam = options.tokenQueryParameterName || 'auth_token';
return function (request) {
var authHeaderExtractor = fromAuthHeaderWithScheme(authScheme);
var token = authHeaderExtractor(request);
if (!token) {
var bodyExtractor = fromBodyField(bodyField);
token = bodyExtractor(request);
}
if (!token) {
var queryExtractor = fromUrlQueryParameter(queryParam);
token = queryExtractor(request);
}
return token;
};
}
JwtRequest.versionOneCompatibility = versionOneCompatibility;
})(JwtRequest = exports.JwtRequest || (exports.JwtRequest = {}));
//# sourceMappingURL=../sourcemaps/passports/JwtStrategy.js.map