- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在使用 TSED - TypeScript Express Decorators ( https://tsed.io ),它取代了如下的快速代码:
server.get('/api/tasks', passport.authenticate('oauth-bearer', { session: false }), listTasks);
带有带注释的中间件类 - https://tsed.io/docs/middlewares.html
现在对 passport.authenticate()
的调用位于 use()
方法中,如下所示:
@OverrideMiddleware(AuthenticatedMiddleware)
export class UserAuthMiddleware implements IMiddleware {
constructor(@Inject() private authService: AuthService) {
}
public use(
@EndpointInfo() endpoint: EndpointMetadata,
@Request() request: express.Request,
@Response() response: express.Response,
@Next() next: express.NextFunction
) {
const options = endpoint.get(AuthenticatedMiddleware) || {};
this.authService.authenticate(request, response, next); // <-- HERE
if (!request.isAuthenticated()) {
throw new Forbidden('Forbidden');
}
next();
}
}
然后我的AuthService.authenticate()
是
authenticate(request: express.Request, response: express.Response, next: express.NextFunction) {
console.log(`before passport authenticate time: ${Date.now()}`);
Passport.authenticate('oauth-bearer', {session: false})(request, response, next);
console.log(`after passport authenticate time : ${Date.now()}`);
}
我的 Passport 配置是在同一个 AuthService 类中执行的:
@Service()
export class AuthService implements BeforeRoutesInit, AfterRoutesInit {
users = [];
owner = '';
constructor(private serverSettings: ServerSettingsService,
@Inject(ExpressApplication) private expressApplication: ExpressApplication) {
}
$beforeRoutesInit() {
this.expressApplication.use(Passport.initialize());
}
$afterRoutesInit() {
this.setup();
}
setup() {
Passport.use('oauth-bearer', new BearerStrategy(jwtOptions, (token: ITokenPayload, done: VerifyCallback) => {
// TODO - reconsider the use of an array for Users
const findById = (id, fn) => {
for (let i = 0, len = this.users.length; i < len; i++) {
const user = this.users[i];
if (user.oid === id) {
logger.info('Found user: ', user);
return fn(null, user);
}
}
return fn(null, null);
};
console.log(token, 'was the token retrieved');
findById(token.oid, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
// 'Auto-registration'
logger.info('User was added automatically as they were new. Their oid is: ', token.oid);
this.users.push(token);
this.owner = token.oid;
const val = done(null, token);
console.log(`after strategy done authenticate time: ${Date.now()}`)
return val;
}
this.owner = token.oid;
const val = done(null, user, token);
console.log(`after strategy done authenticate time: ${Date.now()}`);
return val;
});
}));
}
这一切都有效 - 我的 Azure 配置和设置登录并检索我的 API 的 access_token,并且此 token 成功进行身份验证并将用户对象放置在请求中。
然而,Passport.authenticate()
似乎是异步的,并且直到 request.isAuthenticated()
测试之后才完成。可以看出,我已经添加了时间评论。 afterpassportauthentication time: xxx
发生在 before
后 2 毫秒。
策略完成后验证时间:xxx
发生在 Passport 验证时间后:xxx
一秒后。
所以对我来说这看起来像是异步行为。
查看node_modules/passport/lib/middleware/authenticate.js
( https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js ),没有提到 promise 或异步。然而,在 node_modules/passport-azure-ad/lib/bearerstrategy.js
( https://github.com/AzureAD/passport-azure-ad/blob/dev/lib/bearerstrategy.js ) 中是一个 async.waterfall
:
/*
* We let the metadata loading happen in `authenticate` function, and use waterfall
* to make sure the authentication code runs after the metadata loading is finished.
*/
Strategy.prototype.authenticate = function authenticateStrategy(req, options) {
const self = this;
var params = {};
var optionsToValidate = {};
var tenantIdOrName = options && options.tenantIdOrName;
/* Some introduction to async.waterfall (from the following link):
* http://stackoverflow.com/questions/28908180/what-is-a-simple-implementation-of-async-waterfall
*
* Runs the tasks array of functions in series, each passing their results
* to the next in the array. However, if any of the tasks pass an error to
* their own callback, the next function is not executed, and the main callback
* is immediately called with the error.
*
* Example:
*
* async.waterfall([
* function(callback) {
* callback(null, 'one', 'two');
* },
* function(arg1, arg2, callback) {
* // arg1 now equals 'one' and arg2 now equals 'two'
* callback(null, 'three');
* },
* function(arg1, callback) {
* // arg1 now equals 'three'
* callback(null, 'done');
* }
* ], function (err, result) {
* // result now equals 'done'
* });
*/
async.waterfall([
// compute metadataUrl
(next) => {
params.metadataURL = aadutils.concatUrl(self._options.identityMetadata,
[
`${aadutils.getLibraryProductParameterName()}=${aadutils.getLibraryProduct()}`,
`${aadutils.getLibraryVersionParameterName()}=${aadutils.getLibraryVersion()}`
]
);
// if we are not using the common endpoint, but we have tenantIdOrName, just ignore it
if (!self._options._isCommonEndpoint && tenantIdOrName) {
...
...
return self.jwtVerify(req, token, params.metadata, optionsToValidate, verified);
}],
(waterfallError) => { // This function gets called after the three tasks have called their 'task callbacks'
if (waterfallError) {
return self.failWithLog(waterfallError);
}
return true;
}
);
};
这会导致异步代码吗?如果在“普通 express 中间件”中运行会有问题吗?有人可以证实我所说的或否认我所说的并提供一个有效的解决方案吗?
<小时/>根据记录,我开始在我的 SO 问题中寻求有关 Passport-Azure-Ad 问题的帮助 - Azure AD open BearerStrategy "TypeError: self.success is not a function" 。那里的问题似乎已经解决了。
<小时/>编辑 - 标题最初包含“在 TSED 框架中”,但我相信所描述的问题仅存在于 passport-azure-ad
中。
最佳答案
这是一个解决我认为 passport-azure-ad
异步问题的解决方案,但无法控制它。它不是我想要的答案 - 确认我所说的或否认我所说的并提供一个有效的解决方案。
以下是 https://tsed.io 的解决方案框架。在 https://github.com/TypedProject/ts-express-decorators/issues/559他们建议不要使用 @OverrideMiddleware(AuthenticatedMiddleware) 而是使用 @UseAuth 中间件。它的作用是为了说明目的,这在这里并不重要(我将很快处理反馈)。
@OverrideMiddleware(AuthenticatedMiddleware)
export class UserAuthMiddleware implements IMiddleware {
constructor(@Inject() private authService: AuthService) {
}
// NO THIS VERSION DOES NOT WORK. I even removed checkForAuthentication() and
// inlined the setInterval() but it made no difference
// Before the 200 is sent WITH content, a 204 NO CONTENT is
// HAD TO CHANGE to the setTimeout() version
// async checkForAuthentication(request: express.Request): Promise<void> {
// return new Promise<void>(resolve => {
// let iterations = 30;
// const id = setInterval(() => {
// if (request.isAuthenticated() || iterations-- <= 0) {
// clearInterval(id);
// resolve();
// }
// }, 50);
// });
// }
// @async
public use(
@EndpointInfo() endpoint: EndpointMetadata,
@Request() request: express.Request,
@Response() response: express.Response,
@Next() next: express.NextFunction
) {
const options = endpoint.get(AuthenticatedMiddleware) || {};
this.authService.authenticate(request, response, next);
// AS DISCUSSED above this doesn't work
// await this.checkForAuthentication(request);
// TODO - check roles in options against AD scopes
// if (!request.isAuthenticated()) {
// throw new Forbidden('Forbidden');
// }
// next();
// HAD TO USE setTimeout()
setTimeout(() => {
if (!request.isAuthenticated()) {
console.log(`throw forbidden`);
throw new Forbidden('Forbidden');
}
next();
}, 1500);
}
<小时/>
编辑 - 我有一个使用 setInterval()
的版本,但我发现它不起作用。我什至尝试将代码内联到一个方法中,这样我就可以删除async
。它似乎导致 UserAuthMiddleware
附加到的 @Post
立即完成并返回 204“无内容”。序列将在此之后完成,并且将返回包含所需内容的 200,但为时已晚。我不明白为什么。
关于node.js - Passport-Azure-Ad 似乎异步运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56389077/
已经为此工作了几个小时,非常令人沮丧...... router.post('/', passport.authenticate('local-signup', function(err, user,
我正在寻找一种方法让我的客户端使用 facebook JS SDK 进行授权,然后以某种方式将此授权传输到我的 Node 服务器(以便它可以使用 fb graph api 验证请求) 我偶然发现: h
passport.socketio 抛出此错误,同时无法授权用户。 Error: Error: Failed to deserialize user out of session 我已将问题范围缩小到
passport.js 函数passport.serializeUser 和passport.serializeUser 有什么作用?这是维基百科中描述的序列化示例:http://en.wikiped
现代 Passport 和身份证的底部带有machine-readable zone (MRZ),其中包含基本标识信息(可能是OCR友好格式)。 机读区的格式指定了check digits的数量,可帮
我尝试对我的应用程序实现 passport 身份验证策略,但在尝试登录后不断收到以下错误: TypeError: passport.authenticate is not a function at
我正在将 passport 与 loopback 集成,并且工作正常,问题是如何获取访问 token 。 我有一个 web 应用程序(服务于与环回不同的服务器)所以: 发出请求(在环回后端) 这会将我
我使用带有passport-saml 策略 的 Passport 。在策略 上,有一个我想使用的函数。我知道策略是这样使用的: const SamlStrategy = require('passpo
这是我的套接字配置: // set authorization for socket.io io.set('authorization', passportSocketIo.authorize
我是 Passport.js 的新手。我一直在关注以下博客来注册用户 https://scotch.io/tutorials/easy-node-authentication-setup-and-lo
Passport 似乎是简单例份验证、不显眼且不难设置的绝佳选择。我正在构建一个使用 JWT 进行身份验证的 MEAN 堆栈,因此我查看了 Passport JWT。然而,有几件事我很困惑。 1) 假
我已经开始开发一个小项目,在客户端使用 React 和 Redux,后端是用 Node、Express 和 Passport.js 完成的我将尽力描述我几个小时以来所苦苦挣扎的事情。身份验证后,当用户
我正在使用 Passport 本地策略和 Passport Mongoose 本地来创建用户并检查用户身份验证。但是,我想探索使用电子邮件而不是用户名的选项。我按照文件的规定进行操作,但我未经授权。有
我正在使用 Passport 本地策略进行身份验证。在我的快速服务器中,我收到一个注册帖子请求,我应该为新用户将密码保存到数据库。但是我需要在保存到数据库之前对密码进行哈希处理。 但我不确定如何对其进
我正在将 node 与 express + mongoose 一起使用,并尝试将 passport.js 与 restful api 一起使用。 身份验证成功后,我不断收到此异常(我在浏览器上看到回调
我正在尝试在 JWTStrategy 中检查列入黑名单的 JWT token 。 jwtFromRequest 没有采用异步函数,所以我无法在那里检查它。 validate 函数提供对 JWT 负载而
目前,我正在通过 Google 构建登录功能,但我遇到了一些让我感到困惑的问题。 我们可以在一个项目中同时使用 Restful API 和 Graphql API 吗?除了谷歌身份验证,我们需要一些路
我正在使用与 express 配合良好的 Passport 本地策略: passport.use(localStrategy); passport.serializeUser((user, done)
我正在尝试通过passport-facebook 对用户进行身份验证,并且发生了一件非常奇怪的事情,我真的不确定。定义我的路线时,我有这行代码 app.get('/login/facebook',
当我使用 NPM 包“passport-azure-ad”尝试连接到 Azure AD 时,出现以下错误。我已成功连接到 Facebook、Google 和 MSFT Live,成功,但无法弄清楚为什
我是一名优秀的程序员,十分优秀!