在一层中设置登录UserDetails,并在任意Java MVC的DAO层中访问它,可以通过以下步骤实现:
下面是一个示例代码:
// CustomUserDetailsService.java
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
}
private Collection<? extends GrantedAuthority> getAuthorities(User user) {
List<GrantedAuthority> authorities = new ArrayList<>();
// Add user roles to authorities
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
}
// UserDao.java
@Repository
public class UserDao {
// DAO methods to access user data from the database
// ...
public User findByUsername(String username) {
// Implement the logic to find a user by username
// ...
}
}
// Example usage in a DAO method
@Repository
public class ExampleDao {
@Autowired
private CustomUserDetailsService userDetailsService;
public void exampleMethod() {
// Get the current logged-in user's details
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
// Access the user's details
String userRole = userDetails.getAuthorities().iterator().next().getAuthority();
// ...
}
}
在上述示例中,CustomUserDetailsService类实现了UserDetailsService接口,并通过@Autowired注解注入了UserDao类。在loadUserByUsername方法中,通过调用UserDao的findByUsername方法获取用户信息,并将其封装到UserDetails对象中返回。
在ExampleDao类中的exampleMethod方法中,通过SecurityContextHolder获取当前登录用户的用户名,并调用CustomUserDetailsService的loadUserByUsername方法获取UserDetails对象。然后可以根据需要访问UserDetails对象中的信息,例如获取用户角色。
请注意,上述示例中的代码仅为演示目的,并未涉及具体的数据库操作和安全控制。实际应用中,需要根据具体的业务需求和安全要求进行适当的修改和扩展。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云