spring-security 未经授权的Spring Security

bvuwiixz  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(193)

我正在编写一个Springboot api rest,但是我遇到了一个关于Spring安全的问题。当我想向服务器发出请求时,它抛出了未经授权的401,但是我已经配置了Spring安全。下面是代码:

public class SecurityConfig  extends WebSecurityConfigurerAdapter {

@Bean
PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.GET, "/characters/**").permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
}

@Override
@Bean
protected UserDetailsService userDetailsService() {

    UserDetails admin= User.builder().username("admin").password(passwordEncoder().encode("123")).roles("ADMIN")
            .build();

    UserDetails user= User.builder().username("user").password(passwordEncoder().encode("123")).roles("USER")
            .build();

    return new InMemoryUserDetailsManager(admin,user);
}

}
请求方法:

@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value ="/characters"  ,method = RequestMethod.GET)
public List<ImagenNombreDTO> listarPersonajes(){
    try {
        return personajeService.listarPersonajes();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
zi8p0yeb

zi8p0yeb1#

在www.example.com文件的antmatchers()方法中进行以下更改SecurityConfig.java。
再添加一个“/characters”端点条目,如下所示,然后查看错误是否仍然存在。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.GET, "/characters","/characters/**").permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
}

相关问题