我想要REST服务器中的两种请求:具有路径“ / freerest /”的任何人都可以请求,其他人则需要身份验证。
这是我的代码:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Configuration
class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
@Autowired
UserAccountRepository userAccountRepository;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
@Bean
UserDetailsService userDetailsService() {
return new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
UserAccount account = userAccountRepository.findByEmail(email);
if(account != null) {
return new User(account.getEmail(), account.getPassword(), true, true, true, true,
AuthorityUtils.createAuthorityList("USER"));
} else {
throw new UsernameNotFoundException("could not find the user '"
+ email + "'");
}
}
};
}
}
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/freerest/**").permitAll().and().authorizeRequests().anyRequest().hasAnyAuthority("USER");
}
}
在我的脑海中,在hasAnyAuthority(“ USER”)之后,应该有一个.permitAll()。但是不要。
因此,freerest路径可以正常工作,但是如果我尝试数据库中的某个用户或默认的Spring用户,则会得到403。
怎么了?
试试这个。您已and()
在antMatch和任何请求之间添加了一个。我认为这就是问题所在。
并添加正确的身份验证领域,后跟一个and()
,如下所示。在这里,我使用HTTP基本身份验证以实现宁静
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{
......
......
......
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/freerest/**").permitAll()
.anyRequest().hasAnyAuthority("USER")
.and()
.httpBasic();
}
......
......
......
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句