Relayjs Graphql user authentication

江枫思渺然 提交于 2019-12-06 22:54:19

问题


Is it possible to authenticate users with different roles solely trough a graphql server in combination with relay & react?

I looked around, and couldn't find much info about this topic.

In my current setup, the login features with different roles, are still going trough a traditional REST API... ('secured' with json web tokens).


回答1:


I did it in one of my app, basically you just need a User Interface, this one return null on the first root query if nobody is logged in, and you can then update it with a login mutation passing in the credentials. The main problem is to get cookies or session inside the post relay request since it does'nt handle the cookie field in the request.

Here is my client mutation:

 export default class LoginMutation extends Relay.Mutation {
  static fragments = {
    user: () => Relay.QL`
      fragment on User {
        id,
        mail
      }
    `,
  };
  getMutation() {
    return Relay.QL`mutation{Login}`;
  }

  getVariables() {
    return {
      mail: this.props.credentials.pseudo,
      password: this.props.credentials.password,
    };
  }
  getConfigs() {
    return [{
      type: 'FIELDS_CHANGE',
      fieldIDs: {
        user: this.props.user.id,
      }
    }];
  }
  getOptimisticResponse() {
    return {
      mail: this.props.credentials.pseudo,
    };
  }
  getFatQuery() {
    return Relay.QL`
    fragment on LoginPayload {
      user {
        userID,
        mail
      }
    }
    `;
  }
}

and here is my schema side mutation

var LoginMutation = mutationWithClientMutationId({
  name: 'Login',
  inputFields: {
    mail: {
      type: new GraphQLNonNull(GraphQLString)
    },
    password: {
      type: new GraphQLNonNull(GraphQLString)
    }
  },
  outputFields: {
    user: {
      type: GraphQLUser,
      resolve: (newUser) => newUser
    }
  },
  mutateAndGetPayload: (credentials, {
    rootValue
  }) => co(function*() {
    var newUser = yield getUserByCredentials(credentials, rootValue);
    console.log('schema:loginmutation');
    delete newUser.id;
    return newUser;
  })
});

to keep my users logged through page refresh I send my own request and fill it with a cookie field... This is for now the only way to make it work...



来源:https://stackoverflow.com/questions/33053617/relayjs-graphql-user-authentication

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!