簡體   English   中英

未經授權 Spring 安全

[英]Unauthorized Spring Security

我正在編寫 Springboot api rest 但我對 Spring 安全性有疑問。 當我想向服務器發出請求時,它會拋出 Unauthorized 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);
    }
}

在 SecurityConfig.java 文件的 antmatchers() 方法中進行以下更改。

再添加一個“/characters”端點條目,如下所示,看看錯誤是否仍然存在。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM