I'm developing one application in which I integrated Spring Security successfully and I'm able to login/logout and authorise user based on role.
Now, in same application when I trigger some AJAX GET
request; it redirects request to login page and return my login page HTML page as response. I understand that my AJAX request is not being authenticated by Spring Security.
Now my question is, how can I trigger authenticated AJAX request so that I can get proper response instead of login page as response?
I've configured Spring Security as below:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/register").permitAll()
.antMatchers("/forgetPassword").permitAll()
.antMatchers("/resetPassword").permitAll()
.antMatchers("/changePassword").permitAll()
.antMatchers("/error/*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.defaultSuccessUrl("/index")
.failureUrl("/login?error=true")
.and()
.exceptionHandling()
.accessDeniedPage("/error/403")
.and()
.logout()
.invalidateHttpSession(true)
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login");
}
Update: Here are my request headers as asked.
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:optimizelyEndUserId=oeu1496834101340r0.5246134202334098; Idea-6adc618e=45c8074c-a056-43bd-a6bd-2b8e7545231f; optimizelySegments=%7B%223910210135%22%3A%22gc%22%2C%223921780062%22%3A%22direct%22%2C%223922680052%22%3A%22false%22%7D; optimizelyBuckets=%7B%7D; _ga=GA1.1.304304118.1496834102
Host:localhost:8080
Referer:http://localhost:8080/QuickBill/invoice/new
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
X-Requested-With:XMLHttpRequest
Response header for any request after successful login
Cache-Control:no-cache, no-store, must-revalidate
Content-Language:en-US
Content-Type:text/html;charset=ISO-8859-1
Date:Sat, 29 Jul 2017 06:56:07 GMT
Expires:Thu, 01 Jan 1970 00:00:00 GMT
Pragma:no-cache
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Here is my ajax request code snippet:
$.ajax({
url: 'url?clientId='+clientId,
xhrFields: {
withCredentials: true
}
}).done(function(err, data){
console.log(data);
console.log(err);
})
}