我正在构建一个Range2Web客户端,它试图使用SpringBoot安全性向服务器发送一个帖子。我应该如何编写Spring安全配置?
我对认证的要求是:
public login(username, password) {
let body = JSON.stringify({username: username, password: password});
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
this.http.post("http://localhost:8080/login", body, options)
.subscribe(
res => this.loggedIn = true,
err => console.error("failed authentication: " + err),
() => console.log("tried authentication")
);
}
身份验证失败,错误如下:
{“时间戳”:1487007177889,“状态”:401,“错误”:“未经授权”,“消息”:“身份验证失败:空用户名”,“路径”:“/login”}
我的春季安全配置:
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
@Autowired
private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
@Autowired
private RestAuthenticationFailureHandler restAuthenticationFailureHandler;
@Autowired
private RestLogoutSuccessHandler restLogoutSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and().formLogin()
.loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(restAuthenticationSuccessHandler)
.failureHandler(restAuthenticationFailureHandler)
.permitAll()
.and().logout()
.logoutUrl("/logout")
.logoutSuccessHandler(restLogoutSuccessHandler)
.permitAll()
.and().authorizeRequests().anyRequest().authenticated()
;
}
@Override
public void configure(AuthenticationManagerBuilder builder) throws Exception {
// This configuration has been tested, it works.
// It has been removed for better readability
}
@Bean
public LdapContextSource contextSource() {
// This configuration has been tested, it works.
// It has been removed for better readability
}
}
发布于 2017-02-13 18:18:39
您应该使用application/x-www-form-urlencoded
参数进行表单登录,而不是使用JSON。这就是为什么错误说用户名丢失了,因为Security试图从HttpServletRequest#getParameters获取用户名。若要以角度发送表单参数,您可以
import { URLSearchParams } from '@angular/http';
let params = new URLSearchParams();
params.set('username', username);
params.set('password', password);
如果将其设置为Http请求的主体参数,则应该自动将其序列化为正确的格式,即
username=xxx&password=xxx
我认为您也不需要将header Content-Type
设置为applicatio/x-www-form-urlencoded
。我认为,当角度检测到URLSearchParams
作为身体时,也应该为你设置。
https://stackoverflow.com/questions/42210128
复制相似问题