代码之家  ›  专栏  ›  技术社区  ›  Naanavanalla

spring boot web应用程序中的JWT过滤器和spring安全控制流

  •  0
  • Naanavanalla  · 技术社区  · 8 年前

    JWT 过滤我的web应用程序,使其无状态。我有一段代码,当用户点击 /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()));

    AuthenticationRequest 有两个字段 userName password

    1 回复  |  直到 8 年前
        1
  •  1
  •   Marsu    8 年前

    这个 authenticationManager.authenticate() 方法通过 UsernamePasswordAuthenticationToken AuthenticationProvider

    • 它返回一个 Authentication

    然后你可以打电话 authentication.isAuthenticated() 了解令牌是否已通过身份验证。

    DaoAuthenticationProvider 实施(或 AbstractUserDetailsAuthenticationProvider ). 它从界面检索用户详细信息 UserDetailsService . 所以你需要创建一个类 MyUserDetailsService 哪些实现了 覆盖 loadUserByUsername(String username) 方法和返回 UserDetails 用户详细信息 包含用户名、密码和权限。创建自己的 MyUserdetails 实现的类 用户详细信息 然后,配置Spring以引用cutom类:

    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(myUserDetailsService);
    

    更多详细信息 http://www.baeldung.com/spring-security-authentication-with-a-database

    或者,您也可以使用JDBCUserDetailsManager配置器直接指定数据源和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将通过另一种方法进行解密和验证。 有关的更多信息 https://www.toptal.com/java/rest-security-with-jwt-spring-security-and-java

    推荐文章