【问题标题】:Spring security - Custom AuthenticationProvider not working - Java ConfigSpring security - 自定义 AuthenticationProvider 不起作用 - Java Config
【发布时间】:2017-01-09 20:36:53
【问题描述】:

我已经为标题中的问题苦苦挣扎了几天,我很沮丧。我不知道我做错了什么以及为什么我的实现不起作用。

让我告诉你我有什么:

自定义身份验证提供者:

@Component
public class AuthProvider implements AuthenticationProvider {

    private Logger logger = LoggerFactory.getLogger(AuthProvider.class);

    public AuthProvider() {
        logger.info("Building...");
    }

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        logger.info("Authenticate...");
        return null;
    }

    public boolean supports(Class<?> authentication) {
        logger.info("Supports...");
        return true;
    }
}

网络安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthProvider authProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests().anyRequest().authenticated();
    }
}

如您所见,我已将记录器添加到 AuthenticationProvider 中,但没有任何一个被调用。

我尝试过的:

  • @Autowired 添加到configure AuthenticationManagerBuilder 所在的位置
  • @EnableGlobalMethodSecurity(prePostEnabled=true) 添加到课程中
  • 将自定义AuthenticationProvider直接添加到HttpSecurity

我是如何测试它的:

  • 通过 IntelliJ 调试 - 没有结果,没有调用断点。
  • 运行应用程序并发送请求 - 也没有结果,没有日志,什么都没有。

请大家帮帮我。我没力气了。我讨厌把这么多时间浪费在应该可行的事情上:(

【问题讨论】:

  • @dur 如果出现此问题,是否需要此信息?我现在没有任何身份验证,这就是我想创建自己的 AuthProvider 的原因。我打算对 JWT 进行身份验证。
  • @dur 403 禁止访问。
  • @dur http.authorizeRequests().anyRequest().authenticated(); 没有对所有请求进行身份验证?我认为我没有正确理解它:D
  • 这就是为什么你得到一个 403 的原因。如果你使用 permitAll 你也会得到一个匿名用户的 200。在你自己写AuthenticationProvider之前,你应该学习一下Spring Security的核心概念,请阅读Spring Security Reference
  • 这听起来很合理。无论如何,感谢您指出这一点,并抱歉占用您的时间!我认为我理解正确:)

标签: java spring security authentication spring-security


【解决方案1】:

您可能错过了 WebSecurityConfigurerAdapter 中的以下方法:

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

同样的事情发生在我身上。

【讨论】:

    【解决方案2】:

    使用isAssignableFrom() 方法而不是==equals 我们得到一个真实的,然后流将通过authenticate()

    override fun supports(authentication: Class<*>): Boolean {
        return UsernamePasswordAuthenticationToken::class.java.isAssignableFrom(authentication)
    }
    

    GL

    Source

    【讨论】:

      猜你喜欢
      • 2014-10-06
      • 2015-06-17
      • 2017-05-27
      • 2012-01-28
      • 2016-12-07
      • 2015-12-06
      • 2016-04-21
      • 2015-10-21
      • 1970-01-01
      相关资源
      最近更新 更多