spring security4 security="none"小讲

Not injecting HSTS header since it did not match the requestMatcher HSTS设置问题解决 HSTS请求设置 错误描述:在使用文件上传功能时,form表单提交带有header数据的请求时遇到这个问题,报错如下: Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@79cc14a4 [DEBUG] 2021-08-26 14:04:27.3 阅读详情

在学习spring security4时,参考文档,spring-security.xml有如下片段:

    <http pattern="/resources/**" security="none" />
    <http pattern="/login" security="none"/>
    <http auto-config="true" use-expressions="true">
        <!-- <intercept-url pattern="/login" access="permitAll" /> -->
        <intercept-url pattern="/about" access="permitAll" />
        <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/user/*" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/admin/*" access="hasRole('ROLE_ADMIN')"/>
        <custom-filter ref="ipFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
        <remember-me remember-me-parameter="remember-me" token-validity-seconds="604800" data-source-ref="dataSource" user-service-ref="customjdbcUserService"/>
        <form-login login-page="/login" default-target-url="/"
            password-parameter="pwd" />
        <logout logout-success-url="/about" />
    </http>

Controller细节为:

	@Controller
public class BaseController {
	@Autowired
	private SessionRegistry SessionRegistry;
	@RequestMapping("/")
	public String index(){
		return "index";
	}
	@RequestMapping("/login")
	public void login(){
		
	}

访问login时出现问题,表现为response为login页面,并没有进行登陆验证。

但当这样配置时,又可以正常登陆:

<http pattern="/resources/**" security="none" />
	<http pattern="/about" security="none" />
	<http auto-config="true">
		<strong><em><u><span style="color:#ff0000;"><intercept-url pattern="/login" access="permitAll" /></span></u></em></strong>
		<intercept-url pattern="/user/**" access="hasRole('USER')" />
		<intercept-url pattern="/admin/**" access="hasRole('ADMIN')" />
		<!-- 这个要在最后一个拦截,否则会匹配上,/user,/admin都将失效(未验证) -->
		<intercept-url pattern="/**" access="hasRole('USER')" />
		<session-management session-fixation-protection="migrateSession">
			<concurrency-control max-sessions="1"
				expired-url="/login?error=expired" />
		</session-management>
		<custom-filter ref="ipFilter" before="FILTER_SECURITY_INTERCEPTOR" />
		<remember-me key="elim" remember-me-parameter="remember-me"
			token-validity-seconds="604800" data-source-ref="dataSource"
			user-service-ref="customjdbcUserService" />
		<form-login login-page="/login" default-target-url="/"
			password-parameter="pwd" />
		<logout logout-success-url="/about" />
	</http>

(原来的代码找不到了,这是做过一定功能增加及修正后的,重点在红色行)

这样可以正常验证并登录。


记录下登陆验证出现问题时debug级别的日志信息,如下:

22:32:42,905 DEBUG AntPathRequestMatcher:151 - Checking match of request : '/login'; against '/resources/**'
22:32:42,905 DEBUG AntPathRequestMatcher:151 - Checking match of request : '/login'; against '/login'
<strong><span style="color:#ff0000;">22:32:42,905 DEBUG FilterChainProxy:200 - /login has an empty filter list</span></strong>
22:32:42,906 DEBUG DispatcherServlet:861 - DispatcherServlet with name 'springmvc' processing POST request for [/login]
22:32:42,907 DEBUG RequestMappingHandlerMapping:294 - Looking up handler method for path /login
22:32:42,908 DEBUG RequestMappingHandlerMapping:299 - Returning handler method [public void com.bay1ts.controller.BaseController.login()]
22:32:42,908 DEBUG DefaultListableBeanFactory:248 - Returning cached instance of singleton bean 'baseController'
22:32:42,909 DEBUG DispatcherServlet:1241 - Rendering view [org.springframework.web.servlet.view.JstlView: name 'login'; URL [/WEB-INF/jsps/login.jsp]] in DispatcherServlet with name 'springmvc'
22:32:42,910 DEBUG DefaultListableBeanFactory:248 - Returning cached instance of singleton bean 'requestDataValueProcessor'
22:32:42,910 DEBUG JstlView:166 - Forwarding to resource [/WEB-INF/jsps/login.jsp] in InternalResourceView 'login'
22:32:42,919 DEBUG DispatcherServlet:996 - Successfully completed request
可以发现:

第三行处,/login has an empty filter list。其实这是可以理解的,因为在拦截处,如果配置单独的<http>元素,并security="none",会让spring security放弃对这个pattern的所有处理,包括登陆验证,所以会出现上面描述的问题

而使用

<intercept-url pattern="/login" access="permitALL" />
<span style="font-family: Arial, Helvetica, sans-serif;">时,表示对这个pattern不进行权限限制,但还是需要经过spring security 的过滤器链的,即包括登陆验证的过滤器。</span>

下面是正常登录是的

22:56:22,763 DEBUG AntPathRequestMatcher:151 - Checking match of request : '/login'; against '/resources/**'
22:56:22,770 DEBUG FilterChainProxy:324 - /login at position 1 of 15 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
22:56:22,770 DEBUG HttpSessionSecurityContextRepository:171 - HttpSession returned null object for SPRING_SECURITY_CONTEXT
22:56:22,770 DEBUG HttpSessionSecurityContextRepository:101 - No SecurityContext was available from the HttpSession: org.eclipse.jetty.server.session.HashedSession:1bf4hxwrtqrdvs3dedd70rh8o@1206903733. A new one will be created.
22:56:22,770 DEBUG FilterChainProxy:324 - /login at position 2 of 15 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
22:56:22,770 DEBUG FilterChainProxy:324 - /login at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
22:56:22,771 DEBUG HstsHeaderWriter:128 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@1945827
22:56:22,771 DEBUG FilterChainProxy:324 - /login at position 4 of 15 in additional filter chain; firing Filter: 'CsrfFilter'
22:56:22,772 DEBUG FilterChainProxy:324 - /login at position 5 of 15 in additional filter chain; firing Filter: 'LogoutFilter'
22:56:22,772 DEBUG AntPathRequestMatcher:151 - Checking match of request : '/login'; against '/logout'
22:56:22,773 DEBUG FilterChainProxy:324 - /login at position 6 of 15 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
22:56:22,773 DEBUG AntPathRequestMatcher:151 - Checking match of request : '/login'; against '/login'
22:56:22,773 DEBUG UsernamePasswordAuthenticationFilter:211 - Request is to process authentication
22:56:22,774 DEBUG ProviderManager:162 - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
22:56:22,778 DEBUG JdbcTemplate:693 - Executing prepared SQL query
22:56:22,780 DEBUG JdbcTemplate:627 - Executing prepared SQL statement [select username,password,enabled from users where username = ?]
22:56:22,788 DEBUG DataSourceUtils:110 - Fetching JDBC Connection from DataSource
22:56:22,862  INFO AbstractPoolBackedDataSource:203 - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 1hge1379c1b42a3w17r38ui|3c87fdf2, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceUseNamedDriverClass -> false, identityToken -> 1hge1379c1b42a3w17r38ui|3c87fdf2, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/jdbcdaoimpl?characterEncoding=UTF-8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
22:56:22,895 DEBUG MConfig:198 - The configuration file for resource identifier '/mchange-commons.properties' could not be found. Skipping.
java.io.FileNotFoundException: Resource not found at path '/mchange-commons.properties'.
    at com.mchange.v2.cfg.BasicPropertiesConfigSource.propertiesFromSource(BasicPropertiesConfigSource.java:64)
    at com.mchange.v2.cfg.BasicMultiPropertiesConfig.firstInit(BasicMultiPropertiesConfig.java:185)
    at com.mchange.v2.cfg.BasicMultiPropertiesConfig.<init>(BasicMultiPropertiesConfig.java:110)
    at com.mchange.v2.cfg.ConfigUtils.read(ConfigUtils.java:63)
    at com.mchange.v2.cfg.MConfig$CSManager.recreateFromKey(MConfig.java:153)
    at com.mchange.v1.cachedstore.NoCleanupCachedStore.find(NoCleanupCachedStore.java:63)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.mchange.v1.lang.Synchronizer$1.invoke(Synchronizer.java:58)
    at com.sun.proxy.$Proxy29.find(Unknown Source)
    at com.mchange.v2.cfg.MConfig.readVmConfig(MConfig.java:75)
    at com.mchange.v2.cfg.MConfig.readVmConfig(MConfig.java:81)
    at com.mchange.v2.resourcepool.BasicResourcePool.<clinit>(BasicResourcePool.java:60)
    ...//日志信息过长,这里是无关紧要的部分,省去了。
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:695)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:727)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:737)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:787)
    at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUsersByUsername(JdbcDaoImpl.java:216)
    at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUserByUsername(JdbcDaoImpl.java:173)
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:143)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1667)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1667)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1114)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1048)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:109)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:119)
    at org.eclipse.jetty.server.Server.handle(Server.java:517)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:302)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:245)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
    at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
    at java.lang.Thread.run(Thread.java:745)
22:56:22,992 DEBUG BasicResourcePool:195 - com.mchange.v2.resourcepool.BasicResourcePool@a87512f config: [start -> 3; min -> 3; max -> 15; inc -> 3; num_acq_attempts -> 30; acq_attempt_delay -> 1000; check_idle_resources_delay -> 0; max_resource_age -> 0; max_idle_time -> 0; excess_max_idle_time -> 0; destroy_unreturned_resc_time -> 0; expiration_enforcement_delay -> 0; break_on_acquisition_failure -> false; debug_store_checkout_exceptions -> false]
22:56:22,992 DEBUG C3P0PooledConnectionPoolManager:195 - Created new pool for auth, username (masked): 'ro******'.
22:56:22,992 DEBUG BasicResourcePool:195 - acquire test -- pool size: 0; target_pool_size: 3; desired target? 1
22:56:22,993 DEBUG BasicResourcePool:195 - awaitAvailable(): [unknown]
22:56:23,568 DEBUG DataSourceUtils:327 - Returning JDBC Connection to DataSource
22:56:23,570 DEBUG JdbcTemplate:693 - Executing prepared SQL query
22:56:23,570 DEBUG JdbcTemplate:627 - Executing prepared SQL statement [select username,authority from authorities where username = ?]
22:56:23,571 DEBUG DataSourceUtils:110 - Fetching JDBC Connection from DataSource
22:56:23,573 DEBUG DataSourceUtils:327 - Returning JDBC Connection to DataSource
22:56:23,578 DEBUG DefaultListableBeanFactory:248 - Returning cached instance of singleton bean 'sqlSessionFactory'
22:56:23,578 DEBUG CompositeSessionAuthenticationStrategy:86 - Delegating to org.springframework.security.web.csrf.CsrfAuthenticationStrategy@70540f7b
22:56:23,580 DEBUG CompositeSessionAuthenticationStrategy:86 - Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy@51ae01da
22:56:23,581 DEBUG DefaultListableBeanFactory:248 - Returning cached instance of singleton bean 'sqlSessionFactory'
22:56:23,582 DEBUG UsernamePasswordAuthenticationFilter:317 - Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fec65191: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1bf4hxwrtqrdvs3dedd70rh8o; Granted Authorities: ROLE_ADMIN, ROLE_USER
22:56:23,582 DEBUG PersistentTokenBasedRememberMeServices:147 - Creating new persistent login for user admin
22:56:23,586 DEBUG JdbcTemplate:908 - Executing prepared SQL update
22:56:23,586 DEBUG JdbcTemplate:627 - Executing prepared SQL statement [insert into persistent_logins (username, series, token, last_used) values(?,?,?,?)]
22:56:23,587 DEBUG DataSourceUtils:110 - Fetching JDBC Connection from DataSource
22:56:23,593 DEBUG JdbcTemplate:918 - SQL update affected 1 rows
22:56:23,594 DEBUG DataSourceUtils:327 - Returning JDBC Connection to DataSource
22:56:23,594 DEBUG DefaultListableBeanFactory:248 - Returning cached instance of singleton bean 'sqlSessionFactory'
22:56:23,595 DEBUG SavedRequestAwareAuthenticationSuccessHandler:110 - Using default Url: /
22:56:23,595 DEBUG DefaultRedirectStrategy:39 - Redirecting to '/'
22:56:23,595 DEBUG HttpSessionSecurityContextRepository:362 - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@fec65191: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fec65191: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1bf4hxwrtqrdvs3dedd70rh8o; Granted Authorities: ROLE_ADMIN, ROLE_USER' stored to HttpSession: 'org.eclipse.jetty.server.session.HashedSession:m2b22n17auwqwwbhl5t9veiw@1206903733
22:56:23,596 DEBUG SecurityContextPersistenceFilter:105 - SecurityContextHolder now cleared, as request processing completed
22:56:23,598 DEBUG AntPathRequestMatcher:151 - Checking match of request : '/'; against '/resources/**'
22:56:23,599 DEBUG FilterChainProxy:324 - / at position 1 of 15 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
22:56:23,599 DEBUG HttpSessionSecurityContextRepository:192 - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@fec65191: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fec65191: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1bf4hxwrtqrdvs3dedd70rh8o; Granted Authorities: ROLE_ADMIN, ROLE_USER'
22:56:23,599 DEBUG FilterChainProxy:324 - / at position 2 of 15 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
22:56:23,600 DEBUG FilterChainProxy:324 - / at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
22:56:23,600 DEBUG HstsHeaderWriter:128 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@1945827
22:56:23,600 DEBUG FilterChainProxy:324 - / at position 4 of 15 in additional filter chain; firing Filter: 'CsrfFilter'
22:56:23,600 DEBUG FilterChainProxy:324 - / at position 5 of 15 in additional filter chain; firing Filter: 'LogoutFilter'
22:56:23,600 DEBUG AntPathRequestMatcher:131 - Request 'GET /' doesn't match 'POST /logout
22:56:23,601 DEBUG FilterChainProxy:324 - / at position 6 of 15 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
22:56:23,601 DEBUG AntPathRequestMatcher:131 - Request 'GET /' doesn't match 'POST /login
22:56:23,601 DEBUG FilterChainProxy:324 - / at position 7 of 15 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
22:56:23,601 DEBUG FilterChainProxy:324 - / at position 8 of 15 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
22:56:23,601 DEBUG FilterChainProxy:324 - / at position 9 of 15 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
22:56:23,601 DEBUG FilterChainProxy:324 - / at position 10 of 15 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
22:56:23,602 DEBUG RememberMeAuthenticationFilter:153 - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fec65191: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1bf4hxwrtqrdvs3dedd70rh8o; Granted Authorities: ROLE_ADMIN, ROLE_USER'
22:56:23,602 DEBUG FilterChainProxy:324 - / at position 11 of 15 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
22:56:23,602 DEBUG AnonymousAuthenticationFilter:106 - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fec65191: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1bf4hxwrtqrdvs3dedd70rh8o; Granted Authorities: ROLE_ADMIN, ROLE_USER'
22:56:23,602 DEBUG FilterChainProxy:324 - / at position 12 of 15 in additional filter chain; firing Filter: 'SessionManagementFilter'
22:56:23,602 DEBUG FilterChainProxy:324 - / at position 13 of 15 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
22:56:23,602 DEBUG FilterChainProxy:324 - / at position 14 of 15 in additional filter chain; firing Filter: 'IPRoleAuthenticationFilter'
22:56:23,603 DEBUG FilterChainProxy:324 - / at position 15 of 15 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
22:56:23,603 DEBUG AntPathRequestMatcher:151 - Checking match of request : '/'; against '/login'
22:56:23,603 DEBUG AntPathRequestMatcher:151 - Checking match of request : '/'; against '/about'
22:56:23,603 DEBUG FilterSecurityInterceptor:218 - Secure object: FilterInvocation: URL: /; Attributes: [hasRole('ROLE_USER')]
22:56:23,603 DEBUG FilterSecurityInterceptor:347 - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@fec65191: Principal: org.springframework.security.core.userdetails.User@586034f: Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1bf4hxwrtqrdvs3dedd70rh8o; Granted Authorities: ROLE_ADMIN, ROLE_USER
22:56:23,608 DEBUG AffirmativeBased:65 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@71ed560f, returned: 1
22:56:23,608 DEBUG FilterSecurityInterceptor:242 - Authorization successful
22:56:23,608 DEBUG FilterSecurityInterceptor:255 - RunAsManager did not change Authentication object
22:56:23,609 DEBUG FilterChainProxy:309 - / reached end of additional filter chain; proceeding with original chain
22:56:23,609 DEBUG DispatcherServlet:861 - DispatcherServlet with name 'springmvc' processing GET request for [/]
22:56:23,609 DEBUG RequestMappingHandlerMapping:294 - Looking up handler method for path /
22:56:23,610 DEBUG RequestMappingHandlerMapping:299 - Returning handler method [public java.lang.String com.bay1ts.controller.BaseController.index()]
22:56:23,610 DEBUG DefaultListableBeanFactory:248 - Returning cached instance of singleton bean 'baseController'
22:56:23,611 DEBUG DispatcherServlet:947 - Last-Modified value for [/] is: -1
22:56:23,612 DEBUG DefaultListableBeanFactory:1616 - Invoking afterPropertiesSet() on bean with name 'index'
22:56:23,612 DEBUG DispatcherServlet:1241 - Rendering view [org.springframework.web.servlet.view.JstlView: name 'index'; URL [/WEB-INF/jsps/index.jsp]] in DispatcherServlet with name 'springmvc'
22:56:23,612 DEBUG DefaultListableBeanFactory:248 - Returning cached instance of singleton bean 'requestDataValueProcessor'
22:56:23,613 DEBUG JstlView:166 - Forwarding to resource [/WEB-INF/jsps/index.jsp] in InternalResourceView 'index'
22:56:23,764 DEBUG DispatcherServlet:996 - Successfully completed request
22:56:23,764 DEBUG ExceptionTranslationFilter:116 - Chain processed normally
22:56:23,765 DEBUG SecurityContextPersistenceFilter:105 - SecurityContextHolder now cleared, as request processing completed
 

这是去stackoverflow提问后明确出来的结论,原文:

http://stackoverflow.com/questions/33371389/spring-security4-login-doesnt-pass-through-any-filter

答题的人还指明了一些配置文件中的错误或者冗余信息。例如:

对url pattern的拦截顺序,pattern="/**"要放在最后拦截,因为他会匹配任何一个请求,并将对应的访问权限设置为其权限。比如

    <intercept-url pattern="/login" access="permitAll" />
    <intercept-url pattern="/about" access="permitAll" />
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
    <intercept-url pattern="/user/*" access="hasRole('ROLE_USER')" />
    <intercept-url pattern="/admin/*" access="hasRole('ROLE_ADMIN')"/>
当访问/admin/时,会匹配上/**,并检查其权限是否有USER权限,而并不需要ADMIN权限。从而屏蔽掉后面的模式。所以要将其配置在最后一个。另外在spring security 4+ 中,并不需要给权限加上ROLE_前缀。所以,修正后的配置文件应该像:

 <intercept-url pattern="/resources/**" access="permitAll" />
    <intercept-url pattern="/login" access="permitAll" />
    <intercept-url pattern="/about" access="permitAll" />
    <intercept-url pattern="/user/*" access="hasRole('USER')" />
    <intercept-url pattern="/admin/*" access="hasRole('ADMIN')"/>
    <intercept-url pattern="/**" access="hasRole('USER')" />
省略了ROLE_前缀。

但是,省略前缀只能在配置文件中省略,在基于数据库的权限模型中,权限表中的值必须不能省略ROLE_前缀,否则会禁止访问!!这是血的教训,也可能是我其他的配置导致跟正常情况不同,但我更倾向于前者。


另外, /user/* 可以匹配上/user/12 但是不可以匹配上 /user/profile/12,所以,如果需要这种形式的url,需要将pattern更新 为/user/**。


新手,如有纰漏,请不吝指出。


Spring Boot整合Spring Security实现JWT无状态认证实战指南 在微服务架构和前后端分离的现代Web开发中,认证与授权是保障系统安全的核心环节。传统的基于Session的认证方式在分布式场景下面临扩展性和跨域挑战,因此无状态认证方案应运而生。JWT(JSON Web Token)作为一种开放标准,通过将用户信息编码为JSON对象并签名,实现了安全、自包含的身份凭证传输。其技术价值在于彻底解耦了服务端会话状态,显著提升了系统的可扩展性和跨域支持能力,尤其适用于RESTful API和微服务间的安全通信。结合Spring Security这一强大的Java安全框架,开发者可 阅读详情

相关推荐

Spring Boot项目密码安全升级:BCrypt算法与Spring Security集成实战

在Web应用开发中,用户密码的安全存储是系统安全的基石。传统的快速哈希函数(如MD5、SHA-256)因其计算速度快,易受彩虹表和暴力破解攻击,已不再适用于密码保护。为此,业界引入了专门设计的自适应哈希函数,其核心原理是通过可配置的成本因子(Work Factor)人为增加计算复杂度与时间,并内置随机盐值(Salt)机制,使得每次哈希结果唯一,从而有效抵御彩虹表攻击。这种技术为密码存储提供了面向未来的、可调整的安全强度,其工程价值在于为高价值用户数据构建了强大的抗破解防线。在Java生态中,Spring S

congsikuai0611的博客 331

Spring Security – security none, filters none, access permitAll

1.概述 Spring Security提供了几种将请求模式配置为不安全或允许所有访问的机制。取决于这些机制中的哪一种 - 这可能意味着根本不在该路径上运行安全过滤器链,或者运行过滤器链并允许访问 2. access=”permitAll” 使用access =“permitAll”设置元素将配置授权,以便在该特定路径上允许所有请求: <intercept-url pattern="/log...

weixin_30699741的博客 564

Spring Security会话固定攻击防御:原理、配置与Spring Authorization Server实践

会话管理是Web应用安全的核心基础,它通过在服务器端维护用户状态,为无状态的HTTP协议提供连续性。其核心原理是服务器生成唯一的会话标识符(Session ID)并通过Cookie传递给客户端,后续请求凭此ID关联用户上下文。若会话ID在用户登录前后保持不变,则可能引发会话固定攻击,攻击者可利用预先设置的ID劫持已认证会话,严重威胁账户安全。该漏洞凸显了认证流程中会话标识符更新的技术价值。在Spring生态中,Spring Security提供了默认的会话迁移防御机制,但在与Spring Authoriza

weixin_30443731的博客 413

spring security中security="none"与ROLE_ANONYMOUS区别

为什么80%的码农都做不了架构师?>>> ...

weixin_33898876的博客 2204

Spring Boot 核心机制与实战:从自动装配到 MySQL、Redis、Security 集成

在 Java Web 开发领域,Spring Boot 通过其核心机制——自动装配(Auto-Configuration)和 Starter 依赖,极大地简化了企业级应用的构建与部署流程。自动装配的原理在于,框架根据项目引入的依赖和现有配置,智能地装配所需的 Spring Bean,实现了“约定大于配置”的理念。这一机制的技术价值在于,它将开发者从繁琐的 XML 配置和依赖管理中解放出来,显著提升了开发效率,并确保了应用的生产就绪性。其应用场景广泛覆盖了 Web 服务、数据访问、缓存和安全认证等现代应用的核

weixin_34389926的博客 392

Spring Security 7.0 CSRF防护升级:SPA应用零配置解决方案

CSRF(跨站请求伪造)是一种常见的Web安全威胁,攻击者诱导用户在已认证的Web应用中执行非本意的操作。其防御原理通常采用令牌验证机制,确保请求来源于合法的用户会话。在前后端分离的现代Web开发中,单页应用(SPA)因其异步交互特性,使得传统的CSRF防护方案面临挑战,尤其是令牌的获取与传递。Spring Security作为Java生态中权威的安全框架,其6.0及7.0版本对CSRF的默认行为进行了重要升级,旨在为SPA架构提供更安全、更优雅的集成方案。通过引入`CookieCsrfTokenRepos

culiao6493的博客 789

Reject: HTTP ‘DELETE‘ is not allowed, Not injecting HSTS.....DELETE请求PUT请求跨域问题

CORS(DELETE请求、PUT请求) Reject: HTTP 'DELETE' is not allowed [DEBUG] 2021-08-25 15:23:52.401 [http-nio-10010-exec-1] HstsHeaderWriter.writeHeaders(169) - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.head

了迹奇有没 1236

JWT与Spring Security整合实战:从原理到安全陷阱全解析

身份认证与授权是现代Web应用,尤其是微服务架构中的核心安全机制。其原理在于通过可靠的凭证验证用户身份,并依据权限控制资源访问,是构建可信系统的技术基石。在众多技术方案中,JWT(JSON Web Token)因其无状态、自包含的特性,成为实现分布式认证的热门选择,而Spring Security则为Java应用提供了强大的安全框架支持。两者的结合能有效解决传统Session方案在扩展性和跨域场景下的痛点,技术价值在于简化架构、提升性能并支持灵活的权限模型。典型的应用场景包括前后端分离项目、微服务API网关

weixin_30883311的博客 365

SSH项目中遇到的不细心错误!

最近学到三大框架的整合,在做项目中遇到一个因为自己不细心而引起的错误,害我排了将近一个小时可能因为自己还是刚刚接触吧,但是三大框架在整合中确实有很多摸不到头脑的问题,今天就遇到在一个部门管理页面添部门时,我并没有在代码里面做回显反而在页面输入框中显示了我的信息,原来Action在spring中依赖注入没有设置为多例而导致  <bean id="departmentAction" class="c

H'Sunshine 。 1117

Anroid8.1 强制修改系统可以adb remount

在Android6.0 (Android M)user版本上,发现使用adb root后再adb remount系统之后会提示这样信息:remount of /system failed: Read-only file system,这是不能对system分区进行操作,提示没有写权限,为只读文件系统Read-only file system,因为系统本身在user就不支持可写操作,我们就不能adb push来调试apk,如果想调试apk就需要修改system、vendor权限问题。 如下现象: C:\Use

wq892373445的博客 1408

[ENVI]-[高光谱遥感]-波谱沙漏分析工具的使用

图1-2-1查看特殊波段的坏波段图1-2-2在中添加坏波段ENVI波谱沙漏分析工具MNF变换。

m0_57992372的博客 1470

Spring Security- 环境搭建与第一个入门案例实现

本文介绍了Spring Security框架的基本概念和功能,并详细讲解了如何从零开始搭建开发环境。主要内容包括: Spring Security概述:一个功能强大的认证授权框架,提供身份验证、访问控制、Web安全防护等功能,采用过滤器链设计模式。 环境准备:需要JDK8+、构建工具(Maven/Gradle)和IDE,推荐使用Spring Boot 2.7.x版本。 依赖配置:提供了Maven和Gradle两种构建工具的详细依赖配置,包括Spring Boot Web、Security核心模块以及Thym

千淘万漉虽辛苦,吹尽狂沙始到金 1万+

Flink实战项目——城市交通实时监控平台

本项目是与公安交通管理综合应用平台、机动车缉查布控系统等对接的,并且基于交通部门现有的数据平台上,进行的数据实时分析项目。

yangwei2048的博客 839

Spring Security进阶

Spring Security进阶一、配置可匿名访问的资源二、使用指定的登录页面1. 提供login.html作为项目的登录页2. 指定登录页面3. 配置表单登录信息4. 关闭CsrfFilter过滤器三、从数据库查询用户信息1. 定义UserService类,实现UserDetailsService接口2. 在spring-security.xml中配置认证管理四、对密码进行加密五、配置多种校验规则(对访问的页面做权限控制)六、注解方式权限控制(对访问的Controller类做权限控制)七、退出登录

IAHEAD的博客 588

【100%通过率】2023华为od机试C卷【电脑病毒感染】C语言 实现

一个局域网内有很多台电脑,分别标注为 0 ~ N-1 的数字。相连接的电脑距离不一样,所以感染时间不一样,感染时间用t 表示。其中网络内一台电脑被病毒感染,求其感染网络内所有的电脑最少需要多长时间。如果最后有电脑不会感染,则返回-1.

MISAYAONE的博客 1043

【PG高可用】一 PostgreSQL高可用方案repmgr部署(非常详细)

repmgr安装部署

DBA之路的博客 7057

ECC 项目 springboot-security 技能实战:Spring Security 驱动的 Spring Boot 服务安全加固指南

在 Java Spring Boot 服务中引入认证、处理用户输入、暴露 REST 端点或管理密钥时,开发者最需要一套**可直接落地、可被代码审查逐条核对**的安全基线。本指南以 ECC 仓库中的 `springboot-security` 技能(SKILL)为主体,系统讲解 Spring Security 在认证(JWT/OAuth2/会话)、授权(方法级安全)、输入校验、SQL 注入防护、密码

gitblog_01184的博客 479

【LangChain编程:从入门到实践】实现多模态代理

【LangChain编程:从入门到实践】实现多模态代理 关键词:LangChain, 多模态代理, 自然语言处理, 机器学习, 知识图谱, 对话系统, 代码生成, AI代理 1. 背景介绍 随着人工智

欢迎来到我的优快云空间!这里聚焦AI大模型应用实战,分享前沿技术、实战案例与开发经验。 581

Spring-security-oauth2之DaoAuthenticationProvider

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33881140的博客 1403

【华为OD机试真题】7、字符串筛选排序 | 机试真题+思路参考+代码解析(C++、Java、Py)

题目描述 >输入一个由N个大小写字母组成的字符串 按照ASCII码值从小到大进行排序 查找字符串中第K个最小ASCII码值的字母(k>=1) 输出该字母所在字符串中的位置索引(字符串的第一个位置索引为0) k如果大于字符串长度则输出最大ASCII码值的字母所在字符串的位置索引 如果有重复字母则输出字母的最小位置索引

KJ.JK 2267

如何使用事务码SMICM分析ABAP代码发起的HTTP请求的错误

当我用CL_HTTP_CLIENT往一个外网的url发请求时,遇到错误:ICM_HTTP_SSL_PEER_CERT_UNTRUSTED 错误是从这段ABAP代码里抛出来的: CALL METHOD lo_http_client-&gt;get_last_error IMPORTING code = lv_sysubrc message = ev_error_message. "BREAK-...

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 3209

Spring Security账号密码认证源码解析

分享一些资料给大家,我觉得这些都是很有用的东西,大家也可以跟着来学习,查漏补缺。《Java高级面试》《Java高级架构知识》《算法知识》《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!“zoom: 33%;” />分享一些资料给大家,我觉得这些都是很有用的东西,大家也可以跟着来学习,查漏补缺。《Java高级面试》[外链图片转存中…(img-QFYqfW1j-1713396746362)]《Java高级架构知识》

2301_76323084的博客 624

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Spring-security

授权就是认证完成之后发生的,拥有不同的权限的用户访问不同的资源认证是为了确保用户身份的合法性,保护系统的隐私和资源授权是为了更细颗粒度的对隐私数据做出划分。

dllxhcjla的博客 180

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

JWT安全审计实战:算法混淆与None攻击的检测与修复

JSON Web Token(JWT)作为现代Web应用身份认证与授权的核心机制,其安全性直接关系到整个系统的数据防护能力。JWT通过数字签名确保令牌的完整性与可信度,但在实际应用中,若验证逻辑存在缺陷,攻击者可利用算法混淆攻击或None Algorithm漏洞伪造身份令牌,导致严重的越权风险。从工程实践角度,开发者需深入理解JWT的签名验证原理,在代码层面严格固定验证算法与密钥来源,杜绝信任客户端可控的算法声明。本文聚焦JWT安全审计,结合高频出现的算法混淆与None漏洞,提供从代码审计、动态测试到加固修

weixin_34320724的博客 428

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

(原创)Spring security用户验证机制浅谈.

1.  首先CustomUserDetailsService需要实现UserDetailsService(org.springframework.security.core.userdetails.UserDetailsService)接口, 实现获取用户Detail信息的回调函数. 必须要实现的方法是loadUserByUsername 注意: 这里的user类必须继承userDetail

d7011800的专栏 3万+

Spring security用户验证机制浅谈.

1.  首先CustomUserDetailsService需要实现UserDetailsService(org.springframework.security.core.userdetails.UserDetailsService)接口,实现获取用户Detail信息的回调函数.必须要实现的方法是loadUserByUsername 注意: 这里的user类必须继承userDetail类,并且

空城旧事的博客 1016
上一篇: Spring MVC 静态资源的访问
下一篇: 解决Spring Security 开启remember-me(持久化),session并发控制后重启服务器remember-me持久化凭证消失问题
Chenctrl
博客等级 码龄11年 2粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值