-->

First Logging in is not required when using meteor

2019-08-23 02:58发布

问题:

I am using meteor restivus to create a rest api. The issue I have is that the api does not force me to login to do posts and gets My code is as follows:

Articles = new Mongo.Collection('articles');

if (Meteor.isServer) {

  // Global API configuration
  var Api = new Restivus({
    useDefaultAuth: true,
    authRequired: true,
    prettyJson: true,
	version:'v1'
  });
  
  Api.addCollection(Articles);
}

I did a POST using:

curl -X POST http://localhost:3000/api/v1/articles/ -d "title=Witty Title" -d "author=Jack Rose"

and I did a GET using

curl -X GET http://localhost:3000/api/v1/articles/

but I am not getting an error forcing me to first login before I can do the above POST and GET. My meteor app uses accounts-password and accounts-ui packages. What must I do to make the API to force me to login before I can do any POSTs or GETs.

回答1:

I managed to fix this. authRequired should have been included in addCollection as per the code below:

Articles = new Mongo.Collection('articles');

if (Meteor.isServer) {

  // Global API configuration
  var Api = new Restivus({
    useDefaultAuth: true,
    //authRequired: true,
    prettyJson: true,
    version:'v1'
  });
  
  Api.addCollection(Articles,{
		routeOptions: {
			authRequired: true
		}
  });
}

I was a bit of an idiot as this is in the docs. Not so clear but in the docs none the less. Hope this helps someone else though!

Just to add:

After logging in do a GET a per the docs

curl H "X-Auth-Token: etttttttt-BM2DyXsTe-Gybtttttttttttttttt3Reo" -H "X-User-Id: pwfy4viiiiiiiyz3Kp" http://localhost:3000/api/v1/articles/

and do a POST like this:

curl -X POST -H "X-Auth-Token: etttttttt-BM2DyXsTe-Gybtttttttttttttttt3Reo" -H "X-User-Id: pwfy4viiiiiiiyz3Kp" http://localhost:3000/api/v1/articles/ -d "title=Witty Title" -d "author=Jack Rose"