在AppSync中,当您使用认知用户池作为设置您的身份时,您将获得
identity:
{ sub: 'bcb5cd53-315a-40df-a41b-1db02a4c1bd9',
issuer: 'https://cognito-idp.us-west-2.amazonaws.com/us-west-2_oicu812',
username: 'skillet',
claims:
{ sub: 'bcb5cd53-315a-40df-a41b-1db02a4c1bd9',
aud: '7re1oap5fhm3ngpje9r81vgpoe',
email_verified: true,
event_id: 'bb65ba5d-4689-11e8-bee7-2d0da8da81ab',
token_use: 'id',
auth_time: 1524441800,
iss: 'https://cognito-idp.us-west-2.amazonaws.com/us-west-2_oicu812',
'cognito:username': 'skillet',
exp: 1524459387,
iat: 1524455787,
email: 'myemail@nope.com' },
sourceIp: [ '11.222.33.200' ],
defaultAuthStrategy: 'ALLOW',
groups: null }但是,当您使用AWS_IAM时,您将得到
identity:
{ accountId: '12121212121', //<--- my amazon account ID
cognitoIdentityPoolId: 'us-west-2:39b1f3e4-330e-40f6-b738-266682302b59',
cognitoIdentityId: 'us-west-2:a458498b-b1ac-46c1-9c5e-bf932bad0d95',
sourceIp: [ '33.222.11.200' ],
username: 'AROAJGBZT5A433EVW6O3Q:CognitoIdentityCredentials',
userArn: 'arn:aws:sts::454227793445:assumed-role/MEMORYCARDS-CognitoAuthorizedRole-dev/CognitoIdentityCredentials',
cognitoIdentityAuthType: 'authenticated',
cognitoIdentityAuthProvider: '"cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob","cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob:CognitoSignIn:1a072f08-5c61-4c89-807e-417d22702eb7"' }医生说这是意料之中的,https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference.html。但是,如果您使用连接到科尼托的AWS_IAM (这是未经身份验证的访问所必需的),您应该如何获取用户的用户名、电子邮件、订阅等?当使用AWS_IAM类型Auth时,我需要访问用户的声明。
发布于 2018-05-23 18:57:47
这是我的答案。appSync客户端库中存在一个错误,它会覆盖所有自定义标头。从那以后就被修复了。现在,您可以传递自定义头,这将使它一直到解析器,我将它传递给我的lambda函数(同样,请注意,我使用的是lambda数据源,而不是dynamoDB)。
因此,我将登录的JWT附加到客户端,服务器端附加到lambda函数中,对其进行解码。您需要认知创建的公钥来验证JWT。(你不需要秘密钥匙。)当我第一次启动lambda时,每个用户池都关联着一个“众所周知的密钥”url,但是,就像我的mongoDB连接一样,它在lambda调用之间被持久化(至少有一段时间)。
这是兰达解析器..。
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const jwkToPem = require('jwk-to-pem');
const request = require('request-promise-native');
const _ = require('lodash')
//ITEMS THAT SHOULD BE PERSISTED BETWEEN LAMBDA EXECUTIONS
let conn = null; //MONGODB CONNECTION
let pem = null; //PROCESSED JWT PUBLIC KEY FOR OUR COGNITO USER POOL, SAME FOR EVERY USER
exports.graphqlHandler = async (event, lambdaContext) => {
// Make sure to add this so you can re-use `conn` between function calls.
// See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
lambdaContext.callbackWaitsForEmptyEventLoop = false;
try{
////////////////// AUTHORIZATION/USER INFO /////////////////////////
//ADD USER INFO, IF A LOGGED IN USER WITH VALID JWT MAKES THE REQUEST
var token = _.get(event,'context.request.headers.jwt'); //equivalen to "token = event.context.re; quest.headers.alexauthorization;" but fails gracefully
if(token){
//GET THE ID OF THE PUBLIC KEY (KID) FROM THE TOKEN HEADER
var decodedToken = jwt.decode(token, {complete: true});
// GET THE PUBLIC KEY TO NEEDED TO VERIFY THE SIGNATURE (no private/secret key needed)
if(!pem){
await request({ //blocking, waits for public key if you don't already have it
uri:`https://cognito-idp.${process.env.REGION}.amazonaws.com/${process.env.USER_POOL_ID}/.well-known/jwks.json`,
resolveWithFullResponse: true //Otherwise only the responce body would be returned
})
.then(function ( resp) {
if(resp.statusCode != 200){
throw new Error(resp.statusCode,`Request of JWT key with unexpected statusCode: expecting 200, received ${resp.statusCode}`);
}
let {body} = resp; //GET THE REPSONCE BODY
body = JSON.parse(body); //body is a string, convert it to JSON
// body is an array of more than one JW keys. User the key id in the JWT header to select the correct key object
var keyObject = _.find(body.keys,{"kid":decodedToken.header.kid});
pem = jwkToPem(keyObject);//convert jwk to pem
});
}
//VERIFY THE JWT SIGNATURE. IF THE SIGNATURE IS VALID, THEN ADD THE JWT TO THE IDENTITY OBJECT.
jwt.verify(token, pem, function(error, decoded) {//not async
if(error){
console.error(error);
throw new Error(401,error);
}
event.context.identity.user=decoded;
});
}
return run(event)
} catch (error) {//catch all errors and return them in an orderly manner
console.error(error);
throw new Error(error);
}
};
//async/await keywords used for asynchronous calls to prevent lambda function from returning before mongodb interactions return
async function run(event) {
// `conn` is in the global scope, Lambda may retain it between function calls thanks to `callbackWaitsForEmptyEventLoop`.
if (conn == null) {
//connect asyncoronously to mongodb
conn = await mongoose.createConnection(process.env.MONGO_URL);
//define the mongoose Schema
let mySchema = new mongoose.Schema({
///my mongoose schem
});
mySchema('toJSON', { virtuals: true }); //will include both id and _id
conn.model('mySchema', mySchema );
}
//Get the mongoose Model from the Schema
let mod = conn.model('mySchema');
switch(event.field) {
case "getOne": {
return mod.findById(event.context.arguments.id);
} break;
case "getAll": {
return mod.find()
} break;
default: {
throw new Error ("Lambda handler error: Unknown field, unable to resolve " + event.field);
} break;
}
}这比我的另一个“坏”答案要好得多,因为您并不总是在查询DB以获取客户端已经拥有的信息。在我的经验中大约快了3倍。
发布于 2018-04-30 23:22:46
为了使用户的用户名、电子邮件、订阅等可以通过AppSync API访问,有一个答案:https://stackoverflow.com/a/42405528/1207523
总之,您希望将用户池ID令牌发送到您的API (例如AppSync或)。您的API请求是IAM认证的。然后,在Lambda函数中验证ID令牌,现在您已经将已验证的IAM用户和用户池数据放在一起。
您希望使用IAM的identity.cognitoIdentityId作为用户表的主键。添加ID令牌中包含的数据(用户名、电子邮件等)作为属性。
通过这种方式,您可以通过API使用户的声明可用。例如,现在可以将$ctx.identity.cognitoIdentityId设置为项的所有者。然后,也许其他用户可以通过GraphQL解析器看到所有者的名称。
如果您需要访问解析器中的用户声明,恐怕目前还不可能这样做。我对此提出了一个问题,因为它对授权非常有帮助:AppSync中使用IAM认证的组授权
在这种情况下,您可以使用Lambda作为数据源,并从上面提到的用户表中检索用户的声明,而不是使用解析器。
目前这一切都有点困难:)
发布于 2018-05-01 03:56:29
这是一个很糟糕的答案。我注意到cognitoIdentityAuthProvider: '"cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob","cognito-idp.us-west-2.amazonaws.com/us-west-2_HighBob:CognitoSignIn:1a072f08-5c61-4c89-807e-417d22702eb7"包含认知用户的子(CognitoSignIn之后的大)。您可以使用regex提取该信息,并使用aws从认知用户池中获取用户的信息。
///////RETRIEVE THE AUTHENTICATED USER'S INFORMATION//////////
if(event.context.identity.cognitoIdentityAuthType === 'authenticated'){
let cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
//Extract the user's sub (ID) from one of the context indentity fields
//the REGEX in match looks for the strings btwn 'CognitoSignIn:' and '"', which represents the user sub
let userSub = event.context.identity.cognitoIdentityAuthProvider.match(/CognitoSignIn:(.*?)"/)[1];
let filter = 'sub = \"'+userSub+'\"' // string with format = 'sub = \"1a072f08-5c61-4c89-807e-417d22702eb7\"'
let usersData = await cognitoidentityserviceprovider.listUsers( {Filter: filter, UserPoolId: "us-west-2_KsyTKrQ2M",Limit: 1}).promise()
event.context.identity.user=usersData.Users[0]; }
这是一个糟糕的答案,因为您正在点击用户池数据库,而不是仅仅解码一个JWT。
https://stackoverflow.com/questions/50085654
复制相似问题