Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring Boot REST API后端和基本身份验证-从Angular 10前端调用REST API_Angular_Spring Boot_Spring Security - Fatal编程技术网

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);
        }
    );
}