【发布时间】:2019-07-12 22:29:23
【问题描述】:
1.在 Spring boot 中,我在 pom.xml 文件中添加 "spring-boot-starter-security" 依赖项,并在角度控制台中出现错误提示 preflight error,即使我覆盖了该方法
@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
}
}
从浏览器我可以直接访问我的数据,方法是使用链接
http://localhost:8080/users/..并提供我在 application.properties 文件中设置的用户 ID 和密码。但通过使用相同的用户 ID 和密码,我无法获取数据的表单 restlet-client(用于测试 API 的类似 Postman 应用程序)。
proxy.conf.js 文件
module.exports = { "/myapi": { "target": "localhost:8080", "secure": false, "changeOrigin": true, "pathRewrite": { "^/myapi": "" } }
HttpInterceptorBasicAuthService.ts
@Injectable({ providedIn: 'root' }) export class HttpInterceptorBasicAuthService implements HttpInterceptor { constructor() { } intercept(request: HttpRequest<any>, next: HttpHandler){ let username='MSD' let password ='dummy' let basicAuthHeaderString = 'Basic '+ username + ':' + password; request=request.clone({ setHeaders : { Authorization : basicAuthHeaderString } }) return next.handle(request); } }
任何人都知道为什么会发生此错误,请解决。
【问题讨论】:
-
你好 Moni Shankar,在 WebConfig 类下面添加,然后再试一次,让我知道结果
-
嗨兄弟@PatelRomil感谢您的解决方案...我的问题得到了解决,它与角度相关的proxy.conf.js文件
-
@PatelRomil 但兄弟如果添加提供者:[{提供:HTTP_INTERCEPTORS,useClass:HttpInterceptorBasicAuthService,multi:true}然后出现CROS错误......如果你有任何想法......请分享
-
如果出现 CORS 问题,您必须在 Spring Boot 时添加一个 webconfig 类,请分享代理配置和 HttpInterceptorBasicAuthService 以获取更多详细信息
-
proxy.conf.js 文件---------- module.exports = { "/myapi": { "target": "localhost:8080", "secure": false , "changeOrigin": true, "pathRewrite": { "^/myapi": "" } }
标签: spring-boot cors angular7