gpt4 book ai didi

java - URL 和用户的 Spring Security 配置

转载 作者:行者123 更新时间:2023-11-30 08:18:04 25 4
gpt4 key购买 nike

我想在我的 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。

出了什么问题?

最佳答案

试试这个。您已在 antMatch 和任何请求之间添加了 and()。我认为这就是问题所在。

还要添加正确的身份验证领域,后跟 and() ,如下所示。 这里我使用HTTP基本身份验证来实现restful

    @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();
}

......
......
......

}

关于java - URL 和用户的 Spring Security 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29376117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com