所以我上课了:
public class CustomUserDetailService implements UserDetailsService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Employee employee = employeeRepository.readEmployee(s);
if(employee != null) {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(employee.getRole().name()));
//how to save employee login and user id????
return new User(employee.getLogin(), employee.getPassword(),true, true, true, true, authorities)
}else {
throw new UsernameNotFoundException("Can't locate employee '" + s + "'");
}
}
}
我使用存储数据的类:
public class CurrentEmployeeParam {
public static Long getCurrentEmployeeId(){
// how to get saved employee login and id???
String employeeId = //something
return Long.parseLong(employeeId);
}
那么如何保存员工信息并从程序中的任何一点获取员工信息?
答案 0 :(得分:0)
如果您使用的是Spring MVC,则可以使用会话范围的bean
答案 1 :(得分:0)
例如,可以使用:
public class AuthenticatedEmployee extends org.springframework.security.core.userdetails.User {
private Long employeeId;
private Long companyId;
public AuthenticatedEmployee(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, Collection<? extends GrantedAuthority> authorities)
throws IllegalArgumentException {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, true, authorities);
}
// setters and getters
}
UserDetails类:
public class CustomUserDetailService implements UserDetailsService {
@Autowired
private EmployeeRepository employeeRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Employee employee = employeeRepository.readEmployee(s);
if(employee != null) {
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(employee.getRole().name()));
AuthenticatedEmployee user = new AuthenticatedEmployee(employee.getLogin(), employee.getPassword(), true, true, true, authorities);
user.setEmployeeId(employee.getId());
user.setCompanyId(employee.getCompany().getId());
return user;
}else {
throw new UsernameNotFoundException("Can't locate employee '" + s + "'");
}
}
}
获取员工信息:
public class CurrentEmployeeParam {
public static Long getCurrentCompanyId() {
return getAuthenticatedEmployee().getCompanyId();
}
public static Long getCurrentEmployeeId() {
return getAuthenticatedEmployee().getEmployeeId();
}
private static AuthenticatedEmployee getAuthenticatedEmployee() {
return (AuthenticatedEmployee) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}