簡體   English   中英

spring-boot 未調用自定義 UserDetailsService

[英]Custom UserDetailsService is not called by spring-boot

我正在嘗試在 spring-security 中使用UserDetailsService spring-security來實現我的身份驗證邏輯。 但是,在 HTTP 請求期間不會調用UserDetailsService ervice。 這是代碼:

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        Optional<User> user = userService.getById(Long.parseLong(userId));
        if (user.isEmpty()) {
            throw new UsernameNotFoundException("User " + userId + " not found");
        }
        return new org.springframework.security.core.userdetails.User(
                user.get().getName(),
                user.get().getHashedPassword(),
                List.of());
    }
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService customUserDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {  // (2)
        http.authorizeRequests()
            .antMatchers("/user/add", "/user/loginByEmail").permitAll() // (3)
            .anyRequest().authenticated()
            .and()
            .logout()
            .permitAll()
            .and()
            .httpBasic();
    }

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

我用一個測試來測試認證邏輯,這里是測試代碼的核心:

MvcResult addMvcResult = mockMvc.perform(post("/habit/friend/addById")
                .with(SecurityMockMvcRequestPostProcessors.httpBasic("Joey", "password"))
                .contentType("application/json")
                .content(StringUtils.toJSONString(addFriendRequestByIdDTO)))
        .andExpect(status().isOk())
        .andReturn();

日志顯示驗證header是通過spring-test插入的:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /habit/friend/addById
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"47", Authorization:"Basic Sm9leTpwYXNzd29yZA=="]
             Body = {
  "currentUserId" : 1,
  "friendUserId" : 2
}
    Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@3a48c398}

但是,身份驗證失敗,我得到了 403,並且從未調用過CustomUserDetailsService 為什么?

您的問題似乎是 CSRF 而不是 UserDetailsService 的實現未注冊,從 Spring 4.x 開始,默認情況下啟用 CSRF 保護,除非您將其關閉

http
    .csrf()
    .disable()

你會得到 403 錯誤。

暫無
暫無

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

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