将cookie设置为安全时Spring Boot无法登录

Posted

技术标签:

【中文标题】将cookie设置为安全时Spring Boot无法登录【英文标题】:Spring Boot unable to login when set cookie as secured 【发布时间】:2019-07-11 14:08:46 【问题描述】:

我正在开发一个使用默认 Thymeleaf 并使用 REST API 访问数据库的 Spring Boot 项目。一切正常,直到测试发现要求我将 cookie 标记为安全。我已经阅读了这些链接:

    Add secure flag to JSESSIONID cookie in spring automatically https://javadeveloperzone.com/spring-boot/spring-boot-secure-session-cookies/

我已经尝试了这两种方法,安全标志都存在。

安全标志 cookie 的屏幕截图

当我尝试登录应用程序时出现问题,我无法登录。我在运行时调试了spring security源代码,我认为问题是从html Form和tokenRepository中发送的CSRF Token CsrfFilter 不匹配,导致

“为 http://localhost:8081/login 找到无效的 CSRF 令牌”

并抛出 MissingCsrfTokenException(CsrfFilter 中的 doFilterInternal)。

以下是我的配置:

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter 

@Bean("authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception 
    return super.authenticationManagerBean();


@Autowired
private CustomAuthProvider customAuthProvider;


@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception 
    auth.authenticationProvider(customAuthProvider);


@Bean
public CustomAuthenticationFailureHandler authenticationFailureHandler() 
    return new CustomAuthenticationFailureHandler();


@Bean
public CustomLogoutSuccessHandler logoutSuccessHandler() 
    return new CustomLogoutSuccessHandler();


@Override
protected void configure(HttpSecurity http) throws Exception 
    http
        .authorizeRequests()
            .antMatchers("/login**").permitAll()
            .anyRequest().authenticated()
            .and()
        .exceptionHandling()
            .accessDeniedPage("/errors/403")
            .and()
        .formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/login")
            .failureHandler(authenticationFailureHandler())
            .permitAll()
            .and()
        .logout()
            .logoutUrl("/logout")
            .logoutSuccessHandler(logoutSuccessHandler())
            .permitAll()
            .deleteCookies("JSESSIONID")
            .and()
        .sessionManagement()
            .maximumSessions(1);

    http.headers().frameOptions().sameOrigin()
        .addHeaderWriter(new StaticHeadersWriter("Content-Security-Policy","script-src 'self' 'unsafe-inline'"))
        .addHeaderWriter(new StaticHeadersWriter("X-Permitted-Cross-Domain-Policies","none"))
        .addHeaderWriter(new StaticHeadersWriter("Feature-Policy","geolocation 'none'"))
        .addHeaderWriter(new StaticHeadersWriter("Referrer-Policy","no-referrer"));


@Override
public void configure(WebSecurity web) throws Exception 
    web.ignoring().antMatchers("/img/**",
            "/misc/**",
            "/css/**",
            "/js/**",
            "/bower_components/**");

这是我的 CustomAuthProvider 的 sn-p

CustomAuthProvider.java

@Component
public class CustomAuthProvider implements AuthenticationProvider 

@Override
public Authentication authenticate (Authentication authentication) throws AuthenticationException 

    String username = authentication.getName();
    String password = authentication.getCredentials().toString();

    HashMap<String, Object> userData;
    try
        userData = AuthViaApi(username, password); //find by username password in api server
    catch(Exception e)
        throw new BadCredentialsException(e.getMessage());
    

    List<GrantedAuthority> grantedAuths = new ArrayList<>();
    try 
        ArrayList<HashMap<String, Object>> permissions = //get user's permission from database via api

        for(HashMap<String, Object> p : permissions)
            String authority = // generate authority string;
            grantedAuths.add(new SimpleGrantedAuthority(authority));
        

    catch(Exception e)
        //throw exception
    

    //updates some userData here to put in auth object's detail

    UserDetails principal = new User(username, password, grantedAuths);

    Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);

    ((UsernamePasswordAuthenticationToken) authentication).setDetails(userData);

    return auth;



@Override
public boolean supports(Class<?> authentication) 
    return authentication.equals(UsernamePasswordAuthenticationToken.class);


这是我的登录表单,csrf隐藏输入是spring生成的:

<form th:action="@/login" method="post" id="form" autocomplete="off">
            <div class="form-group has-feedback">
                <input type="text" class="form-control" placeholder="Username" name="username" autocomplete="off">
                <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
            </div>
            <div class="form-group has-feedback">
                <input type="password" class="form-control" placeholder="Password" name="password" autocomplete="off">
                <span class="glyphicon glyphicon-lock form-control-feedback"></span>
            </div>
</form>

提交表单时确实发送了csrf令牌:

表单数据截图

这是我提交表单时的 IntelliJ 调试控制台(由于正文字符限制,时间戳已删除):

DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/img/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/misc/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/css/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/js/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/bower_components/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /login at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /login at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG 10416 --- [nio-8081-exec-3] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
DEBUG 10416 --- [nio-8081-exec-3] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /login at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /login at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8081/login
 WARN 10416 --- [nio-8081-exec-3] o.s.web.servlet.PageNotFound             : Request method 'POST' not supported
DEBUG 10416 --- [nio-8081-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@b3a4b14
DEBUG 10416 --- [nio-8081-exec-3] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG 10416 --- [nio-8081-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/img/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/misc/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/css/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/js/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/bower_components/**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG 10416 --- [nio-8081-exec-3] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG 10416 --- [nio-8081-exec-3] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@1f953457. A new one will be created.
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/logout'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/login'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 7 of 13 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@ae899d55: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff4c9c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 885412450AE6A0685EDBC8C4A43C7D06; Granted Authorities: ROLE_ANONYMOUS'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG 10416 --- [nio-8081-exec-3] o.s.security.web.FilterChainProxy        : /error at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/logout'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/error'; against '/login**'
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /error; Attributes: [authenticated]
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@ae899d55: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff4c9c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 885412450AE6A0685EDBC8C4A43C7D06; Granted Authorities: ROLE_ANONYMOUS
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@5bee5c02, returned: -1
DEBUG 10416 --- [nio-8081-exec-3] 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.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:155) [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.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [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.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [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.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101) [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.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254) [tomcat-embed-core-8.5.31.jar:8.5.31]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:177) [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(ThreadPoolExecutor.java:1149) [na:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_181]
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(Thread.java:748) [na:1.8.0_181]

DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.util.matcher.AndRequestMatcher   : Trying to match using Ant [pattern='/**', GET]
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'POST /error' doesn't match 'GET /**
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.util.matcher.AndRequestMatcher   : Did not match
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.s.HttpSessionRequestCache        : Request not saved as configured RequestMatcher did not match
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.w.a.ExceptionTranslationFilter     : Calling Authentication entry point.
DEBUG 10416 --- [nio-8081-exec-3] o.s.s.web.DefaultRedirectStrategy        : Redirecting to 'http://localhost:8081/login'
DEBUG 10416 --- [nio-8081-exec-3] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG 10416 --- [nio-8081-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/img/**'
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/misc/**'
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/css/**'
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/js/**'
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/login'; against '/bower_components/**'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG 10416 --- [nio-8081-exec-2] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
DEBUG 10416 --- [nio-8081-exec-2] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 4 of 13 in additional filter chain; firing Filter: 'CsrfFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /login' doesn't match 'POST /logout
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /login' doesn't match 'POST /login
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 7 of 13 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@a34ec6dd: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /login; Attributes: [permitAll]
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@a34ec6dd: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@5bee5c02, returned: 1
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
DEBUG 10416 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy        : /login reached end of additional filter chain; proceeding with original chain
DEBUG 10416 --- [nio-8081-exec-2] 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@b3a4b14
DEBUG 10416 --- [nio-8081-exec-2] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG 10416 --- [nio-8081-exec-2] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
DEBUG 10416 --- [nio-8081-exec-2] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

我是否遗漏或配置错误?

【问题讨论】:

你真的打电话给http://localhost:8081/login 还是那条信息有误? @dur,我在浏览器上打开了 url,显示了登录表单,我提供了凭据,消息显示在 intellij 控制台上,页面刚刚刷新。 如果您使用安全 cookie,则不能调用不安全的 URL。您必须使用 HTTPS。 @dur 你是这个意思吗(developer.mozilla.org/en-US/docs/Web/HTTP/…)?那么“它们不是特定于协议的:HTTPS 网站上设置的 cookie(安全)也将可用于 HTTP 版本(不安全)”是什么意思。在此链接 (tunetheweb.com/security/http-security-headers/secure-cookies) 中? 我不确定,但您的第一个链接显示:从 Chrome 52 和 Firefox 52 开始,不安全的网站 (http:) 无法使用 Secure 指令设置 cookie。 你用的是什么版本? 【参考方案1】:

您的 Spring 应用程序中的 CSRF(跨站点请求伪造)保护似乎已启用。实际上它是默认启用的。 因此,要保持 CSRF 保护处于启用状态,您必须在表单中包含 csrftoken。你可以这样做:

<form .... >
  ....other fields here....
  <input type="hidden"  name="$_csrf.parameterName"   value="$_csrf.token"/>
</form>

在表单的操作中包含 CSRF 令牌:

<form action="./upload?$_csrf.parameterName=$_csrf.token" method="post" enctype="multipart/form-data">

【讨论】:

csrf 令牌输入已经存在,我提供的 html 来自我的源代码,html 输入然后由 spring thymeleaf 添加。 你有没有试过在标题中添加这个:addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Methods", "POST, GET"))【参考方案2】:

更新:

问题现在解决了,我想这是因为我在本地主机上尝试过,我认为浏览器认为这是“不安全的连接”,并且由于不安全的连接不能设置安全cookie,所以spring boot应用程序可以' t 创建会话,请参见此处:https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies

当我在提供 https 的客户端服务器上进行部署时,它正在工作。感谢所有响应者。

【讨论】:

以上是关于将cookie设置为安全时Spring Boot无法登录的主要内容,如果未能解决你的问题,请参考以下文章

spring boot项目之登陆缓存session至redis和cookies

java spring boot2设置Cookie解析器

如何在Spring Boot中使用Cookies

无法为 spring boot 1.5.22 设置 cookie samesite=none

spring boot cookie和session的区别

如何在 Spring Boot 中设置同站点 cookie 标志?