Мое приложение построено с использованием jhipster UAA и архитектуры микросервиса.
Я реализовал UserDetailsService и возвращаю пользовательский объект UserDetails. А также я настроил свой конструктор диспетчера аутентификации для использования этого настроенного UserDetailsService, все это происходит внутри UAA Spring Boot oAuth2, который является отдельной службой.
Но, тем не менее, каждый раз, когда я пытаюсь получить доступ к getPricipal () через SecurityContextHolder, я получаюстрока (имя пользователя) вместо объекта UserDetails ....
Пожалуйста, помогите ....?
DomainUserDetailsService
import com.abuzz.sso.repository.UserRepository;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* Authenticate a user from the database.
*/
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
if (new EmailValidator().isValid(login, null)) {
return userRepository.findOneByEmailIgnoreCase(login)
.map(CustomUserDetails::new)
.orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
}
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository.findOneByLogin(lowercaseLogin)
.map(CustomUserDetails::new)
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));
}
}
CustomUserDetails
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
public class CustomUserDetails extends User {
private final Set<String> clients;
private final Set<String> sites;
public CustomUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities, Set<String> clients, Set<String> sites) {
super(username, password, authorities);
this.clients = clients;
this.sites = sites;
}
public CustomUserDetails(com.abuzz.sso.domain.User user) {
super(
user.getLogin(),
user.getPassword(),
user.getActivated(),
true,
true,
true,
user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList())
);
this.clients = user.getClients();
this.sites = user.getSites();
}
public Set<String> getClients() {
return clients;
}
public Set<String> getSites() {
return sites;
}
}
UaaWebSecurityConfiguration
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class UaaWebSecurityConfiguration extends WebSecurityConfigurerAdapter implements InitializingBean {
private final UserDetailsService userDetailsService;
private final AuthenticationManagerBuilder authenticationManagerBuilder;
public UaaWebSecurityConfiguration(UserDetailsService userDetailsService, AuthenticationManagerBuilder authenticationManagerBuilder) {
this.userDetailsService = userDetailsService;
this.authenticationManagerBuilder = authenticationManagerBuilder;
}
@Override
public void afterPropertiesSet() throws Exception {
try {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
} catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e);
}
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**")
.antMatchers("/h2-console/**");
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}