java 如何为Spring应用程序添加Basic Auth?[关闭]

zdwk9cvp  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(65)

已关闭。此问题需要更多focused。目前不接受回答。
**要改进此问题吗?**更新此问题,使其仅针对editing this post的一个问题。

4天前关闭。
Improve this question
我在Sping Boot 3.2.0上有一个简单的应用程序。我有设置安全性。我的配置文件:

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

@Bean
public UserDetailsService userDetailsService() {
    return new MyUserDetailService();
  }

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

@Bean
public AuthenticationProvider authenticationProvider(){
    DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
    daoAuthenticationProvider.setUserDetailsService(userDetailsService());
    daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
    return  daoAuthenticationProvider;
  }

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
    return httpSecurity.csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(auth -> auth.requestMatchers("/health", "/api/v1/user/new").permitAll()
                    .requestMatchers("/**").authenticated())
            .formLogin(AbstractAuthenticationFilterConfigurer::permitAll)
            .build();
  }
}

字符串
我已经添加了管理员用户。我可以通过浏览器使用我添加的凭据访问我的端点

@GetMapping("/user")
public List<User> getAllUsers(){
    return userService.getAllUsers();
}


的数据


但是我怎么能从 Postman 那里得到同样的结果呢?如果我在Basic Auth中添加了相同的凭据,它就不起作用了。响应只是登录表单页面

of1yzvn4

of1yzvn41#

如果您打算在Sping Boot 中仅使用基本身份验证,请考虑将.formLogin()替换为.httpBasic(),或者如果您希望同时使用两者,则将其添加到旁边。
下面是修改后的代码:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
    return httpSecurity.csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(auth -> auth.requestMatchers("/health", "/api/v1/user/new").permitAll()
                    .requestMatchers("/**").authenticated())
            .httpBasic(Customizer.withDefaults())
            .build();
}

字符串

相关问题