2014-10-18 53 views
0

我有一个类Customer类这样如何在Spring Security上下文中投射UserDetails?

public class MyCustomer { 
    public String username; 
    public String email; 
    public String password; 
} 

,我有一个一流的服务,这是实现的UserDetailsS​​ervice

@Override 
public UserDetails loadUserByUsername(String username) 
      throws UsernameNotFoundException, DataAccessException 
{ 
    MyCustomer customer = customerDao.findByName(username); 
    return new User(customer.getName(), customer.getEmail(), true, true, true, true, customer.getRoles()) 
} 

我怎样才能在控制类MyCustomer?我已经尝试过,但不幸的是,它不起作用。

MyCustomer customer = (MyCustomer)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 

回答

0

不,这是行不通的,因为User不能转换为MyCustomer

而不是创建User实例,可以让您的MyCustomer类实现UserDetails接口。

public class MyCustomer implements UserDetails { 
    // implementation of UserDetails methods 
} 

然后,您只需从UserDetailsS​​ervice返回MyCustomer实例。

相关问题