I'm using access_token handling logic form loopback. It works fine, but unfortunately expects the access_token in the URL.
Can I configure loopback to use the access_token in the header custom field instead?
Initialize Loopback Token Middleware
check the docs
A sample code for enabling loopback.token middleware
app.use(loopback.token({
cookies: ['access_token'],
headers: ['access_token', 'X-Access-Token'],
params: ['access_token']
//additional keys (check docs for more info)
}));
It checks for these values in cookies, headers, and query string parameters
Docs- https://loopback.io/doc/en/lb3/Making-authenticated-requests.html
Pass the following header in request config (use your token)-
headers: {
Authorization: '1vKbyJc9D2pJaE5sZWDqKxcJYlOfPab4eO8giuRMkfOxvoHKGUBRDcNvP4JwDIxe'
}
No configuration needed in server.
Related
Previously I was using django-rest-auth package and I was getting the auth token when user log in in response response.data.key and this auth token or key was working fine with the api calls as authentication auth
Previously for django-rest-auth:
"/rest-auth/login/"
was getting the response.data.key as auth token and that was working
I have stored in the cookie for later use
.get("/rest-auth/user/", {
headers: {
"Content-Type": "application/json",
Authorization: "Token " + response.data.key + "",
},
})
It was working to get info on user and also was working when used in other api calls by setting it in
Authorization: "Token " + response.data.key + ""
But now, I'm using dj-rest-auth package instead of django-rest-auth and shifted my urls to
/dj-rest-auth/login
and I'm not getting any key or auth token that I can use for authorization in header.
.get("/dj-rest-auth/user/", {
headers: {
"Content-Type": "application/json",
Authorization: "Token " + response.data.? + "",
},
})
It's not working because now I'm getting access_token , refresh_token and user info. I tried to use access_token and refresh_token for authorization in header but it's not working because I'm not getting key or auth token in response when user log in
Note: django-rest-auth is no more maintained and dj-rest-auth is forked from the previous one and have more functions (this is the reason why I'm switching)
How to get auth token or key by using dj-rest-auth package so that I can use it in the header of API calls for authorization?
Check that you don't have an REST_USE_JWT = True in your settings. That setting will enable JWT authentication scheme instead of a (default) token-based.
In django-rest-auth you get the key from a GET request, but according to dj-rest-auth's documentation, you get the token key as a response when you make a post request to /dj-rest-auth/login/.
When you make a POST request to /dj-rest-auth/login/, you can access the key at response.data. But now you need to store it so you can use it in your get requests.
I recommend checking out this question's answers to learn more about storing tokens. How you choose to do this will depend on how to the frontend of your application is built, as the javascript needs access to the token key.
I know I'm late to answer this, but hopefully I can help someone other folks who find this.
I am trying to build an application using VueJS and Django. I am also using Graphene-Django library, as the project utilize GraphQL.
Now, The authentication works fine and i get a JWT Token back.
But when i use the token for other queries that need authentication, i got this error in Vue:
"Error decoding signature"
and the Django Log also returns this:
graphql.error.located_error.GraphQLLocatedError: Error decoding signature
jwt.exceptions.DecodeError: Not enough segments
ValueError: not enough values to unpack (expected 2, got 1)
the bizarre thing is that the same query when executed in Postman just works fine.
As i mentioned in the title is use Axios for my requests, here's an example of a request:
axios({
method: "POST",
headers: { Authorization: "JWT " + localStorage.getItem("token") },
data: {
query: `{
dailyAppoint (today: "${today}") {
id
dateTime
}
}`
}
});
Note: It uses 'JWT' not 'Bearer' because somehow 'Bearer' didn't work for me.
Ok, couple of questions, does you API work without Vue.js from curl. Generate token, check API from curl.
If it does, then check the Headers sent from the request, from Network Inspector, mozilla dev tools/chrome devtools. And update your Post with those RAW Headers.
This particular error arises when your public key is unable to decode the string[token] signed by your private key. Which ultimately means the access token has been tampered with. It could also mean you're sending values like 'unkown'-- JS state initialization error.
Check the RAW headers of the request. It'll help.
Use a request interceptor to set the Authorization header:
axios.interceptors.request.use(config => {
if (localStorage.getItem("token") != null)
config.headers["Authorization"] = "JWT " + localStorage.getItem("token");
return config;
});
The HTTP_X_CSRFTOKEN header does not match what is inside the csrftoken cookie.
How can I examine the cookie? Set-Cookie is not displayed in the Response header for Cross Domain requests.
I have already followed instructions found in:
CSRF with Django, React+Redux using Axios
Interestingly I found "X-CSRFTOKEN" translates to "HTTP_X_CSRFTOKEN" on the server request header.
Works fine in the development env under localhost (although I am using 2 different ports - one for django and the other my frontend).
UPDATE:
It seems the csrktoken cookie is not correctly set for cross domain rquests (although the browser displays it in the Request Header) so the X-CSRFTOKEN does not get sent.
I ended up adding an API call to return the current csrftoken using a GET request and then sending it back using the X-CSRFTOKEN header.
You haven't mentioned how you're getting the csrftoken from the server in the first place, so I'm assuming it's already present in your browser.
Along with the X-CSRFToken header, also include the cookies in the request using withCredentials: true.
I'm using the js-cookie library to get the csrftoken from the cookies.
import Cookies from 'js-cookie';
axios({
url: 'http://localhost:8000/graphql',
method: 'post',
withCredentials: true,
data: {
query: `
{
// Your query here
}
`
},
headers: {
"X-CSRFToken": Cookies.get('csrftoken')
}
})
Also add CORS_ALLOW_CREDENTIALS = True to your settings.py, assuming you are using django-cors-headers. Otherwise, the cookies won't be accepted.
You will have to make the X-CSRFTOKEN header accessible via the CORS Access-Control-Expose-Headers directive. Example:
Access-Control-Expose-Headers: X-CSRFTOKEN
This header has to be set by your API or web server, so that the browser will see it during the CORS preflight request.
I am using ember vesrion 2.15.1 for my application. I am using ember-file-upload node module to support file upload and that is successful. Challenge is I am not able to add auth token to the request header. My request header looks like this:
I am not able to add userAuthToken in request header of file upload like below which I am able to add for other api calls:
I have tried uploading the file via
set(file, 'headers.userAuthToken', localStorage.getItem("userToken")); // this line is creating problems
let response = yield file.upload(url);
But unable to add userAuthToken in request header.
Any fix or workaround will be appreciated.
You can pass options as second parameter of upload method. One of possible options is headers. Something like this should work:
let response = yield file.upload(url, {
headers: {userAuthToken: localStorage.getItem("userToken")}
});
You can find other possible options here
You can add additional headers in application adapter, for example:
import ActiveModelAdapter from 'active-model-adapter';
var token = $('meta[name="csrf-token"]').attr('content');
export default ActiveModelAdapter.extend({
headers: {
"X-CSRF-Token": token
}
});
I have a very simple form that I've added the uploader to. When I invoke the uploader, django returns
{"detail":"CSRF Failed: CSRF token missing or incorrect."}
This is the uploader:
var ul = new Uploader(
{
label:"Programmed uploader",
multiple:false,
uploadOnSelect:true,
url:Environment.apiRoot + "upload/",
headers:{
"Accept" : "application/json",
"X-CSRFToken" : dojo.cookie("csrftoken")
}
}).placeAt(form);
I created simple "test" button that invokes a function that performs the same post.
new Button({
name:"Cancel2",
//id:"Cancel",
label:"Cancel" ,
placement:"secondary",
onClick:lang.hitch(this,function(event){
this._testpost()
})
}).placeAt(form);
This is the relavent header from the uploader post
Cookie djdt=hide; csrftoken=WwlARc9OUevblKfgNEDU2Ae4eT9z0kos;sessionid=du37rjyam6v69mw0bgctkbw708xlvc5g
This is the _testpost()
_testpost: function (){
xhr.post({
url: Environment.apiRoot + "upload/",
handleAs: "json",
postData: json.stringify(data),
headers: {
"Content-Type": "application/json",
"Accept" : "application/json",
"X-CSRFToken" : dojo.cookie("csrftoken")
},
loadingMessage: "Submitting form..."
}).then(
lang.hitch(this,function(result) {
form = t._f_form;
dojo.destroy(form);
this._float.destroyRecursive();
alert(result['result_text']);
result['message'] = "Update Request Accepted";
}),lang.hitch(this, function(err){
form = t._f_form;
dojo.destroy(form);
this._float.destroyRecursive();
topic.publish("/application/message","An error occurred.");
}));
this is the relevant header from invoking the _testpost function
Cookie djdt=hide; csrftoken=WwlARc9OUevblKfgNEDU2Ae4eT9z0kos;sessionid=du37rjyam6v69mw0bgctkbw708xlvc5g
X-CSRFToken WwlARc9OUevblKfgNEDU2Ae4eT9z0kos
The key difference being that in the _testpost the X-CSRFToken is put into the header, but on the Uploader post, I don't have any means to put in an X-CSRFToken (my headers attribute seems to just be ignored - i tried it to see if I could get this to work)
Is there any way to get additional headers into the Uploader
Unfortunately, dojox.form.Uploader does not allow headers to be added.
There are a couple options. It sounds like you have access to the csrf token and could append it to the url. Another option may be to provide the csrf token as a cookie and it should be sent with XHR and Flash request.
What I have done (and i'm not sure this is correct), within the django view, disabled csrf checking, and then pull the csrf value out of the header and compare it against the csrf value that is kept in the session record on the server.
you may use dojo.aspect to add the headers to the dojox.form.Uploader.
In case you are using HTML5 upload "plugin", that looks like since you have left the default, you may use something like:
aspect.after(ul, "createXhr", function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("X-CSRFToken", dojo.cookie("csrftoken"));
return xhr;
});
Add this just after you create the Uploader. Also remember to require dojo/aspect.
Notice that this is a bit of a hack and prone to breakage if some change happen in dojox.form.Uploader structure (e.g. they update it to use dojo.promise or other fixes). Also it's implied that this works only for HTML5 plugin, but you may extend the code in the same way to cope for other plugins by inspecting ul.uploadType and make the change specific for that plugin.
This solution works up to and including dojo version 1.12. In 2017 the above announced breakage did happen an this does not work anymore with version of dojo from 1.13 and upward.