我注意到这些文档指定我可以创建一个令牌,使其过期3600秒later1,但是我不知道如何使用auth().createCustomToken .我可以用jsonwektoken手动完成它,但这似乎应该是可以直接用firebase-admin库寻址的。
另一个问题是,我需要验证以这种方式生成的令牌uid的秘密是什么?
index.js
// demo server generating custom auth for firebase
import Koa from 'koa'
import Koajwt from 'koa-jwt'
import Token from './token'
const app = new Koa()
// Custom 401 handling if you don't want to expose koa-jwt errors to users
app.use(function(ctx, next){
return next().catch((err) => {
if (401 == err.status) {
ctx.status = 401
ctx.body = 'Protected resource, use Authorization header to get access\n'
} else {
throw err
}
})
})
// Unprotected middleware
app.use(function(ctx, next){
if (ctx.url.match(/^\/login/)) {
// use router , post, https to securely send an id
const conf = {
uid: 'sample-user-uid',
claims: {
// Optional custom claims to include in the Security Rules auth / request.auth variables
appid: 'sample-app-uid'
}
}
ctx.body = {
token: Token.generateJWT(conf)
}
} else {
return next();
}
});
// Middleware below this line is only reached if JWT token is valid
app.use(Koajwt({ secret: 'shared-secret' }))
// Protected middleware
app.use(function(ctx){
if (ctx.url.match(/^\/api/)) {
ctx.body = 'protected\n'
}
})
app.listen(3000);token.js
//import jwt from 'jsonwebtoken'
import FirebaseAdmin from 'firebase-admin'
import serviceAccount from 'demo-admin-firebase-adminsdk-$$$$-$$$$$$.json'
export default {
isInitialized: false,
init() {
FirebaseAdmin.credential.cert(serviceAccount)
isInitialized = true
},
/* generateJWTprimiative (payload, signature, conf) {
// like: jwt.sign({ data: 'foobar' }, 'secret', { expiresIn: '15m' })
jwt.sign(payload, signature, conf)
} */
generateJWT (conf) {
if(! this.isInitialized)
init()
FirebaseAdmin.auth().createCustomToken(conf.uid, conf.claims)
.then(token => {
return token
})
.catch(err => {
console.log('no token generate because', err)
})
}
}发布于 2018-11-21 17:43:11
您不能更改令牌过期。您找到的文档包括以下几个字:
Firebase令牌符合OpenID连接JWT规范,这意味着保留下列声明,不能在附加声明中指定:经验..。
通过检查Firebase源代码论GitHub,可以进一步备份它。
在本节中:
public createCustomToken(uid: string, developerClaims?: {[key: string]: any}): Promise<string> {
// .... cut for length ....
const header: JWTHeader = {
alg: ALGORITHM_RS256,
typ: 'JWT',
};
const iat = Math.floor(Date.now() / 1000);
const body: JWTBody = {
aud: FIREBASE_AUDIENCE,
iat,
exp: iat + ONE_HOUR_IN_SECONDS,
iss: account,
sub: account,
uid,
};
if (Object.keys(claims).length > 0) {
body.claims = claims;
}
// .... cut for length ....您可以看到exp属性被硬编码为iat + ONE_HOUR_IN_SECONDS,其中常量在代码的其他地方定义为60 * 60.
如果要自定义过期时间,则必须通过第三方JWT包创建自己的令牌。
对于第二个问题,秘密通常存储在服务器环境变量中,并且是预先设置的字符串或密码。从技术上讲,您可以使用UID作为秘密,但这将是一个糟糕的想法,安全方面-请不要这样做。你的秘密应该像你的密码,保持它的安全,不要将它与你的源代码上传到GitHub。您可以阅读有关在Firebase 在这些文档里中设置和检索环境变量的更多信息。
https://stackoverflow.com/questions/53413573
复制相似问题