![](/img/trans.png)
[英]Spring Security with Custom AuthenticationProvider Custom UserDetails and Custom Security Context
[英]How to cast UserDetails in Spring Security context?
我有一個這樣的客戶類
public class MyCustomer {
public String username;
public String email;
public String password;
}
我有一個類服務,它實現了UserDetailsService
@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();
不可以,因為不能將User
MyCustomer
為MyCustomer
所以無法使用。
除了創建User
實例,您還可以讓MyCustomer
類實現UserDetails
接口。
public class MyCustomer implements UserDetails {
// implementation of UserDetails methods
}
然后,您只需從UserDetailsService返回MyCustomer
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.