Authentication 自定义身份验证提供程序中的自动连线为空

Authentication 自定义身份验证提供程序中的自动连线为空,authentication,spring-security,nullpointerexception,autowired,userdetailsservice,Authentication,Spring Security,Nullpointerexception,Autowired,Userdetailsservice,我正面临一个严重的问题,我不知道如何解决它 基本上,在我的自定义身份验证提供程序中,我不能自动连接我的customUserDetailsService,它返回一个空指针异常 我将粘贴我使用的所有类以及异常,这里的问题是它自动连接,但它返回NULL,它不会给我自动连接本身的错误 SecurityConfig类: package esercizio.security; import org.springframework.beans.factory.annotation.Autowired; im

我正面临一个严重的问题,我不知道如何解决它

基本上,在我的自定义身份验证提供程序中,我不能自动连接我的customUserDetailsService,它返回一个空指针异常

我将粘贴我使用的所有类以及异常,这里的问题是它自动连接,但它返回NULL,它不会给我自动连接本身的错误

SecurityConfig类:

package esercizio.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DbAuthenticationProvider dbAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // SecurityContextHolder.getContext().getAuthentication();
        auth.authenticationProvider(new DbAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // .addFilterBefore(
                // new HeaderUsernamePasswordAuthenticationFilter(authenticationManager()),
                // BasicAuthenticationFilter.class)
                .csrf().disable().authorizeRequests().antMatchers("/resources/**").permitAll().antMatchers("/auth/**")
                .hasRole("USER").anyRequest().authenticated().and().formLogin()
                // .loginPage("/login.jsp")
                .loginProcessingUrl("/signin").permitAll().failureForwardUrl("/errorPage")
                .successForwardUrl("/successPage").and().logout().addLogoutHandler(customLogoutHandler())
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
        // .and()
        // .exceptionHandling().accessDeniedPage("/403");
    }

    @Bean
    public CustomLogoutHandler customLogoutHandler() {
        return new CustomLogoutHandler();
    }
}
自定义身份验证提供程序:

package esercizio.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class DbAuthenticationProvider implements AuthenticationProvider {
    Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    UserDetailsService customUserDetailsService;

    public DbAuthenticationProvider() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        Object credentials = authentication.getCredentials();
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        UserDetails user = customUserDetailsService.loadUserByUsername(name);
        Authentication auth = null;

        if (!(credentials instanceof String)) {
            return null;
        }
        String password = null;
        try {
            password = getMD5(credentials.toString());
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (user != null && (user.getUsername().equals(name) && user.getPassword().equals(password))) {
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuthorities);
        } else {
            throw new BadCredentialsException("Errore nell'autenticazione");
        }

        return auth;
    }

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

    public String getMD5(String data) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");

        messageDigest.update(data.getBytes());
        byte[] digest = messageDigest.digest();
        StringBuffer sb = new StringBuffer();
        for (byte b : digest) {
            sb.append(Integer.toHexString((int) (b & 0xff)));
        }
        return sb.toString();
    }

}
WEB.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <servlet>
        <servlet-name>InitServlet</servlet-name>
        <servlet-class>esercizio.InitServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/springmvc-servlet.xml
            /WEB-INF/spring-security-context.xml
        </param-value>
    </context-param>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>InitServlet</servlet-name>
        <url-pattern>/InitServlet</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>esercizio.listener.SessionListener</listener-class>
    </listener>

     <!-- <filter>
        <filter-name>RedirectFilter</filter-name>
        <filter-class>esercizio.filters.RedirectFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>RedirectFilter</filter-name>
        <url-pattern></url-pattern>
    </filter-mapping>  

    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list> --> 

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

</web-app>
如果有人能找出问题的症结所在,我将永远心存感激,这已经有3天了,而我似乎无法解决它。

我想

@自动连线 UserDetails服务CustomUserDetails服务

应该是

@自动连线
CustomUserDetails服务CustomUserDetails服务

主要原因是,在
配置(AuthenticationManagerBuilder)
中,您正在构建
DbAuthenticationProvider
的新实例,同时将其注入
身份验证管理器
(就在这一行:
authenticationProvider(new DbAuthenticationProvider());
)在
Spring框架
上下文之外,因此注入
AuthenticationManager
DbAuthenticationProvider
实例无法
autowire
自动连线
@Autowired userdetails服务customuserdetails服务

由于此UserDetailsService字段将为空,因此将在这行代码的
authenticate()
方法中抛出
NullPointerException
UserDetails user=customUserDetailsService.loadUserByUsername(名称)

您可以通过多种方式更改类的加载方式,但最简单的方法可能是使用以下代码块:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DbAuthenticationProvider dbAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // SecurityContextHolder.getContext().getAuthentication();
        auth.authenticationProvider(new DbAuthenticationProvider());
    }
并将其更改为:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DbAuthenticationProvider dbAuthenticationProvider;    

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(dbAuthenticationProvider);
    }        
我认为这是更改代码以使其正常工作的最简单方法

可能的副本将帮助您!
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

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

    <context:annotation-config />

    <context:component-scan base-package="esercizio" />

 </beans:beans>
java.lang.NullPointerException
    esercizio.security.DbAuthenticationProvider.authenticate(DbAuthenticationProvider.java:41)
    org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
    org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
    org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DbAuthenticationProvider dbAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // SecurityContextHolder.getContext().getAuthentication();
        auth.authenticationProvider(new DbAuthenticationProvider());
    }
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DbAuthenticationProvider dbAuthenticationProvider;    

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