[英]JWT filter and spring security control flow in a Spring boot web application
我對春季安全非常陌生。 我正在嘗試在Web應用程序中實現JWT
過濾器以使其無狀態。 我有一段代碼,當用戶點擊/login
路徑時,控件轉到方法,
public LoginResponse login(
AuthenticationRequest authenticationRequest, Device device )
throws WebappException
{
// Perform the security
final Authentication authentication = authenticationManager
.authenticate(new
UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(),
authenticationRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
/** some more logic**/
在這里,我不了解final Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword()));
的目的final Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword()));
請指導我! AuthenticationRequest
具有兩個字段userName
和password
。
authenticationManager.authenticate()
方法將UsernamePasswordAuthenticationToken
傳遞給AuthenticationProvider
並嘗試使用提供的用戶名和密碼向用戶進行身份驗證。
Authentication
對象, 然后,您可以調用authentication.isAuthenticated()
來了解令牌是否已通過身份驗證。
如果要訪問數據庫以檢查身份驗證,則應使用DaoAuthenticationProvider
實現(或AbstractUserDetailsAuthenticationProvider
)。 它從接口UserDetailsService
檢索用戶詳細信息。 因此,您需要創建一個MyUserDetailsService
類, MyUserDetailsService
實現UserDetailsService
該類將重寫loadUserByUsername(String username)
方法並返回UserDetails
。 UserDetails
包含用戶名,密碼,權限。 創建自己的MyUserdetails
類,該類實現UserDetails
接口。 然后,配置Spring以引用您的cutom類:
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService);
有關更多詳細信息, 請訪問http://www.baeldung.com/spring-security-authentication-with-a-database
或者,您也可以使用JdbcUserDetailsManagerConfigurer直接指定數據源和SQL查詢:
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username, password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, role from user_roles where username=?");
}
關於JWT,我認為您的登錄方法首先檢查用戶的身份驗證,然后應使用用戶詳細信息構建JWT,並將其返回給瀏覽器。 然后,客戶端可以將此令牌重新發送到服務器,並且此JWT將通過另一種方法解密和驗證。 有關https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.