未调用自定义身份验证提供程序

时间:2014-03-17 11:51:08

标签: java spring spring-security

我尝试使用Spring Security设置客户身份验证提供程序,但没有太多运气让它运行起来。我使用 Java配置,所以我可能遗漏了一些简单的东西,但由于大多数学习材料都是基于XML配置的,所以它不会向我跳出来。

这是使用Spring v4.0.1.RELEASE但使用Spring Security v3.2.2.RELEASE。版本号可能会发生冲突吗?

据我所知,我所要做的就是创建我的提供者:

public class KBServicesAuthProvider implements AuthenticationProvider {
  @Autowired
  private ApplicationConfig applicationConfig;

  @Autowired
  private SessionServiceClient sessionServiceClient;

  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String email = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();

    try {
      KBSessionInfo sessionInfo = sessionServiceClient.login(applicationConfig.getKbServicesPresenceId(), email,
          password);

      List<GrantedAuthority> grantedRoles = new ArrayList<>();
      for (KBRoleMembership role : sessionInfo.getAuthenticatedUser().getRoleMemberships()) {
        grantedRoles.add(new SimpleGrantedAuthority(role.getRoleId()));
      }

      return new UsernamePasswordAuthenticationToken(email, password, grantedRoles);
    } catch (InvalidSessionException e) {
      throw new AuthenticationCredentialsNotFoundException("Username or password was not accepted", e);
    }
  }

  @Override
  public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
  }
}

然后设置一个类来描述我的安全设置。此类链接在我的提供者中:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired(required = true)
  SessionServiceClient sessionServiceClient;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated();
    http.formLogin().loginPage("/login").permitAll().and().logout().permitAll();
  }

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

  @Bean
  protected AuthenticationProvider getKBServicesAuthenticationProvider() {
    return new KBServicesAuthProvider();
  }
}

但是我没有在日志中看到任何内容。没有一个我的调试点被击中。该应用程序的行为是不安全的(所以我仍然可以访问各种URL等。)

关于我应该检查什么的任何想法?

9 个答案:

答案 0 :(得分:7)

这可能不是完整的答案,因为我自己也在努力解决这个问题。我正在使用自定义身份验证提供程序和自定义用户详细信息服务。我看到了与您相同的行为 - 断点在我的用户详细信息服务中被点击,但在我的身份验证提供程序中没有。这是我整个配置类的样子:

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        AuthenticationProvider rememberMeAuthenticationProvider = rememberMeAuthenticationProvider();
        TokenBasedRememberMeServices tokenBasedRememberMeServices = tokenBasedRememberMeServices();

        List<AuthenticationProvider> authenticationProviders = new ArrayList<AuthenticationProvider>(2);
        authenticationProviders.add(rememberMeAuthenticationProvider);
        authenticationProviders.add(customAuthenticationProvider);
        AuthenticationManager authenticationManager = authenticationManager(authenticationProviders);

        http
                .csrf().disable()
                .headers().disable()
                .addFilter(new RememberMeAuthenticationFilter(authenticationManager, tokenBasedRememberMeServices))
                .rememberMe().rememberMeServices(tokenBasedRememberMeServices)
                .and()
                .authorizeRequests()
                .antMatchers("/js/**", "/css/**", "/img/**", "/login", "/processLogin").permitAll()
                .antMatchers("/index.jsp", "/index.html", "/index").hasRole("USER")
                .antMatchers("/admin", "/admin.html", "/admin.jsp", "/js/saic/jswe/admin/**").hasRole("ADMIN")
                .and()
                .formLogin().loginProcessingUrl("/processLogin").loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll()
                .and()
                .exceptionHandling().accessDeniedPage("/login")
                .and()
                .logout().permitAll();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/img/**");
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(List<AuthenticationProvider> authenticationProviders) {
        return new ProviderManager(authenticationProviders);
    }

    @Bean
    public TokenBasedRememberMeServices tokenBasedRememberMeServices() {
        return new TokenBasedRememberMeServices("testKey", userDetailsService);
    }

    @Bean
    public AuthenticationProvider rememberMeAuthenticationProvider() {
        return new org.springframework.security.authentication.RememberMeAuthenticationProvider("testKey");
    }

    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}

我刚刚发现如果我专门将我的身份验证提供程序添加到HttpSecurity对象中,我的断点就开始受到攻击:

http
                .csrf().disable()
                .headers().disable()
                .authenticationProvider(customAuthenticationProvider)

我的目标是让BCryptPasswordEncoder工作,而不是使用此配置 - 一切都返回为错误的凭据。无论如何,只是想我会分享。

答案 1 :(得分:6)

我遇到了同样的问题,问题在于你的方法总是会返回false。

<Slider minValue="{{ minAmount }}" maxValue="{{ maxAmount }}" value="{{ amount }}" />

将上述方法更改为以下方法,问题将得到解决。

@Override
public boolean supports(Class<?> authentication) {
      return authentication.equals
  (UsernamePasswordAuthenticationToken.class);
}

答案 2 :(得分:3)

您忘记了@Autowired注释。

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

此外,您可能想要删除.antMatchers("/").permitAll()

@Override
protected void configure(HttpSecurity http) throws Exception {
  http.authorizeRequests().anyRequest().authenticated();
  http.formLogin().loginPage("/login").permitAll().and().logout().permitAll();
}

答案 3 :(得分:2)

我有同样的问题(我的自定义身份验证提供程序没有被点击)并在阅读Why is Spring Security working in Tomcat but not when deployed to Weblogic?之后通过引入 springSecurityFilterChain 解决了这个问题 所以我的问题可能与WebServer有特殊关系,但我在Tomcat上也有自定义身份验证提供程序问题,并检查我的配置现在在Tomcat上工作。

我使用Spring boot 1.4.1版本,其中包含Spring 4.3.3和Spring Security 4.1.3以及Traditional deployment

我针对 Tomcat v9.0 以及 WebLogic 12c R2 测试了我的配置,并检查了它对两者的影响。 希望这至少对使用Tomcat的人有帮助。

以下是我从主类开始的配置。

<强> Application.java

public class Application {
    public static void main( String[] args ) {
        SpringApplication.run(new Class[] {AppConfig.class, Initializer.class, SecurityInitializer.class}, args);
    }
}

<强> Initializer.java

public class Initializer extends SpringBootServletInitializer implements WebApplicationInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(AppConfig.class);
    }

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(WebConfig.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("my-servlet", new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }
}

这里,AbstractSecurityWebApplicationInitializer正在从onStartup方法构建 springSecurityFilterChain 。我没有实现任何,因为我尝试使用默认配置。

<强> SecurityInitializer.java

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {

}

<强> AppConfig.java

@Configuration
@EnableAutoConfiguration
@EnableScheduling
@EnableMBeanExport
@EnableAsync
@EnableAspectJAutoProxy
@ComponentScan("com.my.package")
public class AppConfig {


}

<强> SecurityConfig.java

@Configuration
@EnableWebSecurity
@ComponentScan("com.my.package")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestfulRemoteAuthenticationProvider restfulRemoteAuthenticationProvider;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }
}

<强> WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.my.controller.package")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver internalViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setOrder(1);
        return viewResolver;
    }
}

这是我的自定义身份验证提供程序,通过Restful request

从其他组件获取身份验证信息

RestfulRemoteAuthenticationProvider.java

@Component
public class RestfulRemoteAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private ManagementClientAdapterFactory managementClientAdapterFactory;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        // my logic to get and configure authSource which is my environment specific thing, also same for RemoteAuthRequestResult

        RemoteAuthRequestResult result = (RemoteAuthRequestResult)authSource.sendRequest();
        if(result.isAuthenticated()) {
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            return new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
        }
        throw new BadCredentialsException("User not found by given credential");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

答案 4 :(得分:1)

   Something like should be present in java config 
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class HelloMethodSecurityConfig {
}

答案 5 :(得分:1)

@EnableWebMvcSecurity将在4.0 https://jira.spring.io/browse/SEC-2790

中弃用

您可能需要重新考虑配置。

答案 6 :(得分:0)

<security:global-method-security pre-post-annotations="enabled"/>

答案 7 :(得分:0)

我遇到了类似的问题,这是因为我使用了@ Autowire-ed AuthenticationManager实例,该实例是由Spring Boot构建的,并且根本不包含我的自定义AuthenticationProvider

经过两天的调试,我终于意识到,这与我在自定义org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#authenticationManager()WebSecurityConfigurerAdapter中配置的WebSecurityConfigurerAdapter#configure(AuthenticationManagerBuilder)的管理器不同。

现在,我只需从WebSecurityConfigurerAdapter#authenticationManager()获取此实例,然后将其传递给我的GenericFilterBean,即可处理我的身份验证逻辑。效果很好。

答案 8 :(得分:0)

此外,请确保您发送的用户名和密码带有正确的标题。

在下面测试curl,并检查是否已调用该类

curl -X GET \   http://localhost:8080 \   -H'授权:基本cmdlbGxtYW5AYnIuaWJtLmNvbTphYmM ='\   -H'X-Requested-With:XMLHttpRequest'\   -H'cache-control:no-cache'