Spring Boot Sping Boot 和安全性中的CORS支持

jm81lzqq  于 2023-06-05  发布在  Spring
关注(0)|答案(2)|浏览(140)

我已配置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);
    }
  }

and I have a rest休息controller控制,

@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并且浏览器收到错误,
CORS策略已阻止从源“http://0.0.0.0:3000”访问“http://192.168.1.3:8090/rest/noauth/otp/sandesha@test.com”处的XMLHttpRequest:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不能为通配符“*”。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。
如何解决这个问题?

mgdq6dx1

mgdq6dx11#

我以前也遇到过同样的问题,我想它也期望一些其他的参数。
所以我把下面的代码和它的工作文件给我。

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() {
  }
}
yrefmtwq

yrefmtwq2#

我已经在这个Stackoverflow问题中回答了同样的问题
CORS errors using Spring Boot, Spring Security

相关问题