當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript jwt-simple.decode函數代碼示例

本文整理匯總了TypeScript中jwt-simple.decode函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript decode函數的具體用法?TypeScript decode怎麽用?TypeScript decode使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了decode函數的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: async

export const ensureAuthenticated = async (ctx: Router.IRouterContext, next: (arg: any) => void) => {
  try {
    if (!ctx.headers.authorization) {
      return ctx.throw(401, 'missing_authorization_header', { message: 'Please make sure your request has an Authorization header' });
    }
    const token = ctx.headers.authorization.split(' ')[1];
    let payload = null;
    try {
      payload = decode(token, config.TOKEN_SECRET);
    }
    catch (e) {
      ctx.status = 401;
      return ctx.body = { error: true, message: e.message };
    }

    if (payload.exp <= moment().unix()) {
      return ctx.throw(401, 'expired_token', { message: 'Token has expired' });
    }

    // pass userId to the next middleware
    ctx.state.userId = payload.sub;
    await next(payload.sub);
  } catch (e) {
    return ctx.throw(500, e.message);
  }
};
開發者ID:ghiscoding,項目名稱:Realtime-TODO-Aurelia-RethinkDB,代碼行數:26,代碼來源:authUtils.ts

示例2: authenticate

export function authenticate(ctx, next): IMiddleware {
    let token = ctx.request.header.authorization;
    if (!token) {
        ctx.response.status = 401;
        ctx.body = new XError(XErrorType.UNAUTHORIZED, 'User has not logged in');
        return null;
    }

    const accountId = ctx.request.accountId;
    const host = ctx.request.header.host;

    token = token.slice(7);
    const credentialsInToken = jwt.decode(token, secret);

    const expiryTime = new Date(credentialsInToken.expiryTime);
    const currentTime = new Date();

    if (accountId !== credentialsInToken.accountId || host !== credentialsInToken.host || expiryTime.getTime() < currentTime.getTime()) {
        ctx.response.status = 401;
        ctx.body = new XError(XErrorType.UNAUTHORIZED, 'User has not logged in');
        return null;
    }

    return next();
};
開發者ID:DavidOnGitHub,項目名稱:questionApp_backend,代碼行數:25,代碼來源:authUtil.ts

示例3: function

app.post('/api/get-all-email-addresses', function (request, response) {
    var member_id = jwt.decode(request.headers['x-auth'], secretJwtKey)._id;
    ttcDB.authorizeMember(member_id)
        .then(ttcDB.getAllEmailAddresses)
        .then(function (emailaddresses) { ttcDB.recordDevice(member_id, request.headers['device']); response.json(emailaddresses); })
        .catch(function (err) { httpError(HTTP_ServerError, err, response); });
});
開發者ID:roderickmonk,項目名稱:rod-monk-sample-repo,代碼行數:7,代碼來源:Server.ts

示例4: currentUserId

 public get currentUserId() : boolean {        
     if (this.isLoggedIn === false) {
         return false;
     }
     
     let decoded = jwt.decode(this.token.token, "", true);        
     return decoded.UserId;
 }
開發者ID:LeagueLogbook,項目名稱:LogbookWebsite,代碼行數:8,代碼來源:auth-service.ts

示例5: decode

	function decode(token: string, noVerify = false) {
		const decoded = jwt.decode(token, secret || '', !secret || noVerify);
		if (secret && !noVerify && !isValidTimestamp(decoded)) {
			throw new Error('invalid timestamp');
		}
		log('decode(token: %j, secret: %j) => %j', token, secret, decoded);
		return decoded;
	}
開發者ID:urish,項目名稱:firebase-server,代碼行數:8,代碼來源:token-validator.ts

示例6: it

        it('can be created with arbitrary claims', () => {
            let token = new powerbi.PowerBIToken();
            token.addClaim('foo', 'bar');

            let genericToken = token.generate(accessKey);
            let decoded = jwt.decode(genericToken, accessKey);

            expect(decoded.foo).to.equal('bar');
        });
開發者ID:Microsoft,項目名稱:PowerBI-Node,代碼行數:9,代碼來源:PowerBIToken.test.ts

示例7: isSession

export const isSession = function isSession (req, res, next) {
  if (req.session.passport && req.headers.authorization) {
    let decoded = simple.decode(req.headers.authorization.substring(4), process.env.JWT_SECRET);
    return req.session.passport.user['username'] === decoded.username
      ? next()
      : res.status(403).json({message: 'please login.'});
  } else {
    return res.status(403).json({message: 'please login.'});
  }
};
開發者ID:bamtron5,項目名稱:webpackNGComponents,代碼行數:10,代碼來源:auth.ts

示例8: view

	/**
	 * Checks if a token is valid and returns its meta data.
	 *
	 * @see GET /v1/tokens/:id
	 * @param {Context} ctx Koa context
	 */
	public async view(ctx: Context) {

		const token = ctx.params.id;
		let tokenInfo: TokenDocument;

		// app token?
		if (/[0-9a-f]{32,}/i.test(token)) {

			const appToken = await state.models.Token.findOne({ token }).populate('_created_by').exec();

			// fail if not found
			if (!appToken) {
				throw new ApiError('Invalid token.').status(404);
			}

			tokenInfo = {
				label: appToken.label,
				type: appToken.type,
				scopes: appToken.scopes,
				created_at: appToken.created_at,
				expires_at: appToken.expires_at,
				is_active: appToken.is_active,
			} as TokenDocument;

			// additional props for provider token
			if (appToken.type === 'provider') {
				tokenInfo.provider = appToken.provider;
			} else {
				tokenInfo.for_user = (appToken._created_by as UserDocument).id;
			}

		// Otherwise, assume it's a JWT.
		} else {

			// decode
			let decoded;
			try {
				decoded = jwt.decode(token, config.vpdb.secret, false, 'HS256');
			} catch (e) {
				throw new ApiError('Invalid token.').status(404);
			}
			tokenInfo = {
				type: decoded.irt ? 'jwt-refreshed' : 'jwt',
				scopes: decoded.scp,
				expires_at: new Date(decoded.exp),
				is_active: true, // JTWs cannot be revoked, so they are always active
				for_user: decoded.iss,
			} as TokenDocument;

			if (decoded.path) {
				tokenInfo.for_path = decoded.path;
			}
		}
		this.success(ctx, tokenInfo, 200);
	}
開發者ID:freezy,項目名稱:node-vpdb,代碼行數:61,代碼來源:token.api.ts


注:本文中的jwt-simple.decode函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。