hasura集成jwt
####1创建创建Auth0 App
https://manage.auth0.com
选择Single Page Web Applications
设置回调地址
Allowed Callback URLs: http://localhost:3000/callback
Allowed Web Origins: http://localhost:3000
2 创建jwt rule
名字::hasura-jwt-claim
function (user, context, callback) {
const namespace = "https://hasura.io/jwt/claims";
context.idToken[namespace] =
{
'x-hasura-default-role': 'user',
// do some custom logic to decide allowed roles
'x-hasura-allowed-roles': ['user'],
'x-hasura-user-id': user.user_id
};
callback(null, user, context);
}
3获得jwt-config
https://hasura.io/jwt-config
4设置环境变量
HASURA_GRAPHQL_ADMIN_SECRET: hasura的密码
HASURA_GRAPHQL_JWT_SECRET: {}获得的jwt-config
如果使用docker-compose,请用单引号把上面内容扩起来。'{}'
5创建Auth0 用户注册需要同步到 PostgreSQL 数据库中的rule
创建uers表
id, integer, auto-increment, primary
auth0_id, text, unique
email, text
created_at, timestamp
updated_at, timestamp
名字:sync user to hasura
function (user, context, callback) {
const userId = user.user_id;
const email=user.email;
const hasuraAdminSecret = "****";
const url = "http://ip:port/v1/graphql";
var myDate = new Date();
var created_at=myDate.toLocaleString( );
var updated_at=myDate.toLocaleString( );
const upsertUserQuery = `
mutation($userId: String!,$email: String!,$created_at: timestamptz!,$updated_at: timestamptz!){
insert_users(objects: [{ auth0_id: $userId,email: $email,created_at: $created_at ,updated_at:$updated_at}], on_conflict: { constraint: users_auth0_id_key, update_columns: [updated_at] }) {
affected_rows
}
}`;
const graphqlReq = { "query": upsertUserQuery, "variables": { "userId": userId,"email": email,"created_at":created_at,"updated_at":updated_at} };
request.post({
headers: {'content-type' : 'application/json', 'x-hasura-admin-secret': hasuraAdminSecret},
url: url,
body: JSON.stringify(graphqlReq)
}, function(error, response, body){
console.log(body);
callback(null, user, context);
});
}
6 test
请求地址:
https://domain.auth0.com/login?client=clientid&protocol=oauth2&response_type=token%20id_token&redirect_uri=http://localhost:3000/callback&scope=openid%20profile
注:domain为App的域名;clientid为App的clientid;http://localhost:3000/callback为设置的回调地址
完成登陆后回到设置的回调地址,url参数中中会带token
如http://localhost:3000/callback#access_token=*******
然后请求头加上token
Authorization:Bearer +token
来源:CSDN
作者:weixin_45876565
链接:https://blog.csdn.net/weixin_45876565/article/details/104580197