spring boot和reactjs的前端工作得很好,直到我添加安全的后端



spring boot和reactjs的前端工作得很好,直到我添加安全后端,它停止在浏览器中显示我下面的信息。

static {
todos.add(new Todo(++idCounter, "user1", "learn  react", new Date(), false));
todos.add(new Todo(++idCounter, "user1", " fullstack developer", new Date(), false));
todos.add(new Todo(++idCounter, "user1", "software developer", new Date(), false));
}

我得到的错误是:

xhr.js:177 GET http://localhost:8080/users/user1/todos 401

这是前端:

import axios from "axios"
class HelloWorldService{
executeHelloWolrdService(){
return axios.get('http://localhost:8080/hello-world')

}
executeHelloWolrdServiceBean(){
return axios.get('http://localhost:8080/hello-world-bean')

}
executeHelloWolrdServicePathVariable(name){
let username = 'user1'
let password = 123
let basicAuthHeader ='Basic ' + window.btoa(username+ ':' +password);


return axios.get(`http://localhost:8080/hello-world/path-variable/${name}`, 
{
headers : {
authorization: basicAuthHeader

}
}   
);  
}
}
export default new HelloWorldService()

最后是我的安全类:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception{

http

.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()

.anyRequest().authenticated()
.and()
//.formLogin().and()
.httpBasic();



}
}

更新:

确实有效,非常感谢!

你能告诉我如何使这些下面的代码与你的代码工作吗?当我把它们放在一起时,它确实起作用了:

.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()

.anyRequest().authenticated()
.and()
//.formLogin().and()
.httpBasic();

需要添加关于认证类型的配置:

public class ServiceConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.httpBasic();
}
} 

最新更新