我在spring中遇到了一个身份验证的问题,我有一个身份验证过滤器的扩展UsernamePasswordAuthenticationFilter。
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
private final RefreshTokenProvider refreshTokenProvider;
private final AccessTokenProvider accessTokenProvider = new AccessTokenProvider();
public AuthenticationFilter(AuthenticationManager authenticationManager, RefreshTokenProvider refreshTokenProvider) {
this.authenticationManager = authenticationManager;
this.refreshTokenProvider = refreshTokenProvider;
setFilterProcessesUrl(SecurityConstants.AUTH_SIGN_IN_PATH);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
try {
SingInRequest singInRequest = new ObjectMapper().readValue(request.getInputStream(), SingInRequest.class);
UsernamePasswordAuthenticationToken authRequest =
new UsernamePasswordAuthenticationToken(singInRequest.getUsername(), singInRequest.getPassword());
return authenticationManager.authenticate(authRequest);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain,
Authentication auth) throws IOException, ServletException {
//
}
实现UserDetailsService
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final PasswordEncoder encoder;
private final UserQueryRepository userQueryRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userQueryRepository.findUserByUsername(username)
.map(this::getUserDetails)
.orElseThrow(() -> new UsernameNotFoundException("User with username " + username + " not found"));
}
private UserDetails getUserDetails(UserDto user) {
return org.springframework.security.core.userdetails.User.builder()
.username(user.getUsername())
.authorities(convertAuthorities(user))
.password(encoder.encode(user.getPassword()))
.disabled(!user.isActive())
.build();
}
private List<GrantedAuthority> convertAuthorities(UserDto user) {
return user.getRoles().stream().map(role ->
new SimpleGrantedAuthority(role.toString())
).collect(Collectors.toList());
}
}
而SecurityConfig类
@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserQueryRepository userQueryRepository;
private final RefreshTokenProvider refreshTokenProvider;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/book/**").authenticated()
.and()
.addFilter(new AuthenticationFilter(authenticationManager(), refreshTokenProvider))
.addFilter(new AuthorizationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl(passwordEncoder(), userQueryRepository);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration corsConfiguration = new CorsConfiguration();
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
corsConfiguration.addAllowedOrigin("http://localhost:3000");
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
如果我尝试用postman发送一个具有良好凭证的auth请求,在调试器模式下,一切都很好(AuthFilter和UserDetailsService),但服务器返回401,而且Authfilter中的successfulAuthentication方法没有被调用。
在successfulAuthentication()方法中没有任何内容。它应该是这样的。
@Override
protected void successfulAuthentication(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain,
Authentication auth) throws IOException, ServletException {
super.successfulAuthentication(req, res, chain, auth);
chain.doFilter(req, res);
}
对不起,我没有注意到 "successfulAuthentication没有被调用"。你能不能分享一下在调试模式下的堆栈跟踪,使用的是
@EnableWebSecurity(debug = true)
收到POST'authsing-in'的请求。
org.apache.catalina.connector.RequestFacade@27b774b2。
servletPath:authsing-inpathInfo:nullheaders: content-type: applicationjsonuser-agent: PostmanRuntime7.25.0accept: cache-control: no-cachepostman-token: c5bb3320-9c22-4d3d-93e9-628fe0e6f82ahost: localhost:9000accept-encoding: gzip, deflate, brconnection: keep-alivecontent-length: 54。
安全过滤器链:[WebAsyncManagerIntegrationFilter SecurityContextPersistenceFilter HeaderWriterFilter LogoutFilter AuthenticationFilter AuthorizationFilter RequestCacheAwareFilter SecurityContextHolderAwareRequestFilter AnonymousAuthenticationFilter SessionManagementFilter ExceptionTranslationFilter FilterSecurityInterceptor] 。
2020-06-13 20:52:42.048 INFO 9956 --- [nio-9000-exec-2] org.mongodb.driver.connection : 打开连接[connectionId{localValue:2, serverValue:126}]到127.0.0.1:270172020-06-13 20:52:42.258 INFO 9956 --- [nio-9000-exec-2] Spring Security Debugger .Spring安全调试器。
收到POST'错误'请求。
org.apache.catalina.core.ApplicationHttpRequest@fafe057。
servletPath:errorpathInfo:nullheaders: content-type: applicationjsonuser-agent: PostmanRuntime7.25.0accept: cache-control: no-cachepostman-token: c5bb3320-9c22-4d3d-93e9-628fe0e6f82ahost: localhost:9000accept-encoding: gzip, deflate, brconnection: keep-alivecontent-length: 54。
安全过滤器链:[WebAsyncManagerIntegrationFilter SecurityContextPersistenceFilter HeaderWriterFilter LogoutFilter AuthenticationFilter AuthorizationFilter RequestCacheAwareFilter SecurityContextHolderAwareRequestFilter AnonymousAuthenticationFilter SessionManagementFilter ExceptionTranslationFilter FilterSecurityInterceptor] 。