簡體   English   中英

Spring Boot Web應用程序中的JWT過濾器和Spring安全控制流

[英]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具有兩個字段userNamepassword

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.

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