在匿名页面上的Spring Security中获取经过身份验证的用户的详细信息,可以通过以下步骤实现:
以下是一个示例代码:
// 配置Spring Security
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
// 其他配置...
}
// 自定义用户详细信息服务
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new CustomUserDetails(user);
}
}
// 自定义用户详细信息对象
public class CustomUserDetails implements UserDetails {
private User user;
public CustomUserDetails(User user) {
this.user = user;
}
// 实现UserDetails接口的方法...
// 其他getter和setter方法...
}
// 在匿名页面的控制器或服务中获取经过身份验证的用户详细信息
@Controller
public class AnonymousController {
@GetMapping("/anonymous")
public String anonymousPage() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
// 获取用户详细信息
String username = userDetails.getUsername();
// 其他操作...
return "anonymousPage";
}
}
这样,你就可以在匿名页面上的Spring Security中获取经过身份验证的用户的详细信息了。请注意,以上示例中的代码仅供参考,具体实现可能因项目需求而有所不同。
领取专属 10元无门槛券
手把手带您无忧上云