【发布时间】:2019-10-01 17:50:50
【问题描述】:
我尝试使用 spring security 基本授权。当我从 Angular 发出发布请求时,spring 无法识别“用户名”和“密码”属性。当我向邮递员发出邮寄请求时,它可以工作。我不知道问题出在弹簧配置还是角度请求上。
我已经尝试了许多发布请求的配置,但没有任何效果。
这是我的 spring 安全配置:
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("a").password("a").roles("*");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().
csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/users").permitAll()
.anyRequest().authenticated()
.and().formLogin().and().httpBasic();
}
我最新的角度发布请求:
constructor(private httpClient: HttpClient) {}
handleLogin(user: UserDto) {
let headers = new HttpHeaders({
'Authorization': 'Basic ' + btoa('a' + ':' + 'a'),
'X-Requested-With': 'XMLHttpRequest'
});
this.httpClient
.post("//localhost:8080/login" ,{}, {headers}).subscribe(x=> {console.log(x)});
}
这是spring安全检查凭证和结果为空的地方
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (this.postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} else {
String username = this.obtainUsername(request); //null
String password = this.obtainPassword(request); //null
当我从邮递员授权工作发出帖子请求时,我希望有人可以帮助我通过角度请求获得语义结果。
-----------编辑---------- 正如评论中所建议的,我尝试了这个,但仍然是同样的问题。
let options = { headers: headers };
this.httpClient
.post("//localhost:8080/login", {}, options).subscribe(x => { console.log(x) });
谢谢
【问题讨论】:
-
您想使用 HTTP 基本登录还是表单登录?我猜您不想要表单登录,因此您应该删除表单登录配置或至少调用另一个 URL(
/login仅用于表单登录,不支持 HTTP 基本)。
标签: angular spring-security authorization