我是角度和 spring 安全的新手 . 当我尝试使用基本身份验证从角度登录表单页面登录到其余 endpoints 时,我遇到CORS问题 . 我的Angular代码在http://localhost:4200上运行,而休息终点在http://localhost:8181上运行 . 我的angular login-form尝试向我在登录控制器中指定的http://localhost:8181/token发出请求 . 即使我在服务器端添加了cors配置,我也会收到此错误: -
无法加载http://localhost:8181/token:因此不允许对预检请求进行响应't pass access control check: No ' Access-Control-Allow-Origin ' header is present on the requested resource. 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());
}
}
5 回答
我被困这个问题2天,并在
controller
中添加@CrossOrigin("*")
解决了我的问题 .注意:你可以把
origin address
代替*
使用
代替 .
在控制器内部使用.properties文件中的值
@Value(“$ ”)私有字符串网站;
使用@crossOrigin(网站)
加
到
web.xml
以允许来自所有主机的连接原产地:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
试试这个配置 . 它应该适合你 .
由于您使用的是spring security / authentication . 您应该使用setAllowCredentials(true) .