簡體   English   中英

如何在Spring Security上下文中強制轉換UserDetails?

[英]How to cast UserDetails in Spring Security context?

我有一個這樣的客戶類

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();

不可以,因為不能將User MyCustomerMyCustomer所以無法使用。

除了創建User實例,您還可以讓MyCustomer類實現UserDetails接口。

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

然后,您只需從UserDetailsS​​ervice返回MyCustomer實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM