我试图在另一个应用程序(spring-boot应用程序)上调用REST端点(angularjs)。应用程序正在以下主机和端口上运行。
http://localhost:8080
http://localhost:50029
我也在使用spring-security
和spring-boot应用程序。从HTML应用程序,我可以对REST应用程序进行身份验证,但此后,我仍然无法访问任何REST端点。例如,我有一个angularjs服务定义如下。
adminServices.factory('AdminService', ['$resource', '$http', 'conf', function($resource, $http, conf) {
var s = {};
s.isAdminLoggedIn = function(data) {
return $http({
method: 'GET',
url: 'http://localhost:8080/api/admin/isloggedin',
withCredentials: true,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
};
s.login = function(username, password) {
var u = 'username=' + encodeURI(username);
var p = 'password=' + encodeURI(password);
var r = 'remember_me=1';
var data = u + '&' + p + '&' + r;
return $http({
method: 'POST',
url: 'http://localhost:8080/login',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
};
return s;
}]);
angularjs控制器如下所示。
adminControllers.controller('LoginController', ['$scope', '$http', 'AdminService', function($scope, $http, AdminService) {
$scope.username = '';
$scope.password = '';
$scope.signIn = function() {
AdminService.login($scope.username, $scope.password)
.success(function(d,s) {
if(d['success']) {
console.log('ok authenticated, call another REST endpoint');
AdminService.isAdminLoggedIn()
.success(function(d,s) {
console.log('i can access a protected REST endpoint after logging in');
})
.error(function(d, s) {
console.log('huh, error checking to see if admin is logged in');
$scope.reset();
});
} else {
console.log('bad credentials?');
}
})
.error(function(d, s) {
console.log('huh, error happened!');
});
};
}]);
在致电http://localhost:8080/api/admin/isloggedin
时,我收到401 Unauthorized
。
在REST应用程序方面,我有一个CORS过滤器,如下所示。
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
@Override
public void destroy() { }
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "http://localhost:50029");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, X-Auth-Token");
response.setHeader("Access-Control-Allow-Credentials", "true");
if(!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig config) throws ServletException { }
}
我的Spring安全配置如下所示。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
@Autowired
private JsonAuthSuccessHandler jsonAuthSuccessHandler;
@Autowired
private JsonAuthFailureHandler jsonAuthFailureHandler;
@Autowired
private JsonLogoutSuccessHandler jsonLogoutSuccessHandler;
@Autowired
private AuthenticationProvider authenticationProvider;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private PersistentTokenRepository persistentTokenRepository;
@Value("${rememberme.key}")
private String rememberMeKey;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/api/admin/**").hasRole("ADMIN")
.antMatchers("/", "/admin", "/css/**", "/js/**", "/fonts/**", "/api/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.successHandler(jsonAuthSuccessHandler)
.failureHandler(jsonAuthFailureHandler)
.permitAll()
.and()
.logout()
.deleteCookies("remember-me", "JSESSIONID")
.logoutSuccessHandler(jsonLogoutSuccessHandler)
.permitAll()
.and()
.rememberMe()
.userDetailsService(userDetailsService)
.tokenRepository(persistentTokenRepository)
.rememberMeCookieName("REMEMBER_ME")
.rememberMeParameter("remember_me")
.tokenValiditySeconds(1209600)
.useSecureCookie(false)
.key(rememberMeKey);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(authenticationProvider);
}
}
所有处理程序正在执行的是基于用户是否登录,无法进行身份验证或注销而写出{success: true}
之类的JSON响应。 RestAuthenticationEntryPoint
如下所示。
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException ex)
throws IOException, ServletException {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
关于我遗失或做错的任何想法?
答案 0 :(得分:78)
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class SimpleCORSFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
public SimpleCORSFilter() {
log.info("SimpleCORSFilter init");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
无需额外定义此过滤器只需添加此类。 Spring将扫描并为您添加它。 SimpleCORSFilter。 以下是示例:spring-enable-cors
答案 1 :(得分:25)
我遇到了类似的情况。在进行研究和测试之后,我的发现是:
使用Spring Boot,启用全局CORS的推荐方法是在Spring MVC中声明并与细粒度@CrossOrigin
配置相结合:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}
}
现在,由于您使用的是Spring Security,因此您必须在Spring Security级别启用CORS,以允许它利用Spring MVC级别定义的配置:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
Here是非常优秀的教程,解释了Spring MVC框架中的CORS支持。
答案 2 :(得分:6)
如果您想在不使用过滤器或没有配置文件的情况下启用CORS,只需添加
@CrossOrigin
到控制器的顶部,它可以正常工作。
答案 3 :(得分:3)
这对我有用:
@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter {
//...
@Override
protected void configure(HttpSecurity http) throws Exception {
//...
http.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
return config;
}
});
//...
}
//...
}
答案 4 :(得分:2)
我正在使用func setConstraints() {
NSLayoutConstraint.activate([
switchTheme.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor), // bottomAnchor to set bottom target.
switchTheme.leftAnchor.constraint(equalTo: self.view.leftAnchor), // leftAnchor to set X left
switchTheme.rightAnchor.constraint(equalTo: self.view.rightAnchor), // rightAnchor to set X right
switchTheme.heightAnchor.constraint(equalToConstant: 40.0) //heightAnchor to set appropriate height.
])
}
,对我有用的是
A。通过以下方式添加cors映射:
spring boot 2.1.0
B。将以下配置添加到我的@Configuration
public class Config implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
}
中以确保春季安全性
HttpSecurity
对于Zuul代理,您也可以使用此 INSTEAD OF A和B (只需在Spring安全性中使用.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
return config;
}
})
启用它即可)
HttpSecurity.cors()
答案 5 :(得分:1)
要基于上述其他答案,如果您具有具有Spring安全性的Spring boot REST服务应用程序(非Spring MVC),则通过Spring安全性启用CORS就足够了(如果您使用Spring MVC,则使用{{1} } Yogen提到的bean可能是可行的方式,因为Spring安全性将委托给其中提到的CORS定义)
因此,您需要具有执行以下操作的安全配置:
WebMvcConfigurer
}
此链接上有更多相关信息:https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#cors
注意:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//other http security config
http.cors().configurationSource(corsConfigurationSource());
}
//This can be customized as required
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
List<String> allowOrigins = Arrays.asList("*");
configuration.setAllowedOrigins(allowOrigins);
configuration.setAllowedMethods(singletonList("*"));
configuration.setAllowedHeaders(singletonList("*"));
//in case authentication is enabled this flag MUST be set, otherwise CORS requests will fail
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
),则必须添加UserDetailsService
经过Spring Boot 2.0.0.RELEASE(即Spring 5.0.4.RELEASE和Spring Security 5.0.3.RELEASE)的测试
答案 6 :(得分:1)
对于我来说,使用弹簧安全时唯一能够100%工作的是跳过所有额外过滤器和豆子的额外毛茸茸以及任何间接的“魔术”人们一直暗示这对他们有用但不适合我。
相反,只需强制它使用普通StaticHeadersWriter
:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// your security config here
.authorizeRequests()
.antMatchers(HttpMethod.TRACE, "/**").denyAll()
.antMatchers("/admin/**").authenticated()
.anyRequest().permitAll()
.and().httpBasic()
.and().headers().frameOptions().disable()
.and().csrf().disable()
.headers()
// the headers you want here. This solved all my CORS problems!
.addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin", "*"))
.addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Methods", "POST, GET"))
.addHeaderWriter(new StaticHeadersWriter("Access-Control-Max-Age", "3600"))
.addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Credentials", "true"))
.addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization"));
}
}
这是我发现的最直接,最明确的方式。希望它可以帮到某人。
答案 7 :(得分:0)
如果您的程序最初没有使用Spring安全性并且无法承担代码更改的费用,那么创建一个简单的反向代理就可以解决问题。就我而言,我使用Nginx进行以下配置:
http {
server {
listen 9090;
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}
proxy_pass http://localhost:8080;
}
}
}
我的程序会收听:8080 。
答案 8 :(得分:0)
扩展WebSecurityConfigurerAdapter类并覆盖@EnableWebSecurity类中的configure()方法将起作用:下面是示例类
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling();
http.headers().cacheControl();
@Override
public CorsConfiguration getCorsConfiguration(final HttpServletRequest request) {
return new CorsConfiguration().applyPermitDefaultValues();
}
});
}
}
答案 9 :(得分:0)
检查一下:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
...
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
...
}
答案 10 :(得分:0)
这对我有用。
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
}
}
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedMethods("*")
.allowedHeaders("*")
.allowedOrigins("*")
.allowCredentials(true);
}
}
答案 11 :(得分:0)
此答案复制了@abosancic答案,但为避免CORS漏洞利用增加了额外的安全性。
提示1:在未检查允许访问的主机列表的情况下,不要照原样反映传入的源。
提示2:仅对列入白名单的主机允许凭据请求。
public static void StartProcessAndWait(string processFile, string arguments, string workingDirectory)
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = processFile,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
RedirectStandardError = true,
WorkingDirectory = workingDirectory
}
};
proc.Start();
var _ = ConsumeReader(proc.StandardOutput);
// ReSharper disable once RedundantAssignment
_ = ConsumeReader(proc.StandardError);
async Task ConsumeReader(TextReader reader)
{
string text;
while ((text = await reader.ReadLineAsync()) != null)
Console.WriteLine(text);
}
proc.WaitForExit(30000);
}
答案 12 :(得分:0)
第1步
通过使用@CrossOrigin
注释对控制器进行注释,将允许进行CORS配置。
@CrossOrigin
@RestController
public class SampleController {
.....
}
第2步
即使您可以将自己的CorsFilter注册为bean来提供自己的配置,Spring也已经具有CorsFilter。
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); // Provide list of origins if you want multiple origins
config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
答案 13 :(得分:0)
在我们的Spring Boot应用程序中,我们像这样设置了CorsConfigurationSource。
先添加allowedOrigns
然后设置applyPermitDefaultValues()
的顺序使Spring为允许的标头,公开的标头,允许的方法等设置默认值,因此我们不必指定这些值。
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:8084"));
configuration.applyPermitDefaultValues();
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
configurationSource.registerCorsConfiguration("/**", configuration);
return configurationSource;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**")
.access("@authProvider.validateApiKey(request)")
.anyRequest().authenticated()
.and().cors()
.and().csrf().disable()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
答案 14 :(得分:0)
只需建立一个单个课程,这样,一切都会很好:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCorsConfig implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, enctype");
response.setHeader("Access-Control-Max-Age", "3600");
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
答案 15 :(得分:0)
这对我来说是有效的,以便在Spring boot和React之间禁用CORS
@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* Overriding the CORS configuration to exposed required header for ussd to work
*
* @param registry CorsRegistry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(4800);
}
}
我还必须如下修改安全性配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors().configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedHeaders(Collections.singletonList("*"));
config.setAllowedMethods(Collections.singletonList("*"));
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
return config;
}
}).and()
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().exceptionHandling().accessDeniedHandler(apiAccessDeniedHandler());
}
答案 16 :(得分:0)
我很惊讶地发现 Eduardo Dennis 指出了最新的解决方案,该解决方案更简单且不需要编写自己的过滤器类:它使用
org.springframework.web.bind.annotation.CrossOrigin
控制器上的注释and().cors()
包含到您的 Spring Security 配置中。这就是你所要做的!
您可以像这样使用 @CrossOrigin
注释:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/api")
@CrossOrigin
public class BackendController {
...
}
如果您想配置 allowedHeaders
、methods
、origins
等,您可以简单地将这些值添加到注释中,如下所示:@CrossOrigin(origins = "http://localhost:50029", maxAge = 3600)
。
使用 @CrossOrigin
注释,Spring Security 配置变得非常简单。只需将 and().cors()
添加到您的 WebSecurityConfig.java
类:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.and().cors()
...
}
仅此而已!您可以删除您的 Filter/CORSFilter 类。如果要添加全局配置,也可以声明 CorsConfigurationSource
。请参阅 this great answer 或 this blog post by Sébastien Deleuze)。 Spring 开发人员也明确表示:
这种方法取代了之前基于过滤器的方法 推荐。
因此接受的答案已过时。这里还有一个完整的示例项目:https://github.com/jonashackt/microservice-api-spring-boot