大家好!
我遇到了实现此功能的麻烦。 我按照这篇文章中的所有步骤Spring Security and JSON Authentication阅读了该帖子上的所有链接。这是我想要实现的确切行为,但我一直在接受
用户名=名为myUsername&安培;密码=为mypass
我错过了什么?
我真的很擅长整个网络世界的事情!如果你有任何提示或者至少告诉我应该寻找什么。
这是我的配置类:
@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailsService")
private UserDetailsService userDetailsService;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService);
authenticationManagerBuilder.authenticationProvider(customAuthenticationProvider());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public CustomDaoAuthenticationProvider customAuthenticationProvider() {
CustomDaoAuthenticationProvider customAuthenticationProvider = new CustomDaoAuthenticationProvider();
customAuthenticationProvider.setUserDetailsService(userDetailsService);
customAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return customAuthenticationProvider;
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public Http403ForbiddenEntryPoint http403ForbiddenEntryPoint(){
return new Http403ForbiddenEntryPoint();
}
@Bean
public CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler(){
CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler = new CustomAuthenticationSuccessHandler();
customAuthenticationSuccessHandler.setDefaultTargetUrl("/signin.html");
customAuthenticationSuccessHandler.setTargetUrlParameter("/home.html");
return customAuthenticationSuccessHandler;
}
@Bean
public CustomAuthenticationFailureHandler customAuthenticationFailureHandler(){
CustomAuthenticationFailureHandler customAuthenticationFailureHandler = new CustomAuthenticationFailureHandler();
customAuthenticationFailureHandler.setDefaultFailureUrl("/signin.html");
return customAuthenticationFailureHandler;
}
@Bean
public CustomLogoutSuccessHandler customLogoutSuccessHandler(){
CustomLogoutSuccessHandler customLogoutSuccessHandler = new CustomLogoutSuccessHandler();
return customLogoutSuccessHandler;
}
@Bean
public CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter() {
try {
CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter = new CustomUsernamePasswordAuthenticationFilter();
customUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
customUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler());
customUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler());
customUsernamePasswordAuthenticationFilter.setFilterProcessesUrl("/j_spring_security_check");
customUsernamePasswordAuthenticationFilter.setUsernameParameter("username");
customUsernamePasswordAuthenticationFilter.setPasswordParameter("password");
return customUsernamePasswordAuthenticationFilter;
} catch (Exception e) {
return null;
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/signin.html**").permitAll()
.antMatchers("/**").authenticated()
.and().addFilterBefore(new CustomUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.logout().permitAll().logoutSuccessUrl("/signin.html").deleteCookies("JSESSIONID").invalidateHttpSession(true).logoutSuccessHandler(customLogoutSuccessHandler())
.and().exceptionHandling().authenticationEntryPoint(http403ForbiddenEntryPoint())
.and().csrf().disable();
}
}
这是我的过滤器
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
if ("application/json".equals(request.getHeader("Content-Type"))) {
StringBuffer sb = new StringBuffer();
String line = null;
LoginRequest user = new LoginRequest();
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String fromBuffer = sb.toString();
//fromBuffer is reading username=myUsername&password=myPass
ObjectMapper mapper = new ObjectMapper();
user = mapper.readValue(fromBuffer, LoginRequest.class);
} catch (Exception e) {}
UsernamePasswordAuthenticationToken authenticationRequest = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getPassword());
setDetails(request, authenticationRequest);
return super.attemptAuthentication(request, response);
} else {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
}
}
以下是我如何调用我的登录服务
function doLogin(){
clearErrorMsg("login-alert");
var data = new Object();
data.username = $('#username').val();
data.username = $('#password').val();
$.ajax({
data: data,
timeout: ajaxTimeout,
type: 'POST',
url: rootURL +'/login',
contentType: "application/json"
}).done(function(data, textStatus, jqXHR) {
window.location.href = rootURL + "/home.html";
}).fail(function(jqXHR, textStatus, errorThrown) {
displayErrorMsg("login-alert", "Wrong credentials, try again! <br >Error code: [" + errorThrown + "]");
});
}
很抱歉这篇长篇文章,感谢您提供的任何帮助! 也许代码有点乱,但我一直在尝试我找到的每个解决方案,没有一个对我有用。
答案 0 :(得分:0)
你一直在接收
username=myUsername&password=myPass.
因为javascript代码中有一些错误。你应该在ajax请求中将数据编码为json字符串( JSON.stringify(data))
完整示例
function doLogin(){
clearErrorMsg("login-alert");
var data = new Object();
data.username = $('#username').val();
data.username = $('#password').val();
$.ajax({
data: JSON.stringify(data),
timeout: ajaxTimeout,
type: 'POST',
url: rootURL +'/login',
contentType: "application/json"
}).done(function(data, textStatus, jqXHR) {
window.location.href = rootURL + "/home.html";
}).fail(function(jqXHR, textStatus, errorThrown) {
displayErrorMsg("login-alert", "Wrong credentials, try again! <br >Error code: [" + errorThrown + "]");
});
}