【发布时间】:2018-08-15 18:38:44
【问题描述】:
我正在使用 Spring boot + Spring Security 制作 API。我在 Spring Security“允许”任何请求通过时遇到问题。
发生的事情是我有两个端点:
users/register/app
users/recoverpasswordbyemail
我正在用 Postman 测试它们,问题是如果我在应用程序启动后第一次调用其中一个端点而没有 Authoritation 标头或错误的标头,它不会让我进入并给出401 错误。但是,如果我使用正确的Authoritation 标头再次调用其他方法或相同的方法,然后再次调用其中一个没有标头,它会让我通过。我认为如果没有 auth 标头,它不应该工作。
我不确定是因为我在输入正确的身份验证标头时已经完成了某种“登录”,还是因为邮递员的问题。但我希望每次调用其中一个端点时都会为用户进行检查。
这是我的 Spring 配置文件:
@Configuration @EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserServiceImpl userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/users/register/app", "/users/recoverpasswordbyemail")
.hasAnyRole("ADMIN", "SADMIN")
.and().httpBasic().authenticationEntryPoint(new NotAuthorizedExceptionMapper())
.and().sessionManagement().disable();
}
@Override
public void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
而且每次发生这种情况时,如果存在(但是当我有错误的 auth 标头时)或我的 UsersService 中的任何内容,用户不会首先获得:
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("Hi");
User user = userRepository.findById(username).get();
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getRole());
}
这是我用来调用端点的 URL:
http://localhost:8680/ulises/usersserver/users/register/app
/ulises/usersserver/ 是 servlet 上下文
有人知道为什么会这样吗?我研究了很多,但没有发现任何可以解决的问题。
谢谢。
【问题讨论】:
标签: spring security authentication header endpoint