我试图在未经授权的情况下访问我的网站的主页,但是,当我访问它时,Spring一直要求登录。
我在SecurityConfig中对其进行了配置以允许此操作,但它仍无效。
SecurityConfig.java
package com.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import security.MyUserDetailsService;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private MyUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/", true)
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(encoder());
return authProvider;
}
@Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder(11);
}
}
我还添加了一个初始化程序类,看它是否可以解决问题,但我认为在spring-boot中不需要它。
初始化程序
package com.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer{
public SecurityInitializer() {
super(SecurityConfig.class);
}
}
我可以在没有身份验证的情况下将POST发送到/ login,当我在配置中禁用csrf保护时,它会选择它,所以我认为Spring没有找到配置是不是问题。
以下是Spring的日志
:: Spring Boot :: (v1.5.4.RELEASE)
2017-07-19 03:09:22.347 INFO 7832 --- [ restartedMain] com.mp.DemoApplication : Starting DemoApplication on Meade with PID 7832 (C:\Users\markp\git\Abbraa\target\classes started by markp in C:\Users\markp\git\Abbraa)
2017-07-19 03:09:22.348 INFO 7832 --- [ restartedMain] com.mp.DemoApplication : No active profile set, falling back to default profiles: default
2017-07-19 03:09:22.771 INFO 7832 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@39cff043: startup date [Wed Jul 19 03:09:22 CDT 2017]; root of context hierarchy
2017-07-19 03:09:24.027 INFO 7832 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'scopedTarget.oauth2ClientContext' with a different definition: replacing [Root bean: class [null]; scope=session; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=org.springframework.security.oauth2.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientContextConfiguration; factoryMethodName=oauth2ClientContext; initMethodName=null; destroyMethodName=(inferred); defined in org.springframework.security.oauth2.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientContextConfiguration] with [Root bean: class [null]; scope=session; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2RestOperationsConfiguration$SessionScopedConfiguration$ClientContextConfiguration; factoryMethodName=oauth2ClientContext; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration$SessionScopedConfiguration$ClientContextConfiguration.class]]
2017-07-19 03:09:24.394 WARN 7832 --- [ restartedMain] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance @Configuration bean definition 'beanNamePlaceholderRegistryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2017-07-19 03:09:24.764 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Post-processing PropertySource instances
2017-07-19 03:09:24.792 INFO 7832 --- [ restartedMain] c.u.j.c.StringEncryptorConfiguration : String Encryptor custom Bean not found with name 'jasyptStringEncryptor'. Initializing String Encryptor based on properties with name 'jasyptStringEncryptor'
2017-07-19 03:09:24.801 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Converting PropertySource commandLineArgs [org.springframework.core.env.SimpleCommandLinePropertySource] to EncryptableEnumerablePropertySourceWrapper
2017-07-19 03:09:24.801 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Converting PropertySource servletConfigInitParams [org.springframework.core.env.PropertySource$StubPropertySource] to EncryptablePropertySourceWrapper
2017-07-19 03:09:24.802 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Converting PropertySource servletContextInitParams [org.springframework.core.env.PropertySource$StubPropertySource] to EncryptablePropertySourceWrapper
2017-07-19 03:09:24.802 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Converting PropertySource systemProperties [org.springframework.core.env.MapPropertySource] to EncryptableMapPropertySourceWrapper
2017-07-19 03:09:24.802 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Converting PropertySource systemEnvironment [org.springframework.core.env.SystemEnvironmentPropertySource] to EncryptableMapPropertySourceWrapper
2017-07-19 03:09:24.803 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Converting PropertySource random [org.springframework.boot.context.config.RandomValuePropertySource] to EncryptablePropertySourceWrapper
2017-07-19 03:09:24.803 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Converting PropertySource applicationConfig: [classpath:/application.properties] [org.springframework.core.env.PropertiesPropertySource] to EncryptableMapPropertySourceWrapper
2017-07-19 03:09:24.803 INFO 7832 --- [ restartedMain] eEncryptablePropertySourcesPostProcessor : Converting PropertySource refresh [org.springframework.core.env.MapPropertySource] to EncryptableMapPropertySourceWrapper
2017-07-19 03:09:25.629 INFO 7832 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-07-19 03:09:25.644 INFO 7832 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-07-19 03:09:25.645 INFO 7832 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-07-19 03:09:25.900 INFO 7832 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-07-19 03:09:25.900 INFO 7832 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3133 ms
2017-07-19 03:09:26.249 INFO 7832 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-19 03:09:26.250 INFO 7832 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-07-19 03:09:26.250 INFO 7832 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-07-19 03:09:26.251 INFO 7832 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'OAuth2ClientContextFilter' to: [/*]
2017-07-19 03:09:26.251 INFO 7832 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-07-19 03:09:26.253 INFO 7832 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2017-07-19 03:09:26.253 INFO 7832 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-07-19 03:09:26.254 INFO 7832 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'webServlet' to [/h2-console/*]
2017-07-19 03:09:27.168 INFO 7832 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-07-19 03:09:27.191 INFO 7832 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-07-19 03:09:27.281 INFO 7832 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-07-19 03:09:27.283 INFO 7832 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-07-19 03:09:27.286 INFO 7832 --- [ restartedMain] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-07-19 03:09:27.341 INFO 7832 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-07-19 03:09:27.489 INFO 7832 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-07-19 03:09:27.840 INFO 7832 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-07-19 03:09:27.848 INFO 7832 --- [ restartedMain] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-07-19 03:09:27.887 INFO 7832 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-07-19 03:09:28.186 INFO 7832 --- [ restartedMain] b.a.s.AuthenticationManagerConfiguration :
Using default security password: b93e6b62-c3c6-41c6-b1fb-aff865c47624
2017-07-19 03:09:28.513 INFO 7832 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/authorize]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(java.util.Map<java.lang.String, java.lang.Object>,java.util.Map<java.lang.String, java.lang.String>,org.springframework.web.bind.support.SessionStatus,java.security.Principal)
2017-07-19 03:09:28.514 INFO 7832 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/authorize],methods=[POST],params=[user_oauth_approval]}" onto public org.springframework.web.servlet.View org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.approveOrDeny(java.util.Map<java.lang.String, java.lang.String>,java.util.Map<java.lang.String, ?>,org.springframework.web.bind.support.SessionStatus,java.security.Principal)
2017-07-19 03:09:28.515 INFO 7832 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/token],methods=[GET]}" onto public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException
2017-07-19 03:09:28.516 INFO 7832 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/token],methods=[POST]}" onto public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException
2017-07-19 03:09:28.517 INFO 7832 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/check_token]}" onto public java.util.Map<java.lang.String, ?> org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint.checkToken(java.lang.String)
2017-07-19 03:09:28.517 INFO 7832 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/confirm_access]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelApprovalEndpoint.getAccessConfirmation(java.util.Map<java.lang.String, java.lang.Object>,javax.servlet.http.HttpServletRequest) throws java.lang.Exception
2017-07-19 03:09:28.518 INFO 7832 --- [ restartedMain] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped "{[/oauth/error]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelErrorEndpoint.handleError(javax.servlet.http.HttpServletRequest)
2017-07-19 03:09:29.074 INFO 7832 --- [ restartedMain] a.OAuth2AuthorizationServerConfiguration : Initialized OAuth2 Client
security.oauth2.client.clientId = 8f83ba6f-ddd0-4584-989e-8bf15d9ca800
security.oauth2.client.secret = 90f22f41-57ea-4a35-b4aa-f2e2c228b9c5
2017-07-19 03:09:29.546 INFO 7832 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@39cff043: startup date [Wed Jul 19 03:09:22 CDT 2017]; root of context hierarchy
2017-07-19 03:09:29.655 INFO 7832 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.mp.MainController.index()
2017-07-19 03:09:29.656 INFO 7832 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/logon],methods=[POST]}" onto public java.lang.String com.mp.MainController.login(java.lang.String,java.lang.String)
2017-07-19 03:09:29.660 INFO 7832 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-07-19 03:09:29.661 INFO 7832 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-07-19 03:09:29.738 INFO 7832 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-19 03:09:29.738 INFO 7832 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-19 03:09:29.816 INFO 7832 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-19 03:09:30.844 INFO 7832 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2017-07-19 03:09:30.978 INFO 7832 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@147facd0, org.springframework.security.web.context.SecurityContextPersistenceFilter@57681424, org.springframework.security.web.header.HeaderWriterFilter@60769ed5, org.springframework.security.web.authentication.logout.LogoutFilter@7abdb07c, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@69b1535d, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@6fc31f04, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@1388aafd, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@77b72eb9, org.springframework.security.web.session.SessionManagementFilter@26bc4252, org.springframework.security.web.access.ExceptionTranslationFilter@b0ad272, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@6190b047]
2017-07-19 03:09:30.995 INFO 7832 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/h2-console/**'], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4464b064, org.springframework.security.web.context.SecurityContextPersistenceFilter@57affbac, org.springframework.security.web.header.HeaderWriterFilter@29e75695, org.springframework.security.web.authentication.logout.LogoutFilter@7f423605, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@5798d0da, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@24ff986, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@110f44a4, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6fb5646d, org.springframework.security.web.session.SessionManagementFilter@2079db43, org.springframework.security.web.access.ExceptionTranslationFilter@245e3d72, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@e6e5393]
2017-07-19 03:09:31.017 INFO 7832 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/**']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@26d80f5b, org.springframework.security.web.context.SecurityContextPersistenceFilter@243b400b, org.springframework.security.web.header.HeaderWriterFilter@dbb1e82, org.springframework.security.web.authentication.logout.LogoutFilter@35f7f5a9, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@4b32c004, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@a677b9e, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@5ffd3b5e, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@22a0c587, org.springframework.security.web.session.SessionManagementFilter@8d5dbd, org.springframework.security.web.access.ExceptionTranslationFilter@6bd8b55f, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@1b162e0f]
2017-07-19 03:09:31.236 INFO 7832 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2017-07-19 03:09:31.313 INFO 7832 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-07-19 03:09:31.431 INFO 7832 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-07-19 03:09:31.439 INFO 7832 --- [ restartedMain] com.mp.DemoApplication : Started DemoApplication in 9.556 seconds (JVM running for 10.373)
2017-07-19 03:09:42.498 INFO 7832 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-07-19 03:09:42.498 INFO 7832 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-07-19 03:09:42.540 INFO 7832 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 41 ms
我想知道我在使用SecurityConfig.configure方法的方式是否有问题,或者是否有其他原因导致它不允许访问。
答案 0 :(得分:0)
我的问题是我的项目结构不正确,因为我的主要应用程序与我的一些配置不同。我能够通过将主应用程序移动到根包中来解决问题。我查看了Spring样式指南,发现Autoconfig和Component扫描需要在主应用程序的子包中包含所有其他文件才能正常工作。
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html