gpt4 book ai didi

java - Spring安全认证总是返回401

转载 作者:行者123 更新时间:2023-12-01 16:17:54 24 4
gpt4 key购买 nike

我在 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 {
//

}

实现UserDetailsS​​ervice

@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 发送具有良好凭据的身份验证请求,则在调试器模式下一切正常(AuthFilter 和 UserDetailsS​​ervice),但服务器返回 401 并且 Authfilter 中的 successAuthentication 方法不会调用。

<小时/>

收到 POST '/auth/sing-in' 请求:

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

servlet路径:/auth/sing-in路径信息:空标题:内容类型:应用程序/json用户代理:PostmanRuntime/7.25.0接受:/缓存控制:无缓存 postman token :c5bb3320-9c22-4d3d-93e9-628fe0e6f82a主机:本地主机:9000接受编码:gzip、deflate、br连接:保持 Activity 状态内容长度:54

安全过滤器链:[WebAsyncManager集成过滤器安全上下文持久性过滤器 header 写入过滤器注销过滤器认证过滤器授权过滤器请求缓存感知过滤器SecurityContextHolderAwareRequestFilter匿名认证过滤器 session 管理过滤器异常翻译过滤器过滤器安全拦截器]

<小时/>

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 安全调试器:

<小时/>

收到 POST '/error' 请求:

org.apache.catalina.core.ApplicationHttpRequest@fafe057

servlet路径:/错误路径信息:空标题:内容类型:应用程序/json用户代理:PostmanRuntime/7.25.0接受:/缓存控制:无缓存 postman token :c5bb3320-9c22-4d3d-93e9-628fe0e6f82a主机:本地主机:9000接受编码:gzip、deflate、br连接:保持 Activity 状态内容长度:54

安全过滤器链:[WebAsyncManager集成过滤器安全上下文持久性过滤器 header 写入过滤器注销过滤器认证过滤器授权过滤器请求缓存感知过滤器SecurityContextHolderAwareRequestFilter匿名认证过滤器 session 管理过滤器异常翻译过滤器过滤器安全拦截器]

<小时/>

最佳答案

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 不会调用”。您能否使用以下命令在 Debug模式下共享堆栈跟踪

@EnableWebSecurity(debug = true)

关于java - Spring安全认证总是返回401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62357892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com