I have a project divided in two layers. The back-end is developed in spring boot, secured by Sprint security and JWT, and the front-end is developed in Vue.js, using Axios library for communication between layers.
I receive the "Bearer token" authentication properly, and all the authentication process is done correctly. The issue appears when I try to send a request with a token header to access content but the token doesn't send, and the Spring boot returns null without the content.
Here is the code
getOffers: function () {
if (localStorage.getItem("userSession")) {
this.aux = JSON.parse(localStorage.getItem("userSession"));
this.token = this.aux.token;
this.tokenHeader = "Bearer "+this.token;
alert(this.tokenHeader)
};
console.log(`Bearer ${this.token}`)
axios.
get('http://localhost:8080/api/v1/offer', {'Authorization' : `Bearer ${this.token}`})
.then(response => {
console.log(response);
this.offers = response.data
}).catch(e => console.log(e))
}
P.S: When I make a request in Postman, it works fine and returns the desired object. Here is a postman example:
postman
Correct way to pass header is :
axios.get(uri, { headers: { "header1": "value1", "header2": "value2" } })
In your case try this:
axios.get('http://localhost:8080/api/v1/offer', { headers:{Authorization : `Bearer ${this.token}`} })
Also, check in console if this gives correct Bearer token:
console.log(`Bearer ${this.token}`)
Register the Bearer Token as a common header with Axios so that all outgoing HTTP requests automatically have it attached.
window.axios = require('axios')
let bearer = window.localStorage['auth_token']
if (bearer) {`enter code here`
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + bearer
}
And no need to send bearer token on every request.
Related
I have Spring boot app where I integrate JWT authentication.
In order to authenticate, user need to send a POST request to /login with username and password, then he gets a JSON response with {"token": "BEARER SOME_TOKEN" }.
In my swagger UI, when I click "Try it out" and execute a request, the request is being sent without any token.
Question - Is there any way to query a login request and add authorization token to the Swagger UI requests?
In this case we can intercept the tokens and add them to all the requests by using these two interceptors in the index.html when defining SwaggerUIBundle:
const ui = SwaggerUIBundle({
...
responseInterceptor:
function (response) {
if (response.obj.access_token) {
console.log(response.obj.access_token)
const token = response.obj.access_token;
localStorage.setItem("token", token)
}
return response;
},
requestInterceptor:
function (request) {
request.headers.Authorization = "Bearer " + localStorage.getItem("token");
return request;
}
}
The responseInterceptor captures the response and if it contains the field "token" it saves it in local storage.
The requestInterceptor adds the Authorization header on each call you make from swagger-ui using the value from local storage.
This fix is for using v3 of swagger-ui:
<script src="https://unpkg.com/swagger-ui-dist#3.12.1/swagger-ui-standalone-preset.js"></script>
<script src="https://unpkg.com/swagger-ui-dist#3.12.1/swagger-ui-bundle.js"></script>
According to the Django docs, Django should have csrf token validation enabled by default, using a middleware. When I look in my settings file I indeed see the middleware being included.
However, when I do a post request without a csrf token using Ajax, Django will just allow it. Should it not return an error saying the csrf token is invalid? I am seeing a lot of questions from people who can't get their csrf token validated, but I can't get it INvalidated.
This is my Ajax post function (I collect the data from my inputs with js, and pass it to this function):
function ajaxPost(url, data, success) {
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(res => res.json())
.then(response => {
if (response.status !== success) {
//errors
}
updateView(response);
})
.catch(error => console.error('Error:', error))
}
And this is my view function:
#api_view(['POST'])
# API endpoint for posting bulk properties
def bulk(request):
new_properties = []
if request.method == 'POST':
for obj in request.data:
discipline = Discipline.objects.get(pk=obj['discipline.id'])
root_function = Function.objects.get(pk=obj['root_function'])
new_property = Property(name=obj['name'], value=obj['value'], unit=obj['unit'],
discipline_id=discipline)
new_property.save()
new_property.function.add(root_function)
new_properties.append(new_property)
new_properties = json.loads(serializers.serialize('json', new_properties))
return JsonResponse({'status': 201, 'new_properties': new_properties})
Assuming api_view is the one from django-rest-framework, it disables CSRF protection for that view.
This is because API endpoints are frequently used for external requests that won't have a CSRF token; there's no point checking for it in these cases.
I'm trying to send a post request from a vuejs app to a spring backend with which I'm attaching a jwt authorization header.
I have tried with vue-resource
Vue.http.headers.common['Authorization'] = 'Bearer YXBpOnBhc3N3b3Jk';
and the backend headers are like this
{accept-language=en-US,en;q=0.5, origin=http://localhost:8080, host=127.0.0.1:8084, access-control-request-headers=authorization, connection=keep-alive,...
But if i use postman to send the same request, the backend headers are like this
{authorization=Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1OTBhYWFmMjRhNjQ3ZjRiYmZlMDBhMDQiLCJzdWIiOiJiYmIiLCJpYXQiOjE0OTM5NzUxMDQsInJvbGVzIjoidXNlciIsImV4cCI6MTQ5Mzk3NTQ2NH0.kldUh3H1i3xEiNcxQ2ecq1HsjIIF5BI8Q-tb3sALc3E, content-length=0, accept-language=en-US,en;q=0.8,.......
My question is, how can i achieve the postman header using vuejs. I have tried with axios as well but without success.
Try this way with axios. I'm using spring backend too and it works..
axios.post(
url,
query ,
{headers: {
"header name" : "header value"
}}
)
.then((response) => {
var response = response.data;
}, (error) => {
var error = error.response;
}
}
)
I'm trying to consume the WP Rest API with Nativescript.
The WP API and the Authorization with OAUTH1 is already well setup and tested with POSTMAN.
Nativescript Login function to consume rest is already setup too and work without OAUTH.
Now I'm trying to Login with OAUTH here the code :
authorizationString = 'OAuth oauth_consumer_key="T2yXcbN28Ufj",
oauth_token="AmEVr5oSNmbKyZKccFjtmnSk",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1492267438",
oauth_nonce="rGFJG2",
oauth_version="1.0",
oauth_signature="Ru%2BaSvsZn2liesd2ENy8GeNsdHY%3D"';
login(user: User){
console.log("Try to login User : " + user.email);
let headers = new Headers({"Authorization": authorizationString});
let body = JSON.stringify({
username: user.username,
email: user.email,
password: user.password
});
headers.append("Content-Type", this.contentType);
return this.http.post(
this.api,
body,
{headers: headers}
)
.map( response => response.json() )
.do(data => {
//Do work!!
})
.catch(this.handleErrors);
}
But i got an error, this error means the autorization is not well formatted or sent :
"data": {
"code": "rest_cannot_access",
"message": "Only authenticated users can access the REST API.",
"data": {
"status": 401
}
}
How to properly use oauth1 with Nativescript?
I just switched to OAUTH2 by using a opensource plugin :
https://github.com/wlcdesigns/WP-OAuth2-Server-Client
and it's more easy to use with the authorization : Bearer
I'm using Koa JS framework for jwt authentication.
So basically when the user signs in, I set a jwt token (signed) to user's browser cookie, which seems to work fine as shown below (Chrome cookie settings):
(www.localhost.com instead of localhost is because I edited my hostfile, but this should have no effect in setting/getting cookies)
The problem, however, is when I send a POST request to my local Koa server, the jwt cookie is undefined. All I'm doing to verify the token is this:
routes.js
const Router = require("koa-router");
const router = new Router();
router.post(`api/authenticate`, function* () {
const jwt = this.cookies.get("jwt", { signed: true }); //jwt is undefined!!
if (!jwt)
this.throw("Invalid or expired token!");
this.status = 200;
});
//...
app.use(router.routes());
app.use(router.allowedMethods());
Here, this.cookies.get("jwt") returns undefined. The POST request is sent using AXIOS library with "withCredentials: true" header and a valid CSRF token:
authenticate.js
axios.post("api/authenticate", {}, {
headers: {
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": "A VALID CSRF TOKEN GENERATED BY SERVER",
"Content-Type": "application/json",
},
withCredentials: true,
});
Can anyone help me find out why this.cookies.get fails to fetch cookie from a simple POST request? I'm simply posting to my localhost, so I believe this is not a CORS problem.
What is more strange is that when I check my chrome developer tool, the "jwt" and "jwt.sig" tokens are successfully included in the request header..
Any help would be appreciated.
Update: Setting the cookie
//...
this.cookies.set("jwt", "SOME JWT GENERATED BY SERVER", {
httpOnly: true,
signed: true,
});
//...