gpt4 book ai didi

java - spring-boot 不调用自定义 UserDetailsS​​ervice

转载 作者:行者123 更新时间:2023-12-05 04:22:59 25 4
gpt4 key购买 nike

我正在尝试使用 spring-security 中的 UserDetailsS​​ervice 来实现我的身份验证逻辑。但是,在 HTTP 请求期间不会调用 UserDetailsS​​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();

日志显示认证头是由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,并且从未调用过 CustomUserDetailsS​​ervice。为什么?

最佳答案

您的问题似乎出在 CSRF 而不是 UserDetailsS​​ervice 的实现未注册,从 Spring 4.x 开始,默认情况下启用 CSRF 保护,除非您将其关闭

http
.csrf()
.disable()

您将收到 403 错误。

关于java - spring-boot 不调用自定义 UserDetailsS​​ervice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73836549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com