程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Spring Security 返回 200 而不是 HttpWebHandlerAdapter 所述的 401大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Spring Security 返回 200 而不是 httpWebHandlerAdapter 所述的 401?

开发过程中遇到Spring Security 返回 200 而不是 httpWebHandlerAdapter 所述的 401的问题如何解决?下面主要结合日常开发的经验,给出你关于Spring Security 返回 200 而不是 httpWebHandlerAdapter 所述的 401的解决方法建议,希望对你解决Spring Security 返回 200 而不是 httpWebHandlerAdapter 所述的 401有所启发或帮助;

试图弄清楚我是否刚刚在 Spring Security 中发现了一个错误,这是针对最新的 2.4.5 版本。 httpWebHandlerAdapter 声明它在日志中返回 401,而 Postman 中的响应是 200。以下是相关的 spring 安全配置/处理程序等。

Spring 安全配置

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity(proxyTargetClass = truE)
@requiredArgsConstructor
public class SecurityConfig {
  private final JwtAuthenticationConverter jwtAuthenticationConverter;
  private final UsersRepository usersRepository;
  private final UserRolesRepository userRolesRepository;
  private final RoleScopesRepository roleScopesRepository;
  private final JwtUtil jwtUtil;

  private static Map<httpR_923_11845@ethod,String[]> AUTH_WHITEList =
      Map.of(
          // Public auth endpoints
          httpR_923_11845@ethod.PUT,new String[] {"/v1/auth/login"},httpR_923_11845@ethod.POST,new String[] {"/v1/auth/register"},httpR_923_11845@ethod.GET,new String[] {
                // Actuator
                "/actuator","/actuator/health*","/actuator/info",// SpringFox/OpenAPI
                "/v3/API-docs/**","/swagger-ui/**","/swagger-resources/**","/webjars/swagger-ui/**",// Public API endpoints
                "/v1/posts/*/comments/*","/v1/posts/*/comments","/v1/posts/*","/v1/posts"
              });

  @Bean
  public SecurityWebFilterChain securityWebFilterChain(ServerhttpSecurity http) {
    // Build path/verb matchers
    Set<ServerWebExchangeMatcher> matchers = new HashSet<>();
    AUTH_WHITEList.forEach(
        (method,paths) -> matchers.add(ServerWebExchangeMatchers.pathMatchers(method,paths)));
    ServerWebExchangeMatcher[] matchersArray = matchers.toArray(new ServerWebExchangeMatcher[0]);

    return http.addFilterat(
            getAuthenticationWebFilter(matchersArray),SecurityWebFiltersOrder.AUTHENTICATION)
        .authorizeExchange()
        .matchers(matchersArray)
        .permitAll()
        .anyExchange()
        .authenticated()
        .and()
        .formLogin()
        .and()
        .csrf()
        .disable()
        .cors()
        .configurationsource(createCorsConfigsource())
        .and()
        .formLogin()
        .disable()
        .httpBasic()
        .disable()
        .logout()
        .disable()
        .build();
  }

  public CorsConfigurationsource createCorsConfigsource() {
    org.springframework.web.cors.reactive.UrlBasedCorsConfigurationsource source =
        new UrlBasedCorsConfigurationsource();
    CorsConfiguration config = new CorsConfiguration();
    config.addAllowedOrigin("http://localhost:3000");
    config.setAllowedMethods(List.of("OPTIONS","GET","PUT","POST","deletE"));
    source.registerCorsConfiguration("/**",config);
    return source;
  }

  private AuthenticationWebFilter getAuthenticationWebFilter(
      ServerWebExchangeMatcher[] matchersArray) {
    // Create web filter with custom user details service/authentication manager
    AuthenticationWebFilter authenticationWebFilter =
        new AuthenticationWebFilter(new AuthenticationManager(customUserDetailsservice()));
    // Set custom JWT authentication converter
    authenticationWebFilter.setServerAuthenticationConverter(jwtAuthenticationConverter);
    // Negate whiteList to set paths with required authentication
    NegatedServerWebExchangeMatcher negateWhiteList =
        new NegatedServerWebExchangeMatcher(ServerWebExchangeMatchers.matchers(matchersArray));
    authenticationWebFilter.setrequiresAuthenticationMatcher(negateWhiteList);
    // Add failure handler
    authenticationWebFilter.setAuthenticationFailureHandler(new AuthenticationFailureHandler());
    return authenticationWebFilter;
  }

  @Bean
  public passwordEncoder passwordEncoder() {
    return new BCryptpasswordEncoder();
  }

  @Bean
  @PriMary
  public UserDetailsservice customUserDetailsservice() {
    return new UserDetailsservice(
        new Userservice(
            usersRepository,userRolesRepository,roleScopesRepository,passwordEncoder(),jwtUtil));
  }
}

故障处理

@Slf4j
public class AuthenticationFailureHandler implements ServerAuthenticationFailureHandler {
  @OverrIDe
  public Mono<VoID> onAuthenticationFailure(
      WebFilterExchange webFilterExchange,AuthenticationException exception) {
    log.warn(exception.getmessage());
    ServerhttpResponse response = webFilterExchange.getExchange().getResponse();
    response.setStatusCode(httpStatuS.UNAUTHORIZED);
    response.getheaders().addIfAbsent(httpheaders.LOCATION,"/");
    response.setComplete();
    return Mono.error(exception);
  }
}

JWT 身份验证转换器。

@Slf4j
@requiredArgsConstructor
@Component
public class JwtAuthenticationConverter implements ServerAuthenticationConverter {
  private final JwtUtil jwtUtil;

  private Mono<String> extractJwtFromAuthorizationheader(ServerWebExchange exchangE) {
    return Mono.justOrEmpty(exchange.getrequest().getheaders().get(httpheaders.AUTHORIZATION))
        // Remove empty headers/headers with empty String as value
        .filter(
            header ->
                !header.isEmpty()
                    && StringUtils.hasText(header.get(0))
                    && header.get(0).contains("Bearer"))
        .map(header -> header.get(0).replaceAll(AuthConstants.bEARER_PREFIX_REGEX,""))
        .switchIfEmpty(Mono.error(new InvalIDJwtException("InvalID bearer token")));
  }

  @OverrIDe
  public Mono<Authentication> convert(ServerWebExchange exchangE) {
    return Mono.justOrEmpty(exchangE)
        .flatMap(this::extractJwtFromAuthorizationheader)
        .map(jwtUtil::getAuthenticationFromJwt);
  }
}

身份验证管理器

public class AuthenticationManager extends UserDetailsRepositoryReactiveAuthenticationManager {

  public AuthenticationManager(ReactiveUserDetailsservice userDetailsservicE) {
    super(userDetailsservicE);
  }

  @OverrIDe
  public Mono<Authentication> authenticate(Authentication authentication) {
    return authentication.isAuthenticated()
        ? Mono.just(authentication)
        : super.authenticate(authentication);
  }
}

相关日志

2021-05-05 15:41:18.981 DEBUG 1984531 --- [or-http-epoll-3] o.s.w.s.h.ResponseStatusExceptionHandler : [82168f6e-13] Resolved [InvalIDJwtException: Unsupported JWT token: The parsed JWT inDicates it was signed with the HS512 signature algorithm,but the specifIEd signing key of type sun.security.rsa.RSAPublicKeyImpl may not be used to valIDate HS512 signatures.  Because the specifIEd signing key reflects a specific and expected algorithm,and the JWT does not reflect this algorithm,it is likely that the JWT was not expected and therefore should not be trusted.  Another possibility is that the parser was configured with the incorrect signing key,but this cAnnot be assumed for security reasons.] for http POST /v1/posts
2021-05-05 15:41:18.981 DEBUG 1984531 --- [or-http-epoll-3] o.s.w.s.adapter.httpWebHandlerAdapter    : [82168f6e-13] Completed 401 UNAUTHORIZED

解决方法

不是错误,失败处理程序上的 setComplete() 是违规行。日志显示 401 时不再是 200 秒。

大佬总结

以上是大佬教程为你收集整理的Spring Security 返回 200 而不是 HttpWebHandlerAdapter 所述的 401全部内容,希望文章能够帮你解决Spring Security 返回 200 而不是 HttpWebHandlerAdapter 所述的 401所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。