Spring 引导 Web 应用程序中的 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

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

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

然后,可以调用authentication.isAuthenticated()以了解令牌是否已通过身份验证。

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