Spring 安全身份验证始终返回 401



我在春季的身份验证方面遇到了问题。 我有身份验证过滤器扩展用户名密码身份验证过滤器。

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 {
//
}

实施用户详细信息服务

@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;
}

如果我尝试使用邮递员发送具有良好凭据的身份验证请求,在调试器模式下一切正常(AuthFilter 和 UserDetailsService(,但服务器返回 401 并且 Authfilter 中的成功身份验证方法不会调用。


收到的开机自检"/身份验证/唱入"请求:

org.apache.catalina.connector.RequestFacade@27b774b2

servletPath:/auth/sing-in 路径信息:空 头: 内容类型:应用程序/JSON 用户代理:邮递员运行时/7.25.0 接受:/缓存控制:无缓存 邮递员令牌: c5bb3320-9c22-4d3d-93e9-628fe0e6f82a 主机:本地主机:9000 接受编码:gzip、deflate、br 连接:保持活动状态 内容长度:54

安全筛选器链:[ WebAsyncManagerIntegrationFilter SecurityContextPersistenceFilter 标头编写器筛选器 注销筛选器 身份验证筛选器 授权过滤器 RequestCacheAwareFilter SecurityContextHolderAwareRequestFilter 匿名身份验证筛选器 会话管理筛选器 异常翻译过滤器 过滤器安全拦截器 ]


2020-06-13 20:52:42.048 信息 9956 --- [nio-9000-exec-2] org.mongodb.driver.connection:打开的连接 [connectionId{localValue:2, serverValue:126}] 到 127.0.0.1:27017 2020-06-13 20:52:42.258 信息 9956 --- [NIO-9000-exec-2] Spring 安全调试器:

收到

收到的开机自检"/错误"请求:

org.apache.catalina.core.ApplicationHttpRequest@fafe057

servletPath:/error 路径信息:空 头: 内容类型:应用程序/JSON 用户代理:邮递员运行时/7.25.0 接受:/缓存控制:无缓存 邮递员令牌: c5bb3320-9c22-4d3d-93e9-628fe0e6f82a 主机:本地主机:9000 接受编码:gzip、deflate、br 连接:保持活动状态 内容长度:54

安全筛选器链:[ WebAsyncManagerIntegrationFilter SecurityContextPersistenceFilter 标头编写器筛选器 注销筛选器 身份验证筛选器 授权过滤器 RequestCacheAwareFilter SecurityContextHolderAwareRequestFilter 匿名身份验证筛选器 会话管理筛选器 异常翻译过滤器 过滤器安全拦截器 ]

<小时 />

successAuthentication(( 方法中没有任何内容。它应该看起来像这样。

@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);
}

抱歉,我没有注意到"成功身份验证不调用"。您能否使用

@EnableWebSecurity(debug = true)

相关内容

  • 没有找到相关文章

最新更新