Spring引导和安全性中的CORS支持 [英] CORS support in spring boot and security
问题描述
我已将 spring security
配置为启用 cors
.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private CustomLogoutHandler logoutHandler;
@Autowired
private HttpLogoutSuccessHandler logoutSuccessHandler;
@Override
protected void configure( HttpSecurity http ) throws Exception
{
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/rest/noauth/**").permitAll()
.antMatchers("/rest/login").permitAll()
.antMatchers("/rest/logout").permitAll()
.antMatchers("/static/**").permitAll()
.antMatchers("/ws/**").permitAll()
.antMatchers("/rest/razorpay/hook").permitAll()
.antMatchers("/rest/user/cc").permitAll()
.antMatchers("/v2/api-docs/**", "/configuration/ui/**", "/swagger-resources/**",
"/configuration/security/**", "/swagger-ui.html/**", "/webjars/**")
.permitAll()
.anyRequest().authenticated()
.and()
.logout().addLogoutHandler(logoutHandler).logoutSuccessHandler(logoutSuccessHandler)
.logoutUrl("/rest/logout")
.and()
.addFilterBefore(
new JWTAuthenticationFilter("/rest/login", tokenService(), refreshTokenService,
authTokenModelRepository, userService, userActivitiesRepository,
handlerExceptionResolver, bCryptPasswordEncoder, redisTemplate),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTAuthorizationFilter(authenticationManager(), authTokenModelRepository,
userSubscriptionRepository, handlerExceptionResolver, redisTemplate),
UsernamePasswordAuthenticationFilter.class);
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure( AuthenticationManagerBuilder auth ) throws Exception
{
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
}
我有一个休息控制器,
@RestController
@RequestMapping( RestEndPoints.NO_AUTH_CONTROLLER )
@CrossOrigin(origins = "http://0.0.0.0:3000")
public class OtpController extends AbstractController {
@Autowired
private AuthService authService;
@ApiOperation( value = "Generate OTP to login using registered email address", response = UIResponse.class, notes = "Please do validate and send only the organisation email address" )
@ApiResponses( value = { @ApiResponse( code = 200, message = "Otp generated for <email_address>" ),
@ApiResponse( code = 400, message = "Email address not registered as CC", response = UIErrorMessage.class ),
@ApiResponse( code = 500, message = "Something went wrong", response = UIErrorMessage.class ) } )
@PostMapping( "/otp/{email_address:.+}" )
public ResponseEntity generateOtpToLogin( @PathVariable( "email_address" ) String emailAddress )
{
try
{
return buildResponse(authService.generateOtpForTheEmailAddress(emailAddress));
}
catch( DataException e )
{
return buildError(e);
}
}
}
但是,当从前端应用程序向 POST
方法发出API请求时,浏览器将进行 OPTIONS
调用,并将响应标头作为 Access-Control-Allowed-Origin:*
,即使我将其设置为 0.0.0.0:3000
并且浏览器出现错误,
But, when an API request is made from a frontend application to the POST
method, the browser is making an OPTIONS
call and that response headers as Access-Control-Allowed-Origin:*
even though I am setting it to 0.0.0.0:3000
and the browser is getting the error,
在以下位置访问XMLHttpRequest' http://192.168.1.3:8090/rest/noauth/otp/sandesha@test.com "来自来源' http://0.0.0.0:3000 '已被CORS政策阻止:响应中"Access-Control-Allow-Origin"标头的值必须当请求的凭据模式为时,不是通配符"*"'包括'.发起的请求的凭据模式XMLHttpRequest由withCredentials属性控制.
Access to XMLHttpRequest at 'http://192.168.1.3:8090/rest/noauth/otp/sandesha@test.com' from origin 'http://0.0.0.0:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
如何解决此问题?
推荐答案
我之前也遇到过同样的问题,我想它也希望有其他参数.
I faced same issue earlier, I suppose it expect some other parameter also.
以便我放置以下代码,它对我来说是工作文件.
So that i place following code and it's working file for me.
package com.ecommerce.auth_service.service.jwt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCORSFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String check = "xsrf-token,X-Total-Results,Authorization";
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, Authorization");
response.setHeader("Access-Control-Expose-Headers",check);
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
log.debug("Request get method call status SC_OK.");
response.setStatus(HttpServletResponse.SC_OK);
} else {
log.debug("Request get method not work chain start.");
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
这篇关于Spring引导和安全性中的CORS支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!