Безопасность Spring дает 401 на всех конечных точках API

Я видел много сообщений по одной и той же проблеме, но ни одно решение не помогло мне.

У меня есть API, защищенный пружинной безопасностью, как показано ниже.

@EnableWebSecurity
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired private UserService userService;

    public SecurityConfiguration() {
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/actuator/shutdown", "/api/register");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()
        .authorizeRequests()
        .anyRequest().authenticated()
        .and().httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
        .userDetailsService(userService)
        .passwordEncoder(passwordEncoder());
    }

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

Мне нужны конечные точки /api/register и /actuator/shutdown, доступные без аутентификации. Но, как оказалось, все конечные точки возвращают один и тот же код состояния 401.


person Karthik Chennupati    schedule 15.07.2020    source источник


Ответы (2)


попробуй с этим.

 protected void configure(HttpSecurity httpSecurity) throws Exception {
  httpSecurity
        //no authentication needed for these context paths
        .authorizeRequests()
        .antMatchers("/your Urls that dosen't need security/**").permitAll()
person Supun Dharmarathne    schedule 15.07.2020
comment
Спасибо за помощь. Но он все еще дает 401 - person Karthik Chennupati; 15.07.2020
comment
Извиняюсь! Я добавил antMatcher к существующему оператору вместо того, чтобы заменить его вашим. Теперь работает. Но так как csrf сейчас не отключено, то для доступа без аутентификации выдается 403 вместо 401 - person Karthik Chennupati; 15.07.2020

Мы реализовали аналогичный подход, упомянутый Супуном выше,

http
.authorizeRequests()
.antMatchers(AUTH_WHITELIST).permitAll()
.anyRequest().authenticated()
.and().httpBasic()

Вы можете оставить «AUTH_WHITELIST», как показано ниже, чтобы продолжать добавлять несколько конечных точек.

private static final String[] AUTH_WHITELIST = {
        // -- swagger ui
        "/api/register",
        "/actuator/shutdown"
};
person Nagesh Tripathi    schedule 15.07.2020
comment
Он работает, но поскольку csrf не отключен, он дает 403 вместо 401 для доступа без аутентификации. - person Karthik Chennupati; 15.07.2020
comment
да, вам нужно будет обработать csrf, проверьте эту ссылку, если она поможет -csrf - person Nagesh Tripathi; 15.07.2020