我对弹簧安全非常新。我正在尝试在我的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
有两个字段userName
和password
。
答案 0 :(得分:0)
authenticationManager.authenticate()
方法将UsernamePasswordAuthenticationToken
传递给AuthenticationProvider
,并尝试使用提供的用户名和密码向用户进行身份验证。
Authentication
对象,然后,您可以致电authentication.isAuthenticated()
以了解令牌是否已经过身份验证。
如果要访问数据库以检查身份验证,则应使用DaoAuthenticationProvider
实现(或AbstractUserDetailsAuthenticationProvider
)。
它从界面UserDetailsService
检索用户详细信息。因此,您需要创建一个类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
的更多信息