【问题标题】:Authentication object is null after bypassing the particular request绕过特定请求后,身份验证对象为空
【发布时间】:2021-03-26 09:05:54
【问题描述】:

我在 webConfigSecurity 类中使​​用以下代码绕过来自客户端的一些请求

@Override
public void configure(WebSecurity webSecurity) throws Exception
{
    webSecurity.ignoring().antMatchers("/adminSettings/get/**")
             .antMatchers("/cases/sayHello/**").antMatchers("/cases/**/downloadPdfFolderPBC/**");
}

在controller api方法中需要用户详细信息进一步执行,而获取用户详细信息时认证对象为null,所以会抛出“用户未通过身份验证”的异常

 public static User get() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
            if (principal == null) {
                throw new InsufficientAuthenticationException("User not authenticated");
            }
            return principal.getUser();
        }
        throw new AuthenticationCredentialsNotFoundException("User not authenticated");
    }

我是 Spring Security 的新手,在这种情况下,我应该如何获取登录的用户详细信息

【问题讨论】:

  • 请求如何被认证? Spring Security 本质上是一组请求过滤器,用于拦截和验证凭据 - 如果您未在请求中提供凭据,则 Spring Security 无需进行验证。
  • 使用 json webtokens 对每个请求进行身份验证。就我而言,我绕过了该请求。绕过认证后为空。
  • 如果你为一个给定的请求绕过了 Spring Security,那么就没有设置SecurityContextHolderignoring() 表示“Spring Security 不应该对这个请求做任何事情”。

标签: spring-boot spring-security spring-security-oauth2 jwt-auth spring-security-rest


【解决方案1】:

而不是 ignoring(),这会导致 Spring Security 跳过这些请求,我相信您想使用 permitAll(),而不是像这样:

@Override
public void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests((requests) -> requests
            .antMatcher("/adminSettings/get/**").permitAll()
            .antMatcher("/cases/sayHello/**").permitAll()
            // ... etc
            .anyRequest().authenticated()
        )
        .formLogin(Customizer.withDefaults());
}

通过这种方式,Spring Security 仍将使用登录用户填充SecurityContextHolder,但所有permitAll 端点都不需要身份验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 2014-12-20
    • 1970-01-01
    • 2019-07-09
    相关资源
    最近更新 更多