【发布时间】:2020-11-20 01:55:39
【问题描述】:
我有一个带有端点的 Springboot REST API
-
/api/quizzesGET -
/api/quizzes/{id}POST -
/api/registerPOST -
/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();
}
}
现在,当我尝试在 Postman 中访问 /api/register 时,响应为 401 unauthorised。我可以访问/。我知道/**是这个目录和任何子目录的通配符,所以它应该匹配root和/api/register和permitAll()?
编辑:更多信息
- 注释掉
SecurityConfig中的所有代码,我可以访问/、/api/quizzes、/api/quizzes/{id}而不是/api/register,实际上它返回403而不是401,这很有趣。 -
antMatchers("/**").permitAll(),访问除/api/register之外的所有内容,现在响应为 401 ? -
antMatchers("/**).authenticated(),一切都返回 401 unauthorized
我想知道,所有/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");
}
【问题讨论】:
标签: java spring-boot frameworks authorization