Spring引导Web应用程序中的JWT过滤器和弹簧安全控制流程

时间:2017-08-25 12:39:33

标签: java spring-boot spring-security jwt

我对弹簧安全非常新。我正在尝试在我的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()));

请指导我! AuthenticationRequest有两个字段userNamepassword

1 个答案:

答案 0 :(得分:0)

authenticationManager.authenticate()方法将UsernamePasswordAuthenticationToken传递给AuthenticationProvider,并尝试使用提供的用户名和密码向用户进行身份验证。

  • 如果成功,则返回具有授予权限的Authentication对象,
  • 如果身份验证失败,则会抛出异常。

然后,您可以致电authentication.isAuthenticated()以了解令牌是否已经过身份验证。

如果要访问数据库以检查身份验证,则应使用DaoAuthenticationProvider实现(或AbstractUserDetailsAuthenticationProvider)。 它从界面UserDetailsService检索用户详细信息。因此,您需要创建一个类MyUserDetailsService,该类实现UserDetailsService覆盖loadUserByUsername(String username)方法并返回UserDetailsUserDetails包含用户名,密码和权限。创建自己的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

的更多信息