【发布时间】:2019-12-05 09:24:17
【问题描述】:
我尝试访问 URL: http://localhost:8080/hello-world/path-variable 从 Angular 到 Spring Boot。在添加 Spring Security 之前项目很好。我在 Spring Boot 中使用了基本身份验证安全性。所以,我需要在发送请求之前添加标题以进行授权。我已经添加了 Angular 标题从 Spring Boot 访问资源时,它向我显示错误,例如:
这是一个服务类:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class HelloWorldBean{
constructor(public message:String){
}
}
@Injectable({
providedIn: 'root'
})
export class WelcomeDataService {
constructor(private httpClient:HttpClient) { }
executeHelloWorldBeanService(){
return this.httpClient.get<HelloWorldBean>('http://localhost:8080/hello-world-bean');
console.log("hello world bean service executed");
}
executeHelloWorldBeanServiceWithPathVariable(name){
console.log("hitting to get data")
let basicAuthHeaderString=this.createBasicAuthenticationHeader();
console.log(basicAuthHeaderString);
let headers=new HttpHeaders({
Authorization: basicAuthHeaderString
})
//i have added headers here in the URL
return this.httpClient.get<HelloWorldBean>(
`http://localhost:8080/hello-world/path-variable/${name}`,
{headers});
console.log("hello world bean service executed");
}
createBasicAuthenticationHeader(){
let username='ashwin'
let password='karki'
let basicAuthHeaderString='Basic '+ window.btoa(username + ':' + password);
return basicAuthHeaderString;
}
}
我尝试通过将用户名和密码添加为 let basicAuthHeaderString='Basic '+ window.btoa(username + ':' + password); 来发送用户名和密码,但它说我被 CORS 政策阻止了。
在这里,我在我的 spring boot 中添加了:
spring.security.user.name=ashwin
spring.security.user.password=karki
在这个安全配置类中,我禁用了 csrf():
package com.ashwin.rws.basic.auth;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@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();
}
}
在控制器类中:
package com.ashwin.rws.rest.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ashwin.rws.model.HelloWorldBean;
@CrossOrigin(origins="http://localhost:4200")
@RestController
public class HelloWorldController {
@GetMapping(path="/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldBeanPathVariable(@PathVariable("name") String name) {
System.out.print("name is"+name);
return new HelloWorldBean(String.format("Hello world %s", name));
}
}
来自网络标签的消息
Request URL: http://localhost:8080/hello-world/path-variable/in28minutes
Request Method: GET
Status Code: 401
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Sat, 27 Jul 2019 08:17:09 GMT
Expires: 0
Pragma: no-cache
WWW-Authenticate: Basic realm="Realm", Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Basic YXNod2luOmthcmtp
Origin: http://localhost:4200
Referer: http://localhost:4200/welcome/in28minutes
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
【问题讨论】:
-
你为什么要用
@CrossOrigin(origins="http://localhost:4200")和http://localhost:8080之类的东西污染你的生产代码?您的请求不会来自现实生活中的http://localhost:4200,对吗?如果您的计划是从同一主机提供前端和 API,请使用 Angular CLI 代理支持:angular.io/guide/build#proxying-to-a-backend-server
标签: angular spring spring-boot spring-security angular7