English 中文(简体)
允许 通往一条通道的所有人都在春天的不安全中被禁止。
原标题:After permitting All to a route, stil getting forbidden in Spring securoty

I m 采用泉子3.2.0。 I m 试图前往设在WT的Austhentication wth Spring security。 为此,我确定了设在华盛顿州的一个认证过滤器。 问题在于有一条路线:<代码>/auths/public/**,我想允许所有路线。 在安全界,我做了以下工作:

    @Configuration
    @EnableWebSecurity
    @RequiredArgsConstructor
    public class SecurityConfiguration {
        private final JwtAuthenticationFilter jwtAuthenticationFilter;
        private final AuthenticationProvider authenticationProvider;
    
        @Bean
        SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http.cors(AbstractHttpConfigurer::disable).authorizeHttpRequests((authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
                                    .requestMatchers("/auths/inner/**").hasRole(Role.INNER_SERVICE.name()) // Selectively permitted for users with role INNER_SERVICE with authentication
                                    .requestMatchers("/auths/authenticated/**").hasRole(Role.USER.name()) // Selectively permitted for users with role USER with authentication
                                    .requestMatchers("/auths/public/**").permitAll() // All requests are permitted
                                    .requestMatchers("/actuator/**").permitAll() // All requests are permitted
                                    .anyRequest().permitAll() // All other routes are permitted (!! security alert)
            ))
                    .sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                    .authenticationProvider(authenticationProvider)
                    .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
            return http.build();
        }
    }

这是《维也纳条约法公约》的习俗过滤器。

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtService jwtService;
    private final UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain) throws ServletException, IOException {
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final String userEmail;
        // for public urls
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        // To cut out the "Bearer " part
        jwt = authHeader.substring(7);
        userEmail = jwtService.extractUsername(jwt, true);
        if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // user present but not authenticated yet
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail);
            if (jwtService.isTokenValid(jwt, userDetails, true)) {
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userDetails,
                        null, userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }

        }
        filterChain.doFilter(request, response);
    }

}

这里的主要部分是:

http.cors(AbstractHttpConfigurer::disable).authorizeHttpRequests((authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
                                    .requestMatchers("/auths/inner/**").hasRole(Role.INNER_SERVICE.name()) // Selectively permitted for users with role INNER_SERVICE with authentication
                                    .requestMatchers("/auths/authenticated/**").hasRole(Role.USER.name()) // Selectively permitted for users with role USER with authentication
                                    .requestMatchers("/auths/public/**").permitAll() // All requests are permitted
                                    .requestMatchers("/actuator/**").permitAll() // All requests are permitted
                                    .anyRequest().permitAll() // All other routes are permitted (!! security alert)
            ))
                    .sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                    .authenticationProvider(authenticationProvider)
                    .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
            return http.build();

在这里,你可以看到,我已经允许所有线路<代码>/auths/public,但当我请求:

POST http://localhost:5000/auths/public/send?message=Hello_Kafka I get:

{
    "timestamp": "2024-01-15T18:42:16.607+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "Forbidden",
    "path": "/auths/public/send"
}

这些是我请求的标志:

2024-01-16 00:12:16.495 
d9814d3abe2031bb
2024-01-16T00:12:16.495+05:30  WARN [auth,0ac98fa25129402e7442fba23c5552be,d9814d3abe2031bb] 47661 --- [auth] [http-nio-auto-1-exec-1] [0ac98fa25129402e7442fba23c5552be-d9814d3abe2031bb] o.s.w.s.h.HandlerMappingIntrospector     : Cache miss for ERROR dispatch to  /error  (previous null). Performing MatchableHandlerMapping lookup. This is logged once only at WARN level, and every time at TRACE.
2024-01-16 00:12:16.550 
afab4ea55ae080f6
2024-01-16T00:12:16.550+05:30 DEBUG [auth,0ac98fa25129402e7442fba23c5552be,afab4ea55ae080f6] 47661 --- [auth] [http-nio-auto-1-exec-1] [0ac98fa25129402e7442fba23c5552be-afab4ea55ae080f6] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for POST "/error?message=Hello_Kafka", parameters={masked}
2024-01-16 00:12:16.558 
afab4ea55ae080f6
2024-01-16T00:12:16.558+05:30 DEBUG [auth,0ac98fa25129402e7442fba23c5552be,afab4ea55ae080f6] 47661 --- [auth] [http-nio-auto-1-exec-1] [0ac98fa25129402e7442fba23c5552be-afab4ea55ae080f6] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2024-01-16 00:12:16.619 
afab4ea55ae080f6
2024-01-16T00:12:16.619+05:30 DEBUG [auth,0ac98fa25129402e7442fba23c5552be,afab4ea55ae080f6] 47661 --- [auth] [http-nio-auto-1-exec-1] [0ac98fa25129402e7442fba23c5552be-afab4ea55ae080f6] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using  application/json , given [*/*] and supported [application/json, application/*+json]
2024-01-16 00:12:16.629 
afab4ea55ae080f6
2024-01-16T00:12:16.629+05:30 DEBUG [auth,0ac98fa25129402e7442fba23c5552be,afab4ea55ae080f6] 47661 --- [auth] [http-nio-auto-1-exec-1] [0ac98fa25129402e7442fba23c5552be-afab4ea55ae080f6] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [{timestamp=Tue Jan 16 00:12:16 IST 2024, status=403, error=Forbidden, message=Forbidden, path=/auths (truncated)...]
2024-01-16 00:12:16.659 
afab4ea55ae080f6
2024-01-16T00:12:16.659+05:30 DEBUG [auth,0ac98fa25129402e7442fba23c5552be,afab4ea55ae080f6] 47661 --- [auth] [http-nio-auto-1-exec-1] [0ac98fa25129402e7442fba23c5552be-afab4ea55ae080f6] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 403

从原木中,我可以看到,由于某种原因,Im 发运会错失手,我无法理解为什么。

整个代码基:Hangout-Auth-service, 核对updated-workflow 页: 1

This compose file will help you setup other dependency services

Additional services required to setup:

<https://github.com/光学Squid/hangout-service-discovery/tree/dev"rel=“nofollow noreferer”> > > ...... <> 发现/a>, 核对

,Application Portal, 校对

问题回答

You would need to configure or disable csrf through you filter. That is why you get this error I think. For more details about this type of error you can enable spring security log in your config file with that config:

logging:
  level:
    org:
      springframework:
        security: TRACE

您可以尝试通过过滤器进行可分辨的手套:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws 
  Exception {
      http.cors(Customizer.withDefaults())
            .csrf(AbstractHttpConfigurer::disable)
    //...
}

希望会有所助益。

在安全过滤链中,可分解的炉.主要是,但这里我也有残疾的 co子。 这一错误主要是由于Im没有穿过任何 c子而导致 c子不匹配。

因此,安全 Filter 链条变化:

@Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors(AbstractHttpConfigurer::disable).csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests((authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
                                .requestMatchers("/auths/inner/**").hasRole(Role.INNER_SERVICE.name()) // Selectively permitted for users with role INNER_SERVICE with authentication
                                .requestMatchers("/auths/authenticated/**").hasRole(Role.USER.name()) // Selectively permitted for users with role USER with authentication
                                .requestMatchers("/auths/public/**").permitAll() // All requests are permitted
                                .requestMatchers("/actuator/**").permitAll() // All requests are permitted
                                .anyRequest().permitAll() // All other routes are permitted (!! security alert)
        ))
                .sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

我也谈到这个问题。 在从我的观点进行研究后,我认为<代码>permitAll()是指用户作用或特权是否仍需要紧缩。 这并不意味着你可以不经授权访问资源。

If you need to set a whitelist, consider using the ignoring configuration.

在这里,它应该解决你的问题。

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    String[] ignoredApis = ignoredAPI.split(",");
    return (web) -> web.ignoring()
                .requestMatchers("/auths/public/**");
}




相关问题
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 ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签