Я хочу выполнить вход в систему с помощью Spring Security, используя jquery ajax. вот что у меня есть в моем классе конфигурации безопасности:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private Environment env;
@Autowired
private UserSecurityService userSecurityService;
@Autowired
MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
@Autowired
MyAuthenticationFailureHandler myAuthenticationFailureHandler;
private static final String SALT = "salt";
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
}
private static final String[] PUBLIC_MATCHERS = {
"/webjars/**",
"/css/**",
"/js/**",
"/images/**",
"/",
"/about/**",
"/contact/**",
"/error/**/*",
"/console/**",
"/signup"
};
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().
antMatchers(PUBLIC_MATCHERS).
permitAll().anyRequest().authenticated();
http
.csrf().disable().cors().disable()
.formLogin().failureHandler(myAuthenticationFailureHandler).loginProcessingUrl("/login")
.successHandler(myAuthenticationSuccessHandler).loginPage("/index").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/index?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
}
}
MyAuthenticationSuccessHandler. java
@Component
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private Log log = LogFactory.getLog(MyAuthenticationSuccessHandler.class);
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// This is actually not an error, but an OK message. It is sent to avoid redirects.
response.sendError(HttpServletResponse.SC_OK);
}
}
MyAuthenticationFailureHandler.class
@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.sendError(401, "Authentication Failed: " + exception.getMessage());
}
}
, и это Форма, куда я отправляю запрос ajax:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="common/header :: common-header"/>
<body>
<!-- Login Section -->
<img class="img-responsive" src="/images/banner.png" alt="banner"/>
<div class="container">
<div class="row ">
<div class="main-center" id="main">
<div class="bg-danger" id="wrongPass" style="display: none">
Invalid username and secret.
</div>
<div class="bg-danger" th:if="${param.logout}">
You have been logged out.
</div>
<form id="loginForm" class="form-signin" th:action="@{/index}" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<div class="form-group">
<label for="username" class="sr-only">Username</label>
<input type="text" roleId="username" class="form-control" placeholder="Username" name="username"
id="username"
required="required" autofocus="autofocus"/>
</div>
<div class="form-group">
<label for="password" class="sr-only">Password</label>
<input type="password" roleId="inputPassword" class="form-control" placeholder="Password"
id="password"
name="password" required="required"/>
</div>
<div class="form-group">
<input type="checkbox" name="remember-me" id="remember-me"/> Remember me
</div>
<button id="signIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
<hr />
<div class="form-group ">
<a id="signUp" type="submit" class="btn btn-info btn-lg btn-block login-button" th:href="@{/signup}">Sign up!</a>
</div>
</div>
</div>
</div>
<div th:replace="common/header :: body-bottom-scripts"/>
<script>
$(document).ready(function() {
$('#signIn').on('click', function (e) {
debugger;
e.preventDefault();
$('#wrongPass').hide();
$.ajax({
url: "/j_spring_security_check",
type: 'POST',
beforeSend: function(xhr) {
xhr.withCredentials = true;
},
data:$('#loginForm').serialize()
}).success(function (response){
debugger;
console.log(response);
$('body').load('/userFront');
}).error(function (res, status){
debugger;
console.log(res);
$('#wrongPass').show()
});
});
})
</script>
</body>
</html>
, но он не работает вообще! и в логе консоли я получаю выше html как ответ!
мне нужно просто получить что-то вроде логического значения, чтобы указать, была ли аутентификация истинной или нет. и исходя из этого функция обратного вызова должна либо загрузить страницу userFront.html
, либо показать сообщение об ошибке.
я даже пытался использовать /index
в качестве ajax url, а также JSON.stringify({username:...,password:...})
в качестве json данных, но ни один из них не помогал!
любая помощь будет оценена, так как я действительно получил застрял!