English 中文(简体)
在请拨资源上没有见到“Control-Allow-Origin”。 春季安全
原标题:No Access-Control-Allow-Origin header is present on the requested resource. in spring security

查阅XMLHttpRequest, https://b304-210-121-223-90.ngrok.io/ members/sign-up 原籍 http:// localhost:3000 索马里再次解放联盟的政策阻止了: 对飞行前飞行请求的回复 在请拨资源上没有见到“Control-Allow-Origin”。

I m working on Spring boot and react.

当前线人向浏览器发出请求时,我便会收到这个问题。 虽然在邮局工作。

我只拿到200处ngo。

www.un.org/Depts/DGACM/index_french.htm TRACE

2023-10-19T11:34:42.070+09:00 INFO 18568 --- [ main] o.s.d.j.r.query.QueryEnhancerFactory : Hibernate is in classpath; If applicable, HQL parser will be used.

2023-10-19T11:34:43.091+09:00 WARN18568 ---[主要]JpaBaseConfiguration$JpaWebConfiguration : Spring.jpa. open-in-view 因违约而得以实现。 因此,可以在提出意见期间查询数据库。 诚然,会春。 jpa. open-in-view to disable this press

2023-10-19T11:34:43.099+09:00 TRACE 18568 --- [ main] eGlobalAuthenticationAutowiredConfigurer : Eagerly initializing {securityConfig=com.jbaacount.config.SecurityConfig$$SpringCGLIB$$0@27ee8493}

Reutwork3:

2023-10-19T11:34:43.452+09:00 INFO18568 - [ main] o.s.b.w.embe.tomcat. TomcatWebServer : Tomcat开始在港口:8080(http://www.un.org)。

2023-10-19T11:34:43.459+09:00 INFO18568 - [ main] com.jbaacount. 服务器应用:在6.136秒开始的服务器应用(运行时间为6.543次)

2023-10-19T11:34:49.569+09:00 INFO18568 - [nio-8080-exec-1] o.a.c.C.[Tomcat].[当地]: 1. 启动春季派遣 传真机 Servlet

Reutworking3:

2023-10-19T11:34:49.576+09:00 DEBUG18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy: Securing OPTIONS / members/sign-up

2023-10-19T11:34:49.577+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy: Invoking DisableEncodeUrlFilter (1/13)

2023-10-19T11:34:49.577+09:00 TRACE 18568 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/13)

2023-10-19T11:34:49.578+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy: Invoking SecurityContextHolderFilter (3/13)

2023-10-19T11:34:49.579+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy: Invoking HeaderWriterFilter (4/13)

2023-10-19T11:34:49.580+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy : InvokinglogoutFilter (5/13)

2023-10-19T11:34:49.580+09:00TRACE 18568 - [nio-80-exec-1] o.s.w.a.logout. CarlooutFilter : Did notcompquest to Or [Ant [pattern= /logout , GET], Ant [pattern= /logout , POST], Ant [pattern= /logout , PUT], Ant [pattern= /logout , DELETE]

2023-10-19T11:34:49.580+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy: Invoking JwtAuthenticationFilter (6/13)

2023-10-19T11:34:49.580+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy: Invoking JwtVerificationFilter (7/13)

2023-10-19T11:34:49.580+09:00 INFO18568 - [nio-8080-exec-1] c.j.g.s.filter.JwtVerificationFilter : ==should NotFilter==

2023-10-19T11:34:49.580+09:00 INFO18568 - [nio-8080-exec-1] c.j.g.s.filter.JwtVerificationFilter : 批准=无效

2023-10-19T11:34:49.580+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy : Invoking RequestCacheAwareFilter (8/13)

2023-10-19T11:34:49.580+09:00 TRACE 18568 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderAwareRequestFilter (9/13)

2023-10-19T11:34:49.581+09:00TRACE 18568 ---[nio-80-exec-1] o.s.security.web.FilterChainProxy : Invoking AnonymousAuthenticationFilter (10/13)

2023-10-19T11:34:49.581+09:00TRACE 18568 ---[nio-80-exec-1] o.s.security.web.FilterChainProxy: Invoking SessionManagementFilter (11/13)

2023-10-19T11:34:49.581+09:00TRACE 18568 - [nio-80-exec-1].s.w.c.SupplierDefered SecurityContext : 创建安全委员会 [无认证]

2023-10-19T11:34:49.582+09:00TRACE 18568 - [nio-80-exec-1] o.s.w.a. AnonymousAuthenticationFilter : Set SecurityContextHolder to AnonymousAuthentication Token [ Principal=anonymousUser, Frau=[PROTEC], Authenticated Authorities=true, details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:

2023-10-19T11:34:49.582+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy : Invoking Statelessnession TranslationFilter (12/13)

2023-10-19T11:34:49.582+09:00TRACE 18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy : Invoking authorizationFilter (13/13)

2023-10-19T11:34:49.582+09:00 TRACE 18568 --- [nio-8080-exec-1] estMatcherDelegatingAuthorizationManager : Authorizing SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@3e08b966]

2023-10-19T11:34:49.589+09:00 TRACE 18568 --- [nio-8080-exec-1] estMatcherDelegatingAuthorizationManager : Checking authorization on SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@3e08b966] using org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer$$Lambda$1596/0x0000000801c1a730@1b7a1007

2023-10-19T11:34:49.589+09:00 DEBUG18568 - [nio-80-exec-1] o.s.security.web.FilterChainProxy : 有保障的OPTIONS / members/sign-up

2023-10-19T11:34:49.603+09:00 TRACE 18568 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match request to [Is Secure]

Here are my codes

<>安全栏>

@RequiredArgsConstructor
@Configuration
@EnableWebSecurity
public class SecurityConfig
{
    private final JwtService jwtService;
    private final RedisRepository redisRepository;
    private final CustomAuthorityUtils authorityUtils;
    private final MemberDetailsService memberDetailsService;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
    {
        http
                .headers((headers) ->
                        headers.frameOptions((frameOptions) -> frameOptions.disable()))
                .csrf(csrf -> csrf.disable())
                .httpBasic(httpBasic -> httpBasic.disable())
                .formLogin(formLogin -> formLogin.disable())
                .sessionManagement(sessionManagement ->
                        sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .exceptionHandling(exceptionHandling ->
                        exceptionHandling
                                .accessDeniedHandler(new CustomAccessDeniedHandler())
                                .authenticationEntryPoint(new CustomAuthenticationEntryPoint()))
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                        .requestMatchers(HttpMethod.GET).permitAll()
                        .requestMatchers(HttpMethod.PATCH, "/members/help/reset-password").permitAll()
                        .requestMatchers(HttpMethod.POST, "/members/login", "/members/sign-up").permitAll()
                        .requestMatchers(HttpMethod.POST).hasAnyRole("USER", "ADMIN")
                        .requestMatchers(HttpMethod.PATCH).hasAnyRole("USER", "ADMIN")
                        .requestMatchers(HttpMethod.DELETE).hasAnyRole("USER", "ADMIN")
                        .anyRequest().permitAll())
                .apply(new CustomFilterConfigurer());

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
    

    public class CustomFilterConfigurer extends AbstractHttpConfigurer<CustomFilterConfigurer, HttpSecurity>
    {
        @Override
        public void configure(HttpSecurity builder) throws Exception
        {
            AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);

            JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager, jwtService, redisRepository);
            jwtAuthenticationFilter.setFilterProcessesUrl("/members/login");
            jwtAuthenticationFilter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessfulHandler());
            jwtAuthenticationFilter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());

            JwtVerificationFilter jwtVerificationFilter = new JwtVerificationFilter(jwtService, authorityUtils, memberDetailsService);

            builder
                    .addFilter(jwtAuthenticationFilter)
                    .addFilterAfter(jwtVerificationFilter, JwtAuthenticationFilter.class);
        }
    }
}

在 Custom菲勒堡,我添加了扩大用户名称PasswordAuthenticationFilter和“PerRequestFilter”的过滤器。

<>载体>

@Slf4j
@RequiredArgsConstructor
public class JwtVerificationFilter extends OncePerRequestFilter
{
    private final JwtService jwtService;
    private final CustomAuthorityUtils authorityUtils;
    private final MemberDetailsService memberDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
    {
        log.info("===doFilterInternal===");

        try {
            String accessToken = resolveAccessToken(request);
            jwtService.isValidToken(accessToken);
            setAuthenticationToContext(jwtService.getClaims(accessToken));

            log.info("accessToken = {}", accessToken);
        } catch (InvalidTokenException e){
            log.error("Error processing JWT: {}", e.getMessage());
            throw e;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException
    {
        String authorization = request.getHeader(AUTHORIZATION);
        log.info("===shouldNotFilter===");
        log.info("authorization = {}", authorization);

        return authorization == null || !authorization.startsWith("Bearer ");
    }

    private void setAuthenticationToContext(Claims claims)
    {
        String email = claims.getSubject();
        UserDetails userDetails = memberDetailsService.loadUserByUsername(email);

        List<GrantedAuthority> authorities = authorityUtils.createAuthorities((List) claims.get("roles"));

        log.info("===setAuthenticationToContext===");
        log.info("authorities = {}", authorities);

        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private String resolveAccessToken(HttpServletRequest request)
    {
        return request.getHeader(AUTHORIZATION).substring(7);
    }
}

在NotFilter一案中,如果该请求没有在HttpHeader的鸡奸或授权,则该请求是真实的。 因此,

doFilterInternal will not be executed for the request.

<>AuthenticationFilter>

@Slf4j
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter
{
    private final AuthenticationManager authenticationManager;
    private final JwtService jwtService;
    private final RedisRepository redisRepository;

    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            ObjectMapper objectMapper = new ObjectMapper();
            LoginDto loginDto = objectMapper.readValue(request.getInputStream(), LoginDto.class);

            UsernamePasswordAuthenticationToken authenticationToken
                    = new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword());

            return authenticationManager.authenticate(authenticationToken);
        }

        catch (RuntimeException e)
        {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws ServletException, IOException
    {
        String email = authResult.getName();

        List<String> roles = authResult.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());

        log.info("===successfulAuthentication===");
        log.info("authorities = {}", authResult.getAuthorities());
        String accessToken = jwtService.generateAccessToken(email, roles);
        String refreshToken = jwtService.generateRefreshToken(email);

        redisRepository.saveRefreshToken(refreshToken, email);

        response.setHeader("Authorization", "Bearer " + accessToken);
        response.setHeader("Refresh", refreshToken);

        this.getSuccessHandler().onAuthenticationSuccess(request, response, authResult);
    }
}

CorsConfiguration

@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfig()
    {
        return new WebMvcConfigurer()
        {
            @Override
            public void addCorsMappings(CorsRegistry registry)
            {
                registry.addMapping("/**")
                        .allowedOriginPatterns("http://localhost:3000", "https://b304-210-121-223-90.ngrok.io")
                        .allowedMethods(HttpMethod.GET.name(),
                                HttpMethod.POST.name(),
                                HttpMethod.OPTIONS.name(),
                                HttpMethod.PATCH.name(),
                                HttpMethod.DELETE.name())
                        .allowCredentials(true)
                        .allowedHeaders("*");
            }
        };
    }
}

我检查了杰夫的工具。 这里是头盔。

enter image description here

enter image description here

我猜测这一请求是寄给NotFilter的,但我不知道这一请求为何仍然是备选办法,尽管我允许在安全辩论中提出《任择议定书》和《优先权要求》。

If I missed anything or applied something wrong, please let me know.

问题回答

暂无回答




相关问题
array dependency injection in spring?

is there a way to use dependency injection to inject all available implementations of a specific interface in spring? This is kind of the same thing as asked here for .NET. Though my aim is to use @...

Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Grails Packaging and Naming Conventions

Packaging Controllers, Services,etc. i.e. - com.company.controllers - com.company.services Is this a good practice or should be avoided by all means?? Another worth mentioning problem I encountered ...

How can I determine Objects in application context?

I am trying to write a portlet for Liferay (using Tomcat and Spring) and need to use a database via Persistence API/Hibernate. I am using some configuration XMLs (applicationContext.xml, etc.) and ...

How to prevent JPA from rolling back transaction?

Methods invoked: 1. Struts Action 2. Service class method (annotated by @Transactional) 3. Xfire webservice call Everything including struts (DelegatingActionProxy) and transactions is configured ...

热门标签