I am trying to make an email check for uniqueness. The request is sent via AJAX. And i get 302 error (and i can see this error in browser). I think that my Spring-security does not permit for request and trying redirect to the login-page (when i authorized, i get same error 302). Why I get 302 error if i permit this request checkUserEmail?
Here AJAX-request
$("#userLogin").click(function (event)
{
event.preventDefault();
var inputValue = document.getElementById("userLogin");
inputValue.addEventListener("input", function (e)
{
var request =
{
query: inputValue.value
};
$.ajax(
{
type: "POST",
contentType: "application/json",
url: "checkUserEmail",
data: JSON.stringify(request),
dataType: 'json',
cache: false,
timeout: 600000,
success: function(response)
{
if (!response)
{
alert("This email '" + inputValue.value + "' is already in use.");
inputValue.value = "";
}
},
error: function(err)
{
console.log(err);
}
});
})
});
Here Spring Controller
@RequestMapping(value = { "/checkUserEmail" }, method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Object> checkUserEmail(@RequestBody AjaxRequest request)
{
AD_User currentUser = userService.getCurrentAuthorizeUser();
String userEmail = request.getQuery().toLowerCase();
boolean result = true;
if (userEmail != null && !userEmail.isEmpty())
{
if (currentUser == null || !userEmail.equals(currentUser.getEmail()))
{
result = userService.getUserByEmail(userEmail).isEmpty();
}
}
return new ResponseEntity<Object>(result, HttpStatus.OK);
}
Here Spring security (in this code i'm trying disable csrf, but it does not work
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
private final UserDetailsService userDetailsService;
@Autowired
public SecurityConfig(@Qualifier("userDetailsServiceImpl") UserDetailsService userDetailsService)
{
this.userDetailsService = userDetailsService;
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.antMatchers("/",
"/about",
"/getEventsByCity",
"/sortEvents",
"/buyService",
"/checkUserPhone",
"/getAllTags",
"/getAllSpecialisations",
"/checkUserEmail",
"/forgotPassword",
"/restorePassword",
"/404",
"/filterSearchEvents",
"/500",
"/about",
"/eventCatalog",
"/createEvent",
"/eventStatic/**",
"/activateAccount/**",
"/events/**/**",
"**/checkUserPhone",
"/serviceCatalog",
"/service/**/**",
"/createService**",
"/createService",
"/robots.txt",
"/error",
"/authorized")
.permitAll()
.antMatchers("/resources/**", "/ts/**", "/fonts/**", "/img/**", "/json/**", "/text/**", "/video/**", "/static/**", "/home/dru/uploads/**",
"data:image/**", "/images/**", "/php/**",
"/sections/**", "/css/**", "/js/**", "/static/error/**", "/", "C:/home/phantomjs-2.1.1-windows/bin/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/authorized").permitAll()
.failureUrl("/failure")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", HttpMethod.GET.name()))
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSIONID")
.and()
.csrf().disable().cors();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
protected DaoAuthenticationProvider daoAuthenticationProvider()
{
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(SecurityMechanism.passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
return daoAuthenticationProvider;
}
}
Here my application.properties (i hide password and some settings in this file by "*")
spring.datasource.url=jdbc:postgresql://localhost:5432/attraction
spring.datasource.username=***
spring.datasource.password=***
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=***
spring.mail.password=***
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
hostname=***
upload.path=***
server.error.whitelabel.enable=true
spring.mvn.throw-exception-if-no-handler-found=true
And at this sreenshot it is my error when i'll trying send AJAX-request (in Java i did not take any error). As you can see First i get 302 error
This is my Exception controller
@Controller
public class ExceptionController
{
private static final Logger LOG = LoggerFactory.getLogger(ExceptionController.class);
@Autowired
private UserService userService;
@GetMapping("/failure")
public ModelAndView getFailurePage(HttpServletRequest servletRequest, HttpServletResponse servletResponse, ModelMap model)
{
userService.getCurrentAuthorizeUser();
HttpSession httpSession = servletRequest.getSession(false);
if (httpSession != null)
{
AuthenticationException ex = (AuthenticationException) httpSession.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
if (ex != null)
{
model.addAttribute("showLoginForm", "login");
model.addAttribute("exceptionMessage", "Bad credentials");
return new ModelAndView("authorized", model);
}
}
return new ModelAndView("redirect:/error/" + ErrorPages.INTERNAL_SERVER_ERROR_500, model);
}
@GetMapping("/error")
public RedirectView getErrorPage(RedirectAttributes attr, HttpServletResponse servletResponse)
{
AD_User currentUser = userService.getCurrentAuthorizeUser();
attr.addFlashAttribute("flashAttribute", currentUser);
if (servletResponse.getStatus() == 404)
{
return new RedirectView("/error/" + ErrorPages.NOT_FOUND_PAGE_404);
}
return new RedirectView("/error/" + ErrorPages.INTERNAL_SERVER_ERROR_500);
}
}
This is my Exception Handler
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionHandlerFilter extends GenericFilterBean
{
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException
{
try
{
chain.doFilter(req, res);
}
catch (RequestRejectedException e)
{
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}
What prevents me from sending an AJAX request?
I tried disabling csrf, but it didn't help. I also tried with sef enabled to transmit with the _csrf.token request in the AJAX request header, but there was a 403 error.