向spring安全登录发送ajax请求



我想使用jquery ajax对spring安全性进行登录操作。这是我的安全配置类中的内容:

@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"/> &nbsp; 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作为响应!

我只需要得到一个类似布尔值的值来指示身份验证是否为真。并且基于此,回叫功能应当加载CCD_ 1页面或者显示错误消息。

我甚至尝试过将/index作为ajax url,将JSON.stringify({username:...,password:...})作为json数据,但都没有帮助!

任何帮助都将不胜感激,因为我真的陷入了困境!

非常愚蠢的错误家伙!在SecurityConfig类中,无论loginProcessingUrl是什么,ajax请求都应该发送到该url。因此,例如,如果loginProcessingUrl"/loginUrl",您只需要简单地将ajax url更改为"/loginUrl"。

就是这样。这是因为我试图阅读SO中的许多文章来找到我的解决方案,但几乎没有一篇文章能完全解释这个解决方案。

我不知道为什么有些人会花这么多时间阅读问题并回答问题,但却没有考虑到询问者可能是初学者这一事实,而大多数情况下都是初学者。所以他们有一些预先假设,会导致这些情况。

大多数时候问题都很容易解决,只是解释不够得体!!能够正确而严谨地解释是一项主要技能!

最新更新