java - 配置 Springboot 安全,允许的路径未授权 401
问题描述
我有一个具有端点的 Springboot REST API
/api/quizzes
GET
/api/quizzes/{id}
POST
/api/register
POST
/
GET
这是一个由 Thymeleaf 控制器类管理的欢迎页面
我已经按如下方式设置了我的安全类;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
/* This sets up the security on specified paths according to role of client */
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.httpBasic()
.and().authorizeRequests()
.antMatchers("/api/quizzes/**").hasRole("USER")
// .antMatchers("/api/register/").permitAll() // have tried this, still 401
.antMatchers("/**").permitAll() // does not permit `/api/register` but does `/` and `h2-
// console
.and().headers().frameOptions().disable();
}
/* This sets up the user roles by searching the database for a match, so they can access the
endpoints configured above */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
现在,当我尝试/api/register
在 Postman 中访问时,响应是401 unauthorised
. 我可以访问/
. 我知道这/**
是这个目录和任何子目录的通配符,所以它应该匹配 root and /api/register
, and permitAll()
?
编辑:更多信息
- 注释掉 中的所有代码
SecurityConfig
,我可以访问/
,/api/quizzes
,/api/quizzes/{id}
但不能访问/api/register
,实际上它返回 403 而不是 401 ,这很有趣。 antMatchers("/**").permitAll()
,访问所有除了/api/register
,现在响应是401?antMatchers("/**).authenticated()
, 一切都返回 401 未授权
我想知道,所有/api/quizzes
端点都在 下QuizController
,但/api/register
端点在它自己的@RestController
控制器类下。我错过了注释吗?看不出来,还是一样的
我知道 Spring 没有查看我的 UserService,因为sout
没有打印消息。我昨天确实有这个工作,它是User
从数据库表中获取的。我不确定发生了什么变化。
这是我的用户服务
@Service
public class UserService implements UserDetailsService {
@Autowired
static UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) {
Optional<User> user = userRepository.findByEmail(email);
System.out.println("loadByUsername called");
if (user.isPresent()) {
System.out.println("loadUserByUsername called: user.isPresent() = true");
return new MyUserDetails(user.get().getEmail(), user.get().getPassword());
} else {
throw new UsernameNotFoundException("User: " + email + " not found");
}
}
public static void saveUserToDB(User user) {
if (user.getPassword().length() < 5) {
throw new UsernameNotFoundException("password too short.");
}
Pattern pattern = Pattern.compile("simon\\.aust@hotmail\\.com");
Matcher matcher = pattern.matcher(user.getEmail());
if (!matcher.matches()) {
throw new UsernameNotFoundException("email not correct format");
}
userRepository.save(user);
}
}
用户存储库
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findByEmail(String email);
}
我的用户详情
public class MyUserDetails implements UserDetails {
private final String username;
private final String password;
public MyUserDetails(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
编辑2;通过内存身份验证,我可以使用某些端点进行身份验证,但同样不能/api/register
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication()
.passwordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance())
.withUser("user1")
.password("password")
.roles("USER");
}
解决方案
尝试这个:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/api/register/**").permitAll()
.antMatchers("/api/quizzes/**").authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
推荐阅读
- azure-devops - 过滤 VSTS 构建工件以基于“触发”分支发布
- c - 文件的班次加密和解密 - 代码无法正常工作
- javascript - 使用jquery“keypress”功能时如何禁用按键加速?
- php - mysqli prepared statement get result error
- javascript - Supposedly identical code results in different routing behavior
- javascript - 可以将 https 请求标头伪装成安全威胁吗?
- python - Python Django heroku 错误“![远程拒绝] master -> master (pre-receive hook denied)”
- android - Merging 2 SQLite database files without windows server
- c# - 列表
到字符串 [] - python - 如何在 django 中修复 NoReverseMatch