การรักษาความปลอดภัยแบบสปริงให้ 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

เราใช้แนวทางที่คล้ายกันตามที่ Supun กล่าวไว้ข้างต้น

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 ตรวจสอบลิงค์นี้ถ้ามันช่วยได้ stackoverflow.com/questions/40929943/spring-boot -csrf - person Nagesh Tripathi; 15.07.2020