Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 1x 1x 1x 1x 1x 1x 46x 1x 46x 45x 44x 46x 46x 1x 45x 45x 45x 45x 45x 45x | import {AuthenticationStrategy} from '@loopback/authentication';
import {inject} from '@loopback/core';
import {RedirectRoute} from '@loopback/rest';
import {UserProfile} from '@loopback/security';
import {Request} from 'express';
import {ParamsDictionary} from 'express-serve-static-core';
import {ParsedQs} from 'qs';
import {TokenServiceBindings} from '../keys';
import {JWTService} from '../services/jwt-service';
import errorMessages from '../utils/errorMessages';
let {authorizationMissing, notBearer, notBearerType} = errorMessages
export class JWTStrategy implements AuthenticationStrategy {
name: string = 'jwt';
@inject(TokenServiceBindings.TOKEN_SERVICE)
public jwtService: JWTService;
async authenticate(request: Request<ParamsDictionary, any, any, ParsedQs>):
Promise<UserProfile | RedirectRoute | undefined> {
const token: string = this.extractCredentials(request);
const userProfile = await this.jwtService.verifyToken(token);
return Promise.resolve(userProfile);
}
extractCredentials(request: Request<ParamsDictionary, any, any, ParsedQs>): string {
let methodName = "extractCredentials"
if (!request.headers.authorization) {
throw {code: 401, message: authorizationMissing, methodName,className:JWTStrategy.name}
}
const authHeaderValue = request.headers.authorization;
Iif (!authHeaderValue.startsWith('Bearer')) {
throw {code: 401, message: notBearer, methodName,className:JWTStrategy.name}
}
const parts = authHeaderValue.split(' ');
Iif (parts.length !== 2) {
throw {code: 401, message: notBearerType, methodName,className:JWTStrategy.name}
}
const token = parts[1];
return token;
}
}
|