Spring Security Spring securuty允许一个GET请求端点和其他身份验证端点

bqujaahr  于 5个月前  发布在  Spring
关注(0)|答案(4)|浏览(81)

我有一个spring安全配置类,我希望在我的spring Boot MVC中允许GET请求端点/api/check/status?appId=12345,然后让所有其他端点包括身份验证措施。
这是我配置的一部分public SecurityFilterChain securityFilterChain(HttpSecurity http)throws Exception {

http
    //Authenticate HTTP endpoints
   .authorizeHttpRequests(authorize -> authorize            
        .requestMatchers(AntPathRequestMatcher.antMatcher("/api/check/status?appId=**")).permitAll()
        .anyRequest().authenticated()
    )
    //Sessions should be stateless
         .sessionManagement(smc -> smc
              .sessionCreationPolicy(SessionCreationPolicy.STATELESS
    )

字符串
我用这个,仍然要求认证。不知道如何让它允许没有授权。任何人帮助

hxzsmxv2

hxzsmxv21#

.authorizeHttpRequests(authorize -> authorize
    .requestMatchers(HttpMethod.GET, "/api/check/status").permitAll()
    .anyRequest().authenticated()
)

字符串
尝试以上配置。
我们的想法是定义请求类型,而不包括matcher中的参数

bfhwhh0e

bfhwhh0e2#

我能够修复的挑战,如下.现在工作如预期.

.authorizeHttpRequests(authorize -> authorize
    .requestMatchers(antMatcher("/api/check/status")).permitAll()                    
    .anyRequest().authenticated()
)

字符串

2j4z5cfb

2j4z5cfb3#

据我所知,你不需要在antMatcher(String pattern)方法参数中写query-string,因为“String pattern”需要ant-style-pattern
antMatcher(String pattern)方法中有方法doc
“创建一个具有特定模式的匹配器,该模式将以区分大小写的方式匹配所有HTTP方法。
Params:pattern -用于匹配的ant模式Since:5.8”
所以代码需要像

.authorizeHttpRequests(authorize -> authorize            
    .requestMatchers(AntPathRequestMatcher.antMatcher("/api/check/status")).permitAll()
    .anyRequest().authenticated()
)

字符串
有关蚂蚁样式图案外观this的更多详细信息,

3qpi33ja

3qpi33ja4#

我认为你可以在你的安全配置中使用自定义的RequestMatcher。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/public/**").permitAll() // Allow access to public endpoints
            .anyRequest().authenticated() // Require authentication for all other requests
            .and()
            .formLogin() // Use form-based authentication
            .loginPage("/login") // Specify the login page URL
            .defaultSuccessUrl("/home") // Redirect to home page after successful login
            .failureUrl("/login?error") // Redirect to login page with error message on failed login
            .and()
            .logout() // Enable logout functionality
            .logoutUrl("/logout") // Specify the logout URL
            .logoutSuccessUrl("/login") // Redirect to login page after successful logout;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user").password("{noop:password}").roles("USER") 
            .and()
            .withUser("admin").password("{noop:password}").roles("USER", "ADMIN");
    }
}

字符串
我想这会有帮助的。最好的问候

相关问题