SpringSecurity本身有UsernamePasswordAuthenticationFilter,但我想使用电子邮件而不是用户名。 我曾经使用过这个类这样的用户名:
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
private AuthenticationManager authenticationManager;
private JwtUserDetailsToUserDTOConverter jwtUserDetailsToUserDTOConverter = new JwtUserDetailsToUserDTOConverter();
public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
try {
User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
String token = JwtGenerator.builder().build().generate((JwtUserDetails) authResult.getPrincipal());
response.addHeader(JwtConstants.HEADER,JwtConstants.PREFIX + token);
}
}
我想为电子邮件和密码实施AuthenticationFilter。 SpringSecurity中没有任何指定的此类意图类。 如何为电子邮件自定义它?
答案 0 :(得分:1)
所以你有几个选择:
创建一个自定义UserDetailsService,并重写loadUserByUsername(),它将给定的用户名与用户的电子邮件相匹配。然后可以将其设置为AuthenticationManagerBuilder
实例,如下所示:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(myUserDetailsService);
}
}
自定义AuthenticationProvider,用于根据电子邮件验证用户。这对您的方案来说有点过分,会导致代码重复。但是如果你想这样做,请使用与#1相同的代码,但调用auth.authenticationProvider(myAuthProviderInstance);
代替