Spring security, thymeleaf and cookie - spring-boot

Actually, I use spring boot, thymeleaf and spring security.
Security is splitted in two in the application.
One for mvc and other one for rest call.
I search a way if login is ok to create a cookie with login/password to be able to do add header to every ajax call.
headers: {
"Authorization": "Basic " + $.cookie('cookie-authorization')
},
So i search to create a cookie if login success
Edit is it possible do to it on the server side?

You can use this code from the official doc to include the tokens in all your Ajax calls.
$(function() {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
})
Hope this helps.

Related

Axios JWT doesn't send

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.

POST request doesn't get response from server in chrome but work in postman

I'am making a POST request to spring boot endpoint and wanna get data return from server.With testing my API in Postman,it works good.but when testing it in
chrome,it doesn't even get a response and chrome NETWORK bar even did't have record.
so code is simple,I can't find any problem,RestController
#PostMapping("/signup")
public User signup(#RequestBody ModelUser user){
//fetch data from DTO and craft a user
User userData=user.adapter();
//...code here omit for sake of brevity
return userData;
}
it indeed get data from ajax,when I use logger(slf4j) to debug.
and ajax:
$("#sign-up").submit(function () {
var userInfo={}
userInfo["phone"]=$("#phone").val()
userInfo["password"]=$("#password").val()
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
}).then(
function(){
//this doesn't print in console
console.log("Hello Callback is executed")
}
)
})
weird as it is,I never encounter this when I use GET request,since ajax callback is successfully called when I use GET to test a GetMapping endpoint.
oh,with lots of similar questions
AJAX POST request working in POSTMAN but not in Chrome
Angular 4 POST call to php API fails, but GET request work and POST requests work from Postman
POST response arrives in Postman, but not via Ajax?
I don't get any response status code in chrome and completely not involved CORS in question
Have you tried adding a consumes and produces media type of Json in the Java
#PostMapping(path="/signup", consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
And explicitly set the Accept header in the javascript
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
headers: {Accept : "application/json"},
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
})
I'am sorry for my poor front end skill,the main reason is that I don't understand Javascript event.
$("#sign-up").submit(function (e) {
//e.preventDefault();
var user={};
user["phone"]="187308";
user["name"]="icywater";
$.ajax({
type:'POST',
contentType:'application/json',
data:JSON.stringify(user),
url:"http://localhost:8080/test"
}).done(function(data){
console.log("Hello Callback is executed");
console.log(data)
});
});
here when I click submit It actually already submit the form and don't wait ajax code to be executed,so I should use e.preventDefault()to suppress default behavior.It's nothing
related about POST or postman ,it is about the form submit default behavior,ahh,Oolong event.
I got it when I found this page

Adding the application autehntication to Swagger UI

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>

Ionic 2 ASP APi token request

I'm Trying to retrieve a bearer token from my ASP API from my ionic2 app.
I have enabled CORS on the API as shown below:
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
This enabled me to form a POST request from my ionic 2 app to my API in order to register a user. This works wonderfully.
The request I used for this is as shown below:
let headers = new Headers({
'Content-Type': 'application/json'
});
let options = new RequestOptions({
headers: headers
});
let body = JSON.stringify({
Email: credentials.email,
Password: credentials.password,
ConfirmPassword: credentials.confirmPassword
});
return this.http.post('http://localhost:34417/api/Account/Register', body, options)
However when I try to retrieve a token from my API I receive the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
The request I'm using to try and retrieve the token is as follows:
let body = "grant_type=password" + "&userName=" + credentials.email + "&password=" + credentials.password;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:34417/token', body, options)
This is the only request that is throwing this error, all other requests to my API work fine.
Have I missed anything, or am I doing something wrong?
var cors = new EnableCorsAttribute("*", "*", "*");
Looks like you are setting Access-Control-Allow-Origin as *.
Check MDN CORS Requests with credentials.
Credentialed requests and wildcards
When responding to a credentialed request, the server must specify an
origin in the value of the Access-Control-Allow-Origin header, instead
of specifying the "*" wildcard.
You will have to set a specific url if you use credentials.
Or if you only intend to use only for ionic 2, you could avoid the cors issue by setting a proxy.
According to the official blog:
The proxies settings contain two things: the path you use to access them on your local Ionic server, and the proxyUrl you’d ultimately like to reach from the API call.
{
"name": "ionic-2-app",
"app_id": "my_id",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://localhost:34417/api"
}
]
}
Ionic serve command by default will start server on localhost:8100.
The set proxy will hit your http://localhost:34417/api.
Your path in the requests will be to the localhost:8100/api instead of your actual server.

Rest API call fails with status 302 (spring security, html5)

I'm having 2 projects:
1) Restful Project with jdbc spring security (username:password) => port:9091
2) HTML5 Application with a JQGrid => port:9092
I have disabled csrf token in both the projects. Now, I'm able to hit the rest service successfully from browser and using postman and by passing the credentials
But when I try to hit the service from HTML5 Application (Jqgrid), I'm see that XHR Call is ending with status 302 and I'm not getting the results back.
So, please guide me on the same.
Additional Points:
I'm able to successfully hit the rest service from postman by passing basic authentication. But from JQGrid, I'm not able to query data even after using below code in my JQGrid. It always goes to status 302. (An FYI, I'm using stateless authentication in my spring security) :
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", CURRENT_AUTH_KEY);
},
beforeSend: function (request)
{
request.withCredentials = true;
request.setRequestHeader("Authorization", CURRENT_AUTH_KEY);
},
ajaxEditOptions: {
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", CURRENT_AUTH_KEY);
}
},
ajaxGridOptions: { Authorization: CURRENT_AUTH_KEY } ,

Resources