spring security 没有调用 loadUserByUsername() 方法

Posted

技术标签:

【中文标题】spring security 没有调用 loadUserByUsername() 方法【英文标题】:loadUserByUsername() method not getting invoked by spring security 【发布时间】:2018-12-10 18:58:30 【问题描述】:

我是 Spring 安全的新手,刚刚开始学习它。我想使用自定义的User 类,所以我试图实现UserDetailsService 接口并覆盖loadUserByUsername() 方法以返回自定义User 对象。 但是spring security没有调用loadUserByUsername(),所以用户没有得到认证,而是被重定向到登录页面。 我不知道出了什么问题 代码:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter 
    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http
            .authorizeRequests()
                .antMatchers("/login","/css/**","/images/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll();
    
    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
        System.out.println("configureglobal called");

        auth.userDetailsService(userDetailsService);
    

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService 

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(final String username)
        throws UsernameNotFoundException 
        System.out.println("loadUserByUsername called");
        User user = userRepository.findByUsername(username);


return user;

    

public interface UserRepository extends JpaRepository<User, Long>
    User findByUsername(String username);
    List<User> findByName(String name);


这是我的控制器类。即使提供了有效的用户名和密码,登录方法也会被调用 3 次,并且不会调用 loadUserByUsername()

 @Controller
    public class MainController 
        @RequestMapping(value= "/login")
        public String login() 
            System.out.println("login called");
            return "login";
         

            @RequestMapping(value="/",/home")
            public String homeReturner(HttpServletRequest request,Model model) 
                System.out.println("home returner called");
                model.addAttribute("name", request.getAttribute("name"));
                return "home";
            
    

用户类

@Entity
public class User implements UserDetails 
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String username;

    private String password;


    public Integer getId() 
        return id;
    

    public void setId(Integer id) 
        this.id = id;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public String getUsername() 
        return username;
    


    public void setUsername(String userName) 
        this.username = userName;
    

    public String getPassword() 
        return password;
    

    public void setPassword(String password) 
        this.password = password;
    


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() 
        // TODO Auto-generated method stub
        return null;
    

    @Override
    public boolean isAccountNonExpired() 
        // TODO Auto-generated method stub
        return true;
    

    @Override
    public boolean isAccountNonLocked() 
        // TODO Auto-generated method stub
        return true;
    

    @Override
    public boolean isCredentialsNonExpired() 
        // TODO Auto-generated method stub
        return true;
    

    @Override
    public boolean isEnabled() 
        // TODO Auto-generated method stub
        return true;
    


登录页面中的html表单

<form action="/signin">
    <input type="text" name="username" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit">Sign in</button><br>
    <input type="checkbox" name=""> <label>Remember me.</label>&nbsp;&nbsp; <input type="checkbox" name=""><label>Forgot password?</label>
</form>

登录控制器

@Controller
public class LoginController 
    @Autowired
    private UserRepository userRepository;
    @GetMapping(path="/signin")
    public String signin() 

            System.out.print("signin called");
        return "home";
    

这里出了什么问题?为什么不调用 loadUserByUsername()? 调试日志

2018-07-04 21:59:19.249 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using NegatedRequestMatcher [requestMatcher=Ant [pattern='/**/favicon.ico']]
2018-07-04 21:59:19.250 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/favicon.ico'; against '/**/favicon.ico'
2018-07-04 21:59:19.251 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.u.matcher.NegatedRequestMatcher  : matches = false
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.s.HttpSessionRequestCache        : Request not saved as configured RequestMatcher did not match
2018-07-04 21:59:19.252 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.a.ExceptionTranslationFilter     : Calling Authentication entry point.
2018-07-04 21:59:19.253 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.web.DefaultRedirectStrategy        : Redirecting to 'http://localhost:8080/login'
2018-07-04 21:59:19.254 DEBUG 7128 --- [nio-8080-exec-4] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@7a1d6f3f
2018-07-04 21:59:19.254 DEBUG 7128 --- [nio-8080-exec-4] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2018-07-04 21:59:19.257 DEBUG 7128 --- [nio-8080-exec-4] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-07-04 21:59:19.298 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@22d63ce1. A new one will be created.
2018-07-04 21:59:19.299 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-07-04 21:59:19.300 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-07-04 21:59:19.300 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/logout'
2018-07-04 21:59:19.301 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2018-07-04 21:59:19.301 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /login' doesn't match 'POST /login
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
2018-07-04 21:59:19.302 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.DefaultSavedRequest            : requestURI: arg1=/home; arg2=/login (property not equals)
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.s.HttpSessionRequestCache        : saved request doesn't match
2018-07-04 21:59:19.303 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-07-04 21:59:19.304 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-07-04 21:59:19.304 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS'
2018-07-04 21:59:19.306 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-07-04 21:59:19.306 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-07-04 21:59:19.307 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-07-04 21:59:19.307 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/'
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/login'
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /login; Attributes: [permitAll]
2018-07-04 21:59:19.308 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS
2018-07-04 21:59:19.309 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@7cbce1e2, returned: 1
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
2018-07-04 21:59:19.310 DEBUG 7128 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : /login reached end of additional filter chain; proceeding with original chain
login called2018-07-04 21:59:19.320 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@7a1d6f3f
2018-07-04 21:59:19.321 DEBUG 7128 --- [nio-8080-exec-3] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2018-07-04 21:59:19.326 DEBUG 7128 --- [nio-8080-exec-3] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2018-07-04 21:59:19.326 DEBUG 7128 --- [nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2018-07-04 21:59:26.605 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-07-04 21:59:26.606 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@22d63ce1. A new one will be created.
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-07-04 21:59:26.607 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/logout'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/login'
2018-07-04 21:59:26.608 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-07-04 21:59:26.609 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : pathInfo: both null (property equals)
2018-07-04 21:59:26.609 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : queryString: both null (property equals)
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.DefaultSavedRequest            : requestURI: arg1=/home; arg2=/signin (property not equals)
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.s.HttpSessionRequestCache        : saved request doesn't match
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-07-04 21:59:26.610 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-07-04 21:59:26.611 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS'
2018-07-04 21:59:26.611 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : /signin at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-07-04 21:59:26.612 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/login'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/css/**'
2018-07-04 21:59:26.613 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/signin'; against '/images/**'
2018-07-04 21:59:26.614 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /signin; Attributes: [authenticated]
2018-07-04 21:59:26.614 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@3793fe54: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffde5d4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: FB5BC6CF44B2064132ADF5A75EE463DD; Granted Authorities: ROLE_ANONYMOUS
2018-07-04 21:59:26.615 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@7cbce1e2, returned: -1
2018-07-04 21:59:26.618 DEBUG 7128 --- [nio-8080-exec-7] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) ~[spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_162]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_162]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_162]

【问题讨论】:

你打的是哪个端点?你期待什么样的行为? 尝试添加@Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception return super.authenticationManagerBean(); @fg78nc 当我尝试访问 /home 时,它​​按预期重定向到登录页面,但是当我使用有效的用户名和密码提交登录表单时,它仍然重定向到登录页面。我期待点击主页。 @fg78nc 添加了authenticationManagerBean(),还是不行 请看下面我的回答,因为它不太适合 cmets 【参考方案1】:

我遇到了同样的问题,我可以在下面的日志中看到 Hibernate:选择 user0_.id 作为 id1_0_,user0_.is_active 作为 is_activ2_0_,user0_.password 作为 password3_0_,user0_.roles 作为角色 4_0_,user0_.user_name 作为 user_nam5_0_ from user user0_ where user0_.user_name=?

    表示 loadUserByUserName 正在 DB 中搜索具有“user_name”的用户。 我在 DB 中使用 userName 列创建了 userName 当我选择 * from user where user_name = ''; 它将返回 user_name = null 这就是它不验证用户并且无法在数据库中找到用户的原因。 我用与 userName 列相同的值更新了该列并且它起作用了。

【讨论】:

【参考方案2】:

请尝试如下修改。

.and().formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .failureUrl("/login?error=true")
                .defaultSuccessUrl("/default") // add page where to navigate after login
                .usernameParameter("username") // make sure your form has correct params
                .passwordParameter("password") // make sure your form has correct params
                .permitAll() // allow access

你的控制器:

    @GetMapping(value = "/login")
    public ModelAndView login(@RequestParam(value = "error", required = false) String error,
                             @RequestParam(value = "logout", required = false) String logout) 

        logger.info("Login(error): ", error);
        logger.info("Login(logout): ", logout);

        ModelAndView model = new ModelAndView();
        if (error != null) 
            model.addObject("error", "Invalid username/password");
        

        if (logout != null) 
            model.addObject("message", "Logged out");
        
        model.setViewName("login");
        return model;
    

    @GetMapping("/default")
    public String defaultAfterLogin(HttpServletRequest httpServletRequest) 
        return "redirect:/";
    

【讨论】:

不工作的伙伴,还是一样的结果.. 每次提交表单时,login() 方法被调用 3 次 更新了问题以包含 html 表单并登录控制器 @Arjun 尝试将.csrf().disable() 添加到http. 1) 在您的表单中添加method="POST"。 2) 你不应该从getAuthorities 返回null。将其更改为 @Override public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() return AuthorityUtils.createAuthorityList("ROLE_USER"); 3) 添加到 http 链的底部 .antMatchers("/**").access("hasRole('USER'')") 或者您可以添加 .antMatchers("/**").access("hasAnyRole('USER', 'ANONYMOUS')") - 这也将允许匿名访问(这是您现在获得的角色) 你也可以添加noop前缀

以上是关于spring security 没有调用 loadUserByUsername() 方法的主要内容,如果未能解决你的问题,请参考以下文章

DelegatingFilterProxy 在没有 Spring Security 的 Spring MVC 应用程序上调用了两次

当我使用.html url调用时,Spring Security没有阻塞

为啥这个基于令牌的 Spring Security 过滤器没有被调用?

即使对于没有安全设置的端点,也总是调用 Spring Security 过滤器[重复]

使用 Spring Security requires-channel 和 Amazon Elastic Load Balancer 的登录循环

JSF / Spring Security - 添加其他登录字段不会调用自定义过滤器