gpt4 book ai didi

spring-mvc - @Autowire 在 Spring 安全自定义身份验证提供程序中不起作用

转载 作者:行者123 更新时间:2023-12-04 02:08:23 27 4
gpt4 key购买 nike

我们有 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 未在自定义身份验证提供程序中 Autowiring 。虽然相同的服务 authenticationService 在我的 MVC Controller 中以相同的方式 Autowiring 。

这是因为身份验证提供程序是 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 安全组件中 Autowiring 我的服务类?

最佳答案

也许在根应用程序上下文中没有启用 Autowiring 后处理器(但在 DispatcherServlet 的上下文中作为 <mvc:annotation-driven><context:component-scan> 的副作用启用)。

您可以通过添加 <context:annotation-config> 来启用它至 myApp-security.xml .

关于spring-mvc - @Autowire 在 Spring 安全自定义身份验证提供程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7023972/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com