Spring security Spring Security Java config自定义身份验证提供程序中不工作的服务的自动连接
在我花了一天的时间调试和回顾了关于下面描述的问题的所有现有线程之后,我想我会联系专家。虽然有很多关于这个主题的帖子,但答案要么对我不起作用,要么是特定于XML配置的,所以我决定发布配置细节,看看哪里出了问题。我的整个spring配置都是Java配置,所以没有其他与spring相关的XML文件 问题: 实现Spring Security UserDetails服务的自定义服务的自动连接在自定义身份验证提供程序中不起作用。当我尝试访问服务时,它抛出一个空指针异常(NPE)。我在SecurityConfig上有必要的注释,可以扫描包和根上下文,但这并不能解决问题。启动时没有错误,但访问时失败 我已经在许多线程中回顾并遵循了这些建议,但这些建议似乎非常相关且直接相关 你们任何人的任何帮助都将不胜感激 Spring版本:Spring security Spring Security Java config自定义身份验证提供程序中不工作的服务的自动连接,spring-security,spring-java-config,Spring Security,Spring Java Config,在我花了一天的时间调试和回顾了关于下面描述的问题的所有现有线程之后,我想我会联系专家。虽然有很多关于这个主题的帖子,但答案要么对我不起作用,要么是特定于XML配置的,所以我决定发布配置细节,看看哪里出了问题。我的整个spring配置都是Java配置,所以没有其他与spring相关的XML文件 问题: 实现Spring Security UserDetails服务的自定义服务的自动连接在自定义身份验证提供程序中不起作用。当我尝试访问服务时,它抛出一个空指针异常(NPE)。我在SecurityCon
<!-- Spring -->
<spring-framework.version>4.1.2.RELEASE</spring-framework.version>
<spring-security-web.version>3.2.5.RELEASE</spring-security-web.version>
<spring-security-config.version>3.2.5.RELEASE</spring-security-config.version>
<spring-security-tags.version>3.2.5.RELEASE</spring-security-tags.version>
自定义身份验证提供程序类
@Component
public class WebtoolAuthenticationProvider implements AuthenticationProvider {
@Autowired
UserDetailsService userDetailsDao;
/* (non-Javadoc)
* @see org.springframework.security.authentication.AuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
*/
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
System.out.println("*** IN THE METHOD *** UN: " + name + " PWD: " + password);
// use the credentials to try to authenticate against the third party system
if (authenticationSuccessful(authentication)) {
System.out.println(" Create session object");
// Populate the list of grants
List<GrantedAuthority> grantedAuths = new ArrayList<>();
UserSessionInfo us = userDetailsDao.loadUserByUsername(name);
Authentication auth = new UsernamePasswordAuthenticationToken(us, password, grantedAuths);
return auth;
} else {
throw new SecurityException("Unable to auth against Directory for user " + name);
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
public boolean authenticationSuccessful(Authentication authentication){
boolean authSuccessful = false;
LdapAuthenticationProvider prov = WebtoolLdapConfiguration.getLdapAuthenticationProvider();
try
{
Authentication result = prov.authenticate(authentication);
if(result != null )
{
System.out.println("Auth Successful for user ");
authSuccessful = true;
}
}
catch(AuthenticationException e)
{
System.out.println("Caught Exception, unable to authenticate user ");
}
return authSuccessful;
}
}
应用程序根配置类
@Configuration // Default Root config,
@ComponentScan({"com.drajer.cen.*"})
public class WebtoolRootConfiguration {
}
MVC配置
@Configuration
// @EnableMvc not required due to DelegatingWebMvcConfiguration
@ComponentScan({"com.drajer.cen.*"})
@EnableTransactionManagement
@Order(1)
public class WebtoolWebMvcConfiguration extends
DelegatingWebMvcConfiguration {
@Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder =
new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.drajer.cen.*")
.addResource("database/hibernate.cfg.xml")
.addResource("database/queries.xml")
.addProperties(getHibernateProperties());
SessionFactory sf = builder.buildSessionFactory();
return sf;
}
private Properties getHibernateProperties() {
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect",
"org.hibernate.dialect.Oracle10gDialect");
return prop;
}
@Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
ds.setUrl("jdbc:oracle:thin:@localhost:1521/XE");
ds.setUsername("webtool");
ds.setPassword("webtool");
ds.setTestOnBorrow(true);
ds.setValidationQuery("SELECT 1 FROM DUAL");
return ds;
}
//Create a transaction manager
@Bean
public HibernateTransactionManager txManager() {
return new HibernateTransactionManager(sessionFactory());
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>>
converters) {
super.configureMessageConverters(converters);
Hibernate4Module hibernateModule = new Hibernate4Module();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(hibernateModule);
MappingJackson2HttpMessageConverter jacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
jacksonHttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jacksonHttpMessageConverter);
}
}
Servlet初始值设定项:此(下面的代码)目前未在我的配置中使用,因为它不适用于WLS 12,而仅适用于Tomcat 7/8。因此,配置直接加载到上面的应用程序初始值设定项中。该问题与SpringSecurityFilterChain初始化有关,在上述配置中,这不再是一个问题
/*
public class WebtoolServletConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {WebtoolRootConfiguration.class, WebtoolSecurityConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebtoolWebMvcConfiguration.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
*/
/*
公共类WebtoolServletConfiguration扩展了AbstractAnnotationConfigDispatchersServletInitializer{
@凌驾
受保护类[]getRootConfigClasses(){
返回新类[]{WebtoolRootConfiguration.Class,WebtoolSecurityConfig.Class};
}
@凌驾
受保护类[]getServletConfigClasses(){
返回新类[]{WebtoolWebMvcConfiguration.Class};
}
@凌驾
受保护的字符串[]getServletMappings(){
返回新字符串[]{”/“};
}
}
*/
问题在于,您使用new
创建了WebtoolAuthenticationProvider
的新实例。那么Autowire就不起作用了
调整您的WebtoolSecurityConfig
:
@Autowired
私有WebtoolAuthenticationProvider authenticationProvider;
@自动连线
public void registerGlobalAuthentication(AuthenticationManagerBuilder auth)引发异常{
auth.authenticationProvider(authenticationProvider);
}
就这样,非常感谢您的回答。我真的很感谢你的帮助。@NageshBashyam,因为那时它还没有变成“春豆”;Spring无法为它不知道的实例处理类似于@Autowired
的注释。别忘了将答案标记为已接受:)
@Configuration
// @EnableMvc not required due to DelegatingWebMvcConfiguration
@ComponentScan({"com.drajer.cen.*"})
@EnableTransactionManagement
@Order(1)
public class WebtoolWebMvcConfiguration extends
DelegatingWebMvcConfiguration {
@Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder =
new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.drajer.cen.*")
.addResource("database/hibernate.cfg.xml")
.addResource("database/queries.xml")
.addProperties(getHibernateProperties());
SessionFactory sf = builder.buildSessionFactory();
return sf;
}
private Properties getHibernateProperties() {
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect",
"org.hibernate.dialect.Oracle10gDialect");
return prop;
}
@Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
ds.setUrl("jdbc:oracle:thin:@localhost:1521/XE");
ds.setUsername("webtool");
ds.setPassword("webtool");
ds.setTestOnBorrow(true);
ds.setValidationQuery("SELECT 1 FROM DUAL");
return ds;
}
//Create a transaction manager
@Bean
public HibernateTransactionManager txManager() {
return new HibernateTransactionManager(sessionFactory());
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>>
converters) {
super.configureMessageConverters(converters);
Hibernate4Module hibernateModule = new Hibernate4Module();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(hibernateModule);
MappingJackson2HttpMessageConverter jacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
jacksonHttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jacksonHttpMessageConverter);
}
}
public class WebtoolApplicationConfiguration implements
WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebtoolRootConfiguration.class, WebtoolSecurityConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
//Adding the security filter chain to avoid WLS 12.1.3 loading issues related to Initilizers
Filter dsf = new DelegatingFilterProxy("springSecurityFilterChain");
container.addFilter("springSecurityFilterChain", dsf).addMappingForUrlPatterns(null, false, "/*");
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(WebtoolWebMvcConfiguration.class);
// dispatcherServlet.register(WebtoolSecurityWebConfguration.class);
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
/*
public class WebtoolServletConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {WebtoolRootConfiguration.class, WebtoolSecurityConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebtoolWebMvcConfiguration.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
*/