首页 > 解决方案 > 配置 Springboot 安全,允许的路径未授权 401

问题描述

我有一个具有端点的 Springboot REST API

我已经按如下方式设置了我的安全类;

@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()?

编辑:更多信息

我想知道,所有/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");

}
    

标签: javaspring-bootframeworksauthorization

解决方案


尝试这个:

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

推荐阅读