Spring在SecurityContextHolder中获取自定义UserDetails

时间:2016-10-08 09:38:09

标签: java spring security

我在我的网络项目中使用SpringSecurity。我有保存在DB中的实体用户。我需要在BD中使用用户ID进行请求,以获取此BD中其他表的任何信息。在Spring Security中进行身份验证后,如何从SecurityContextHolder获取用户而不是标准的Spring用户(此用户还没有id?)

How do I wrap my website to open all links on the WKWebview?

PS.Sorry for my english :)

1 个答案:

答案 0 :(得分:1)

您将在另一个类中实现UserDetailsS​​ervice接口和UserDetails接口。例如:

CustomUserDetailsS​​ervice:

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
    // your UserRepository for your user
    private final UserRepository userRepository;

    @Autowired
    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if (null == user || ! user.getUsername().equals(username)) {
            throw new UsernameNotFoundException("No user present with username: " + username);
        } else {

            return new CustomUserDetails(user);
        }
    }
}

CustomUserDetails:

// You want to extend your User class here
public class CustomUserDetails extends User implements UserDetails {
    private static final long serialVersionUID = 1L;
    private Users user;

    public CustomUserDetails(User user) {
        super(user);
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // You don't talk about UserRoles, so return ADMIN for everybody or implement roles. 
        return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN");
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        // just for example
        return this.user.getActive() == true;
    }

    @Override
    public String getUsername() {
        return this.user.getUsername();
    }

    @Override
    public String getPassword() {
        return this.user.getPassword();
    }

    // Just an example to put some addititional Data to your logged in user

    public String getUserDatabase() {
        return "usertable" + Integer.toString(1 + this.user.getUserId());
    }


}

在你的User类中,为hibernate创建一个空构造函数,并为一个用户实例创建一个构造函数:

@Entity
@Table(name = "users")
public class User{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "name")
    private String name;

    @Column(name = "login")
    private String login;

    @Column(name = "password")
    private String password;

    public User() {}

    public User(User user) {
        this.id = user.getId();
        this.name = user.getName();
        // … the same for all properties.
    }
}

在您的WebSecurityConfig中,@Autowire CustomUserDetailsService并将其注入身份验证流程中:

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final
    UserDetailsService service;

    @Autowired
    public WebSecurityConfig(UserDetailsService service) {
        this.service = service;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(service).passwordEncoder(passwordEncoder());

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //left out because not related here
    }
}

就是这样。您现在可以在每个控制器或提供程序中将经过身份验证的主体转换为CustomUserDetails:

CustomUserDetails userDetails = 
    (CustomUserDetails) SecurityContextHolder
        .getContext()
        .getAuthentication()
        .getPrincipal();