Spring Boot REST API后端和基本身份验证-从Angular 10前端调用REST API
Spring Boot REST API后端和基本身份验证-从Angular 10前端调用REST API,angular,spring-boot,spring-security,Angular,Spring Boot,Spring Security,springboot2.3.4REST控制器和springsecurity基本身份验证(默认行为,只需添加依赖项) 现在我的Angular 10REST API调用工作了(使用ng new创建后,默认组件app.component.ts): 构造函数(私有http:HttpClient){ this.http.get('http://localhost:8081/resource') .订阅(结果=>{ 控制台日志(结果); } ); } 使用http://localhost:4200甚至当A
springboot2.3.4
REST控制器和springsecurity
基本身份验证(默认行为,只需添加依赖项)
现在我的Angular 10
REST API调用工作了(使用ng new
创建后,默认组件app.component.ts
):
构造函数(私有http:HttpClient){
this.http.get('http://localhost:8081/resource')
.订阅(结果=>{
控制台日志(结果);
}
);
}
使用http://localhost:4200
甚至当Angular应用程序在Tomcat中运行时,http://localhost:8080/
没有CORS
错误,其余调用正常,我收回了资源
但是现在没有Spring-Security
default-basic-authentication在后端运行,它看起来像是因为上面提到的配置类而被删除了
添加Spring-Security
依赖项将带来基本的身份验证。访问后端,例如使用http://localhost:8081
或http://localhost:8081/resource
从web浏览器显示一个登录页面,以使用用户和密码首次登录。现在没有登录页面,无法使用http://localhost:8081/resource
无需验证即可直接工作
如何将此示例扩展为像以前一样在后端具有Spring Security
basic auth?用户和密码
如何改变角度前端?我假设,对于后端的每个RESTAPI调用,也必须发送用户和密码
有一些教程在那里,但我无法让它工作。
只要我用和()…
扩展http.cors()
,我就会再次收到cors
错误,来自角度前端的REST API调用不再工作
@CrossOrigin()
@RestController
public class HelloWorldRestController {
@GetMapping("/resource")
public Map<String, Object> home() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
}
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
}
constructor(private http: HttpClient) {
this.http.get<Observable<{}>>('http://localhost:8081/resource')
.subscribe(result => {
console.log(result);
}
);
}