【发布时间】:2018-04-13 22:22:07
【问题描述】:
我是 Angular 和 spring-security 的新手。尝试使用基本身份验证从 Angular 登录表单页面登录到其余端点时,我遇到了 CORS 问题。我的 Angular 代码在 http://localhost:4200 上运行,在 http://localhost:8181 上运行休息端点。我的角度登录表单尝试向我在登录控制器中指定的http://localhost:8181/token 发出请求。即使我在服务器端添加了 cors 配置,我也会收到此错误:-
无法加载http://localhost:8181/token:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。响应的 HTTP 状态代码为 403。
(角度) login.service.ts:-
@Injectable()
export class LoginService {
constructor(private http: Http) {}
sendCredential(username: string, password: string) {
const url = 'http://localhost:8181/token';
const encodedCredential = username + ':' + password;
const basicHeader = 'Basic ' + btoa(encodedCredential);
const headers = new Headers();
headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
headers.append('Authorization' , basicHeader);
const opts = new RequestOptions({headers: headers});
return this.http.get(url, opts);
}
}
(spring) SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] PUBLIC_MATCHERS = {
"/css/**",
"/js/**",
"/image/**",
"/book/**",
"/user/**"
};
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.cors().and()
.csrf().disable()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(PUBLIC_MATCHERS)
.permitAll()
.anyRequest()
.authenticated();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
}
LoginController.java
@RestController
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping("/token")
public Map<String, String> token(HttpSession session, HttpServletRequest request) {
String remoteHost = request.getRemoteHost();
int portNumber = request.getRemotePort();
String remoteAddr = request.getRemoteAddr();
System.out.println(remoteHost + ":" + portNumber);
System.out.println(remoteAddr);
return Collections.singletonMap("token", session.getId());
}
}
【问题讨论】:
-
CORS 似乎已停用 (spring.io/understanding/CORS)
-
我已经在 SecurityConfig 类中添加了 CORS 配置,如上代码块所示
-
问题在于您的身份验证机制,不知何故它无法对用户进行身份验证。所以它返回 403 状态
-
当我使用传统方法时,类实现 Filter 接口并为每个请求/响应执行 filterChain.doFilter 以进行 cors 处理而不是 spring CorConfigurationSource 它工作正常。
标签: java spring angular spring-rest