@Autowire在Spring Security自定义身份验证提供程序中不起作用
问题内容:
我们有Spring MVC应用程序。我们正在尝试将Spring安全性集成到其中。
我们已经编写了自定义身份验证提供程序,它将执行身份验证工作。
以下是我的自定义身份验证提供程序的代码。
public class CustomAuthenticationProvider extends DaoAuthenticationProvider {
@Autowired
private AuthenticationService authenticationService;
@Override
public Authentication authenticate(Authentication authentication) {
CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication;
String username = String.valueOf(auth.getPrincipal());
String password = String.valueOf(auth.getCredentials());
try {
Users user = new User();
user.setUsername(username);
user.setPassword(PasswordUtil.encrypt(password));
user = authenticationService.validateLogin(user);
return auth;
} catch (Exception e) {
throw new BadCredentialsException("Username/Password does not match for " + username);
}
}
@Override
public boolean supports(Class<? extends Object> authentication) {
return (CustomAuthenticationToken.class.isAssignableFrom(authentication));
}
}
在这里,我在下一行获取NullpointerException
user = authenticationService.validateLogin(user);
不会在自定义身份验证提供程序中自动连接authenticationService。虽然相同的服务authenticationService在我的MVC控制器中以相同的方式自动接线。
这是因为身份验证提供程序是Spring安全组件吗?
下面是我的web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/myApp-security.xml
</param-value>
</context-param>
<servlet>
<servlet-name>myApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/myApp-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
编辑1:-
我在我的spring安全配置文件中添加了以下几行。
<beans:bean id="customAuthenticationProvider" class="com.myApp.security.provider.CustomAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService"/>
</beans:bean>
请帮助如何在Spring安全组件中自动连接服务类?
问题答案:
也许未在根应用程序上下文中启用自动装配后处理器(但在DispatcherServlet
的上下文中由于<mvc:annotation- driven>
或的影响而启用了<context:component-scan>
)。
您可以通过添加<context:annotation-config>
到中启用它myApp-security.xml
。