在本文中,我们将详细介绍SpringSecurity:WebSecurityConfig类`antMatchers(...).permitAll()`不起作用的各个方面,并为您提供关于springse
在本文中,我们将详细介绍Spring Security:WebSecurityConfig 类`antMatchers(...).permitAll()` 不起作用的各个方面,并为您提供关于spring security permitall 无效的相关解答,同时,我们也将为您带来关于java – 通过@Profile启用WebSecurityConfigurer不起作用、org.apache.catalina.security.SecurityConfig的实例源码、org.springframework.boot.autoconfigure.security.SecurityProperties.Headers的实例源码、org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration的实例源码的有用知识。
本文目录一览:- Spring Security:WebSecurityConfig 类`antMatchers(...).permitAll()` 不起作用(spring security permitall 无效)
- java – 通过@Profile启用WebSecurityConfigurer不起作用
- org.apache.catalina.security.SecurityConfig的实例源码
- org.springframework.boot.autoconfigure.security.SecurityProperties.Headers的实例源码
- org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration的实例源码
Spring Security:WebSecurityConfig 类`antMatchers(...).permitAll()` 不起作用(spring security permitall 无效)
如何解决Spring Security:WebSecurityConfig 类`antMatchers(...).permitAll()` 不起作用?
我正在向我的 Spring 应用程序添加一个新端点。我正在使用 Spring Security 检查 JWT 中的角色并授予访问权限。但是,现在我什至没有检查角色,而是允许所有人使用该 URL。我已经有三个可以按预期工作的端点 POST
。第四个端点 GET
方法是我遇到问题的地方。
请检查以下配置,如果我遗漏了什么,请告诉我。
免责声明:我从这个配置类中删除了 bean 和依赖注入对象,以显示我的问题所在。
@EnableWebSecurity
@ComponentScan(value = {"com.mywebsite.framework.security","com.mywebsite.utility"})
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(crossplatformFilter,SessionManagementFilter.class)
.csrf().disable()
.authorizeRequests()
// WORKS AS EXPECTED
.antMatchers(HttpMethod.POST,"/mywebsite/v1/something_1").permitAll()
// WORKS AS EXPECTED
.antMatchers(HttpMethod.POST,"/mywebsite/v1/something_2").permitAll()
// WORKS AS EXPECTED
.antMatchers(HttpMethod.POST,"/mywebsite/v1/something_3").permitAll()
// NOT WORKING,RETURNS 401 Http Code
.antMatchers(HttpMethod.GET,"/mywebsite/v1/something_4").permitAll() //Todo: Not Working,returning 401
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtAuthenticationFilter,UsernamePasswordAuthenticationFilter.class).authorizeRequests();
}
}
我刚刚添加了第四个 .antMatchers()
,不知道为什么,返回 401。前三个 .antMatchers()
没有任何问题。
有没有人遇到过和我一样的问题?
我只是添加了一个端点作为 GET。
日志:
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 1 of 15 in additional filter chain; firing Filter: ''WebAsyncManagerIntegrationFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 2 of 15 in additional filter chain; firing Filter: ''SecurityContextPersistenceFilter''
w.c.HttpSessionSecurityContextRepository.readSecurityContextFromSession 167 -- No HttpSession currently exists
w.c.HttpSessionSecurityContextRepository.loadContext 117 -- No SecurityContext was available from the HttpSession: null. A new one will be created.
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 3 of 15 in additional filter chain; firing Filter: ''HeaderWriterFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 4 of 15 in additional filter chain; firing Filter: ''CsrfFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 5 of 15 in additional filter chain; firing Filter: ''logoutFilter''
o.s.s.w.u.m.AntPathRequestMatcher.matches 157 -- Request ''GET /mywebsite/v1/something_4'' doesn''t match ''POST /logout''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 6 of 15 in additional filter chain; firing Filter: ''UsernamePasswordAuthenticationFilter''
o.s.s.w.u.m.AntPathRequestMatcher.matches 157 -- Request ''GET /mywebsite/v1/something_4'' doesn''t match ''POST /login''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 7 of 15 in additional filter chain; firing Filter: ''DefaultLoginPageGeneratingFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 8 of 15 in additional filter chain; firing Filter: ''DefaultlogoutPageGeneratingFilter''
o.s.s.w.u.m.AntPathRequestMatcher.matches 177 -- Checking match of request : ''/mywebsite/v1/something_4''; against ''/logout''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 9 of 15 in additional filter chain; firing Filter: ''BasicAuthenticationFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 10 of 15 in additional filter chain; firing Filter: ''RequestCacheAwareFilter''
o.s.s.w.s.HttpSessionRequestCache.getMatchingRequest 95 -- saved request doesn''t match
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 11 of 15 in additional filter chain; firing Filter: ''SecurityContextHolderAwareRequestFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 12 of 15 in additional filter chain; firing Filter: ''AnonymousAuthenticationFilter''
o.s.s.w.a.AnonymousAuthenticationFilter.doFilter 100 -- Populated SecurityContextHolder with anonymous token: ''org.springframework.security.authentication.AnonymousAuthenticationToken@bddba886: 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''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 13 of 15 in additional filter chain; firing Filter: ''SessionManagementFilter''
o.s.s.w.s.SessionManagementFilter.doFilter 124 -- Requested session ID 17C1F2C0B0E165F7DCF87E14CDB0F6DA is invalid.
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 14 of 15 in additional filter chain; firing Filter: ''ExceptionTranslationFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /mywebsite/v1/something_4 at position 15 of 15 in additional filter chain; firing Filter: ''FilterSecurityInterceptor''
o.s.s.a.i.AbstractSecurityInterceptor.beforeInvocation 219 -- Secure object: FilterInvocation: URL: /mywebsite/v1/something_4; Attributes: [authenticated]
o.s.s.a.i.AbstractSecurityInterceptor.authenticateIfrequired 348 -- PrevIoUsly Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@bddba886: 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
o.s.s.a.v.AffirmativeBased .decide 66 -- Voter: org.springframework.security.web.access.expression.WebExpressionVoter@56253eba,returned: -1
o.s.s.w.a.ExceptionTranslationFilter.handleSpringSecurityException 180 -- 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.3.8.RELEASE.jar:5.3.8.RELEASE]
...........
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using Ant [pattern=''/**'',GET]
o.s.s.w.u.m.AntPathRequestMatcher.matches 167 -- Request ''/mywebsite/v1/something_4'' matched by universal pattern ''/**''
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using NegatedRequestMatcher [requestMatcher=Ant [pattern=''/**/favicon.*'']]
o.s.s.w.u.m.AntPathRequestMatcher.matches 177 -- Checking match of request : ''/mywebsite/v1/something_4''; against ''/**/favicon.*''
o.s.s.w.u.m.NegatedRequestMatcher.matches 51 -- matches = true
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,matchingMediaTypes=[application/json],useEquals=false,ignoredMediaTypes=[*/*]]]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 203 -- httpRequestMediaTypes=[*/*]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 207 -- Processing */*
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 210 -- Ignoring
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 231 -- Did not match any media types
o.s.s.w.u.m.NegatedRequestMatcher.matches 51 -- matches = true
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using NegatedRequestMatcher [requestMatcher=RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With,expectedHeaderValue=XMLHttpRequest]]
o.s.s.w.u.m.NegatedRequestMatcher.matches 51 -- matches = true
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,matchingMediaTypes=[multipart/form-data],ignoredMediaTypes=[*/*]]]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 203 -- httpRequestMediaTypes=[*/*]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 207 -- Processing */*
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 210 -- Ignoring
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 231 -- Did not match any media types
o.s.s.w.u.m.NegatedRequestMatcher.matches 51 -- matches = true
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,matchingMediaTypes=[text/event-stream],ignoredMediaTypes=[*/*]]]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 203 -- httpRequestMediaTypes=[*/*]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 207 -- Processing */*
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 210 -- Ignoring
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 231 -- Did not match any media types
o.s.s.w.u.m.NegatedRequestMatcher.matches 51 -- matches = true
o.s.s.w.u.m.AndRequestMatcher .matches 73 -- All requestMatchers returned true
o.s.s.w.s.HttpSessionRequestCache.saveRequest 61 -- DefaultSavedRequest added to Session: DefaultSavedRequest[http://localhost:8080/mywebsite/v1/something_4]
o.s.s.w.a.ExceptionTranslationFilter.sendStartAuthentication 211 -- Calling Authentication entry point.
s.w.a.DelegatingAuthenticationEntryPoint.commence 78 -- Trying to match using AndRequestMatcher [requestMatchers=[NegatedRequestMatcher [requestMatcher=RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With,expectedHeaderValue=XMLHttpRequest]],MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,matchingMediaTypes=[application/xhtml+xml,image/*,text/html,text/plain],ignoredMediaTypes=[*/*]]]]
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using NegatedRequestMatcher [requestMatcher=RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With,expectedHeaderValue=XMLHttpRequest]]
o.s.s.w.u.m.NegatedRequestMatcher.matches 51 -- matches = true
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,ignoredMediaTypes=[*/*]]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 203 -- httpRequestMediaTypes=[*/*]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 207 -- Processing */*
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 210 -- Ignoring
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 231 -- Did not match any media types
o.s.s.w.u.m.AndRequestMatcher .matches 69 -- Did not match
s.w.a.DelegatingAuthenticationEntryPoint.commence 78 -- Trying to match using OrRequestMatcher [requestMatchers=[RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With,expectedHeaderValue=XMLHttpRequest],AndRequestMatcher [requestMatchers=[NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,matchingMediaTypes=[text/html],ignoredMediaTypes=[]]],matchingMediaTypes=[application/atom+xml,application/x-www-form-urlencoded,application/json,application/octet-stream,application/xml,multipart/form-data,text/xml],ignoredMediaTypes=[*/*]]]],matchingMediaTypes=[*/*],useEquals=true,ignoredMediaTypes=[]]]]
o.s.s.w.u.m.OrRequestMatcher .matches 65 -- Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With,expectedHeaderValue=XMLHttpRequest]
o.s.s.w.u.m.OrRequestMatcher .matches 65 -- Trying to match using AndRequestMatcher [requestMatchers=[NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,ignoredMediaTypes=[*/*]]]]
o.s.s.w.u.m.AndRequestMatcher .matches 66 -- Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,ignoredMediaTypes=[]]]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 203 -- httpRequestMediaTypes=[*/*]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 207 -- Processing */*
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 223 -- text/html .isCompatibleWith */* = true
o.s.s.w.u.m.NegatedRequestMatcher.matches 51 -- matches = false
o.s.s.w.u.m.AndRequestMatcher .matches 69 -- Did not match
o.s.s.w.u.m.OrRequestMatcher .matches 65 -- Trying to match using MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@5bb661e0,ignoredMediaTypes=[]]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 203 -- httpRequestMediaTypes=[*/*]
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 207 -- Processing */*
o.s.s.w.u.m.MediaTypeRequestMatcher.matches 216 -- isEqualTo true
o.s.s.w.u.m.OrRequestMatcher .matches 68 -- matched
s.w.a.DelegatingAuthenticationEntryPoint.commence 83 -- Match found! Executing org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint@3d3e9163
s.w.a.DelegatingAuthenticationEntryPoint.commence 78 -- Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With,expectedHeaderValue=XMLHttpRequest]
s.w.a.DelegatingAuthenticationEntryPoint.commence 91 -- No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@4da27f00
o.s.s.w.h.w.HstsHeaderWriter .writeHeaders 169 -- Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@2784c3cd
tRepository$SavetoSessionResponseWrapper.saveContext 346 -- SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
tRepository$SavetoSessionResponseWrapper.saveContext 346 -- SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
s.s.w.c.SecurityContextPersistenceFilter.doFilter 119 -- SecurityContextHolder Now cleared,as request processing completed
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 1 of 15 in additional filter chain; firing Filter: ''WebAsyncManagerIntegrationFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 2 of 15 in additional filter chain; firing Filter: ''SecurityContextPersistenceFilter''
w.c.HttpSessionSecurityContextRepository.readSecurityContextFromSession 179 -- HttpSession returned null object for SPRING_Security_CONTEXT
w.c.HttpSessionSecurityContextRepository.loadContext 117 -- No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@591f2d03. A new one will be created.
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 3 of 15 in additional filter chain; firing Filter: ''HeaderWriterFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 4 of 15 in additional filter chain; firing Filter: ''CsrfFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 5 of 15 in additional filter chain; firing Filter: ''logoutFilter''
o.s.s.w.u.m.AntPathRequestMatcher.matches 157 -- Request ''GET /error'' doesn''t match ''POST /logout''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 6 of 15 in additional filter chain; firing Filter: ''UsernamePasswordAuthenticationFilter''
o.s.s.w.u.m.AntPathRequestMatcher.matches 157 -- Request ''GET /error'' doesn''t match ''POST /login''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 7 of 15 in additional filter chain; firing Filter: ''DefaultLoginPageGeneratingFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 8 of 15 in additional filter chain; firing Filter: ''DefaultlogoutPageGeneratingFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 9 of 15 in additional filter chain; firing Filter: ''BasicAuthenticationFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 10 of 15 in additional filter chain; firing Filter: ''RequestCacheAwareFilter''
o.s.s.w.s.DefaultSavedRequest .propertyEquals 359 -- pathInfo: both null (property equals)
o.s.s.w.s.DefaultSavedRequest .propertyEquals 359 -- queryString: both null (property equals)
o.s.s.w.s.DefaultSavedRequest .propertyEquals 383 -- requestURI: arg1=/mywebsite/v1/something_4; arg2=/error (property not equals)
o.s.s.w.s.HttpSessionRequestCache.getMatchingRequest 95 -- saved request doesn''t match
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 11 of 15 in additional filter chain; firing Filter: ''SecurityContextHolderAwareRequestFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 12 of 15 in additional filter chain; firing Filter: ''AnonymousAuthenticationFilter''
o.s.s.w.a.AnonymousAuthenticationFilter.doFilter 100 -- Populated SecurityContextHolder with anonymous token: ''org.springframework.security.authentication.AnonymousAuthenticationToken@bddba886: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: EC7B42A8FB862A6AEBDC3CD49485BEE9; Granted Authorities: ROLE_ANONYMOUS''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 13 of 15 in additional filter chain; firing Filter: ''SessionManagementFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 14 of 15 in additional filter chain; firing Filter: ''ExceptionTranslationFilter''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 328 -- /error at position 15 of 15 in additional filter chain; firing Filter: ''FilterSecurityInterceptor''
.s.w.FilterChainProxy$VirtualFilterChain.doFilter 313 -- /error reached end of additional filter chain; proceeding with original chain
tRepository$SavetoSessionResponseWrapper.saveContext 346 -- SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
o.s.s.w.a.ExceptionTranslationFilter.doFilter 120 -- Chain processed normally
tRepository$SavetoSessionResponseWrapper.saveContext 346 -- SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
s.s.w.c.SecurityContextPersistenceFilter.doFilter 119 -- SecurityContextHolder Now cleared,as request processing completed
解决方法
未加载安全配置...我没有在服务中加载 WebConfig java 类..... 我将它添加到我的服务配置中的 @Import(...)
中,并且成功了 :)
java – 通过@Profile启用WebSecurityConfigurer不起作用
我希望当我通过Spring Boot运行此应用程序时,我指定本地配置文件时,我的自定义安全设置将覆盖默认行为.
mvn -Dspring.profiles.active =“local”spring-boot:run
也许我正在指定profiles.active错误,但是当应用程序运行时,它仍会吐出生成的密码以供使用,并且似乎不允许在没有所述身份验证的情况下访问/ login路径.
我也没有看到/ env下的活动配置文件,这可能有点说.
我有一个WebSecurityConfigurer被覆盖,如下所示:
@Configuration @EnableWebSecurity @Profile("local") @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().fullyAuthenticated().and().formLogin().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN","USER") .and().withUser("user").password("user").roles("USER"); } }
我的主要@Configuration类是您标准的Spring Java风格的基本配置:
@Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
解决方法
>完全永久地关闭安全性:
>从类路径中删除Spring Security
>或排除安全性自动配置 – @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
>通过设置security.basic.enabled = false来关闭默认的基本身份验证安全性
如果您完全控制安全设置,安全自动配置和弹簧配置文件的使用方式,则可以非常轻松地控制不同的安全设置.
@Configuration @ComponentScan public class Application { public static void main(String[] args) throws Throwable { SpringApplication.run(Application.class,args); } } @Configuration public class WebSecurityConfig { @Configuration @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) @ConditionalOnExpression("!${my.security.enabled:false}") protected static class DefaultWebSecurityConfig { } @Configuration @EnableAutoConfiguration @EnableWebMvcSecurity @Profile("local") @ConditionalOnExpression("${my.security.enabled:false}") protected static class LocalWebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/","/home").permitAll() .anyRequest().authenticated(); http .formLogin().loginPage("/login").permitAll().and() .logout().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } } }
在上面的类中,我基本上从Application类顺序中删除了@EnableAutoConfiguration以有条件地使用它.创建了两个配置类,DefaultWebSecurityConfig和LocalWebSecurityConfig,它们由my.security.enabled标志使用Boot @ConditionalOnExpression选择.
如果我的安全性未启用,则第一个配置只会排除SecurityAutoConfiguration.第二个启用安全性并使用本地配置文件.通过使用不同的配置文件创建另一个配置,您可以控制不同配置文件发生的情况.然后,您可以选择是否启用安全性以及使用哪个配置文件:
#java -jar build/libs/gs-securing-web-0.1.0.jar #java -jar build/libs/gs-securing-web-0.1.0.jar --spring.profiles.active=local --my.security.enabled=true
如果您可以选择使用application.yml,则每个配置文件可以自动应用不同的设置,但仍定义默认值.如果您只想禁用默认安全自动配置启用的默认基本身份验证,这将是一件好事.
security: basic: enabled: false --- spring: profiles: local security: basic: enabled: true ---
可能有一百万种不同的方法来执行这些操作,并且始终根据具体情况最适合当前用例.
org.apache.catalina.security.SecurityConfig的实例源码
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. Todo */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection() { SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection() { SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
/** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDeFinition(); securityConfig.setPackageAccess(); }
org.springframework.boot.autoconfigure.security.SecurityProperties.Headers的实例源码
public static void configureHeaders(HeadersConfigurer<?> configurer,SecurityProperties.Headers headers) throws Exception { if (headers.getHsts() != Headers.HSTS.NONE) { boolean includeSubdomains = headers.getHsts() == Headers.HSTS.ALL; HstsHeaderWriter writer = new HstsHeaderWriter(includeSubdomains); writer.setRequestMatcher(AnyRequestMatcher.INSTANCE); configurer.addHeaderWriter(writer); } if (!headers.isContentType()) { configurer.contentTypeOptions().disable(); } if (!headers.isXss()) { configurer.xssprotection().disable(); } if (!headers.isCache()) { configurer.cacheControl().disable(); } if (!headers.isFrame()) { configurer.frameOptions().disable(); } }
public static void configureHeaders(HeadersConfigurer<?> configurer,SecurityProperties.Headers headers) throws Exception { if (headers.getHsts() != Headers.HSTS.NONE) { boolean includeSubdomains = headers.getHsts() == Headers.HSTS.ALL; HstsHeaderWriter writer = new HstsHeaderWriter(includeSubdomains); writer.setRequestMatcher(AnyRequestMatcher.INSTANCE); configurer.addHeaderWriter(writer); } if (!headers.isContentType()) { configurer.contentTypeOptions().disable(); } if (!headers.isXss()) { configurer.xssprotection().disable(); } if (!headers.isCache()) { configurer.cacheControl().disable(); } if (!headers.isFrame()) { configurer.frameOptions().disable(); } }
public static void configureHeaders(HeadersConfigurer<?> configurer,SecurityProperties.Headers headers) throws Exception { if (headers.getHsts() != Headers.HSTS.NONE) { boolean includeSubdomains = headers.getHsts() == Headers.HSTS.ALL; HstsHeaderWriter writer = new HstsHeaderWriter(includeSubdomains); writer.setRequestMatcher(AnyRequestMatcher.INSTANCE); configurer.addHeaderWriter(writer); } if (!headers.isContentType()) { configurer.contentTypeOptions().disable(); } if (!headers.isXss()) { configurer.xssprotection().disable(); } if (!headers.isCache()) { configurer.cacheControl().disable(); } if (!headers.isFrame()) { configurer.frameOptions().disable(); } }
org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration的实例源码
@Override protected void configure(HttpSecurity http) throws Exception { // secure endpoints RequestMatcher matcher = getRequestMatcher(); if (matcher != null) { // Always protect them if present if (this.security.isRequireSsl()) { http.requiresChannel().anyRequest().requiresSecure(); } AuthenticationEntryPoint entryPoint = entryPoint(); http.exceptionHandling().authenticationEntryPoint(entryPoint); // Match all the requests for actuator endpoints ... http.requestMatcher(matcher); // ... but permitAll() for the non-sensitive ones configurePermittedRequests(http.authorizeRequests()); http.httpBasic().authenticationEntryPoint(entryPoint); // No cookies for management endpoints by default http.csrf().disable(); http.sessionManagement().sessionCreationPolicy( this.management.getSecurity().getSessions()); SpringBootWebSecurityConfiguration.configureHeaders(http.headers(),this.security.getHeaders()); } }
@Override protected void configure(HttpSecurity http) throws Exception { // secure endpoints RequestMatcher matcher = getRequestMatcher(); if (matcher != null) { // Always protect them if present if (this.security.isRequireSsl()) { http.requiresChannel().anyRequest().requiresSecure(); } AuthenticationEntryPoint entryPoint = entryPoint(); http.exceptionHandling().authenticationEntryPoint(entryPoint); // Match all the requests for actuator endpoints ... http.requestMatcher(matcher); // ... but permitAll() for the non-sensitive ones configurePermittedRequests(http.authorizeRequests()); http.httpBasic().authenticationEntryPoint(entryPoint); // No cookies for management endpoints by default http.csrf().disable(); http.sessionManagement().sessionCreationPolicy( this.management.getSecurity().getSessions()); SpringBootWebSecurityConfiguration.configureHeaders(http.headers(),this.security.getHeaders()); } }
@Override public void init(WebSecurity builder) throws Exception { IgnoredRequestConfigurer ignoring = builder.ignoring(); // The ignores are not cumulative,so to prevent overwriting the defaults we // add them back. List<String> ignored = SpringBootWebSecurityConfiguration .getIgnored(this.security); if (!this.management.getSecurity().isEnabled()) { ignored.addAll(Arrays .asList(EndpointPaths.ALL.getPaths(this.endpointHandlerMapping))); } if (ignored.contains("none")) { ignored.remove("none"); } if (this.errorController != null) { ignored.add(normalizePath(this.errorController.getErrorPath())); } if (this.server != null) { String[] paths = this.server.getPathsArray(ignored); ignoring.antMatchers(paths); } }
@Override protected void configure(HttpSecurity http) throws Exception { // secure endpoints RequestMatcher matcher = getRequestMatcher(); if (matcher != null) { // Always protect them if present if (this.security.isRequireSsl()) { http.requiresChannel().anyRequest().requiresSecure(); } AuthenticationEntryPoint entryPoint = entryPoint(); http.exceptionHandling().authenticationEntryPoint(entryPoint); // Match all the requests for actuator endpoints ... http.requestMatcher(matcher); // ... but permitAll() for the non-sensitive ones configurePermittedRequests(http.authorizeRequests()); http.httpBasic().authenticationEntryPoint(entryPoint); // No cookies for management endpoints by default http.csrf().disable(); http.sessionManagement().sessionCreationPolicy( this.management.getSecurity().getSessions()); SpringBootWebSecurityConfiguration.configureHeaders(http.headers(),this.security.getHeaders()); } }
我们今天的关于Spring Security:WebSecurityConfig 类`antMatchers(...).permitAll()` 不起作用和spring security permitall 无效的分享就到这里,谢谢您的阅读,如果想了解更多关于java – 通过@Profile启用WebSecurityConfigurer不起作用、org.apache.catalina.security.SecurityConfig的实例源码、org.springframework.boot.autoconfigure.security.SecurityProperties.Headers的实例源码、org.springframework.boot.autoconfigure.security.SpringBootWebSecurityConfiguration的实例源码的相关信息,可以在本站进行搜索。
本文标签: