在Spring Security自訂的UserDetailsService
中取得HttpServletRequest
物件的方法如下。
把自訂的UserDetailsService
註冊為bean,並直接用@Autowired
注入HttpServletRequest
。
例如下面是自訂的DemoUserDetailsService
,類別名稱上掛有@Service
並由Spring Boot掃描並自動註冊為bean,所以可直接透過@Autowired
注入HttpServletRequest
的實例。
DemoUserDetailsService
package com.abc.demo.config;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.core.userdetails.User;
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.Service;
@Service
public class DemoUserDetailsService implements UserDetailsService {
@Autowired
private HttpServletRequest request; // inject
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
...
}
}
參考:
沒有留言:
張貼留言