我有一个应用程序,配置了安全性,使用基本身份验证(登录名+密码)。我的主要问题是,当我在Postman中执行POST
请求时,我会收到401 Unauthorized
。但是当我执行相同的请求,但将其更改为GET
请求时,它返回的数据状态为200
。这里是我的安全配置与其他截图。
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends VaadinWebSecurity {
private static final String LOGIN_URL = "/login";
private static final String LOGIN_PROCESSING_URL = "/login";
private static final String LOGIN_FAILURE_URL = "/login?error";
private static final String LOGOUT_SUCCESS_URL = "/";
private static final String DENIED_PAGE_URL = "/404";
private final UserService userService;
private final PasswordEncoder passwordEncoder;
public SecurityConfiguration(UserService userService, PasswordEncoder passwordEncoder) {
this.userService = userService;
this.passwordEncoder = passwordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/login", "/register").permitAll();
auth.requestMatchers("/public/**").permitAll();
auth.requestMatchers("/icons/**").permitAll();
auth.requestMatchers("/images/**").permitAll();
auth.requestMatchers("/api/**").authenticated();
auth.requestMatchers("/private/**").authenticated();
auth.requestMatchers("/admin/**").hasAnyRole("ADMIN", "SUPER_ADMIN");
})
.formLogin(loginForm -> {
loginForm.loginPage(LOGIN_URL);
loginForm.loginProcessingUrl(LOGIN_PROCESSING_URL);
loginForm.failureUrl(LOGIN_FAILURE_URL);
})
.logout(logout -> logout.logoutSuccessUrl(LOGOUT_SUCCESS_URL))
.exceptionHandling(e -> {
e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
e.accessDeniedPage(DENIED_PAGE_URL);
})
.httpBasic();
super.configure(http);
setLoginView(http, LoginView.class);
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
daoAuthenticationProvider.setUserDetailsService(userService);
return daoAuthenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
字符串
这是我的请求
@PostMapping("/save")
public Expense saveExpense(@RequestBody ExpenseRequest expenseRequest) {
Expense expense = expenseConvertor.convertToExpense(expenseRequest);
return expenseService.saveExpense(expense);
}
型
的数据
GET请求
的
其他信息
- 任何其他在header中提供了auth的
GET
请求都可以正常工作 PUT
、POST
、DELETE
请求,全部抛出401 Unauthorized
任何帮助都将是伟大的,谢谢
2条答案
按热度按时间mqxuamgl1#
只有GET传递通常是因为csrf而发生的,因为你正在禁用它。我认为你应该保存安全配置文件并重新启动你的应用程序。
ngynwnxp2#
我猜你正在处理一个CSRF错误,知道发生了什么的最快方法是将
logging.level.org.springframework.security=TRACE
添加到application.properties
并分析日志。您已经在
SecurityConfiguration#configure(HttpSecurity)
方法的第二行中禁用了CSRF保护,但是,在下面的几行中,您正在调用super.configure(http);
,它又会再次配置CSRF保护。尝试删除该行或提供CSRF令牌。