当前位置: 首页>>代码示例>>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;未经允许,请勿转载。