我正在研究Spring安全性,我希望一些控制器端点应该需要身份验证,一些不需要。我已经创建了一个安全配置。并尝试
@Bean
public SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> securityConfigurerAdapter() {
return new SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>() {
@Override
public void configure(HttpSecurity http) throws Exception {
http.cors(cor -> {
cor.disable();
}).authorizeHttpRequests(authorizeRequests -> {
authorizeRequests.requestMatchers("/api/**").permitAll()
.requestMatchers("api/login", "api/register")
.permitAll()
.requestMatchers("/api/auth").authenticated();
})
.sessionManagement(sessionManagement -> {
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}).authenticationProvider(authenticationProvider())
.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
字符串
但它仍然是登录和它是给http错误作为403禁止。screen shot of postman
并以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.
的形式给出警告
我试过另一种方法,
@Bean
public SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> securityConfigurerAdapter() {
return new SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>() {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authorizeRequests -> {
authorizeRequests.requestMatchers("/api/application/**").permitAll()
.requestMatchers("api/login", "api/register").permitAll().requestMatchers("/api/auth")
.authenticated();
}).build();
}
};
}
型
但它给出的错误是403 unathorized。我有关于How to allow certain endpoint in spring security to be allowed without authentication?的信息,但在Spring Boot 3. 2. 0 http.cors()
被弃用。
1条答案
按热度按时间t98cgbkg1#
问题是,当错误发生时,Spring会将用户发送到/error端点,但在您的情况下,该端点是受保护的,因此当用户试图访问它时,它会被拒绝,用户会得到403。
允许任何人访问错误端点:
字符串