Spring boot - 如何覆盖spring security中的默认用户名和密码

标签 spring spring-boot spring-security

我有一个 spring boot 应用程序,我正在尝试实现 spring security 以覆盖 spring 生成的默认用户名和密码。但它不起作用。 spring 仍然使用默认的用户凭据。

@EnableWebSecurity
@Configuration
public class WebSecurityConfigurtion extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("demo").password("demo").roles("USER").and().withUser("admin")
                .password("admin").roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }

这是我主要的 Spring Boot 类

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class ,SecurityAutoConfiguration.class})

@EnableAsync
@EntityScan({ "com.demo.entity" })
@EnableJpaRepositories(basePackages = {"com.demo.repositories"})
@ComponentScan({ "com.demo.controller", "com.demo.service" })

@Import({SwaggerConfig.class})

public class UdeManagerServiceApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(UdeManagerServiceApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(UdeManagerServiceApplication.class, args);
    }

这是日志,显示生成的密码

    22:26:48.537 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
22:26:48.540 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/, /spring-boot/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter/target/classes/]
22:26:48.540 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Work/Spring/UdeManagerService/target/classes/]
2018-10-18 22:26:48.797 DEBUG 7652 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'configurationProperties' with highest search precedence

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.4.RELEASE)

2018-10-18 22:26:49.218 DEBUG 7652 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'servletConfigInitParams' with lowest search precedence
2018-10-18 22:26:49.219 DEBUG 7652 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'servletContextInitParams' with lowest search precedence
2018-10-18 22:26:49.220 DEBUG 7652 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'systemProperties' with lowest search precedence
2018-10-18 22:26:49.221 DEBUG 7652 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'systemEnvironment' with lowest search precedence
2018-10-18 22:26:49.222 DEBUG 7652 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Initialized StandardServletEnvironment with PropertySources [StubPropertySource {name='servletConfigInitParams'}, StubPropertySource {name='servletContextInitParams'}, MapPropertySource {name='systemProperties'}, SystemEnvironmentPropertySource {name='systemEnvironment'}]
2018-10-18 22:26:49.967  INFO 7652 --- [  restartedMain] c.c.U.UdeManagerServiceApplication       : Starting UdeManagerServiceApplication on TRV-LT-ANSAR with PID 7652 (C:\Work\Spring\UdeManagerService\target\classes started by Ansar.Samad in C:\Work\Spring\UdeManagerService)
2018-10-18 22:26:49.973 DEBUG 7652 --- [  restartedMain] c.c.U.UdeManagerServiceApplication       : Running with Spring Boot v2.0.4.RELEASE, Spring v5.0.8.RELEASE
2018-10-18 22:26:49.976  INFO 7652 --- [  restartedMain] c.c.U.UdeManagerServiceApplication       : No active profile set, falling back to default profiles: default
2018-10-18 22:26:50.614  INFO 7652 --- [  restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@23daa694: startup date [Thu Oct 18 22:26:50 IST 2018]; root of context hierarchy
2018-10-18 22:26:53.258 DEBUG 7652 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Removing PropertySource 'defaultProperties'
2018-10-18 22:26:53.428  INFO 7652 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$82d409fb] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-10-18 22:26:53.936  INFO 7652 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-10-18 22:26:53.959  INFO 7652 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-10-18 22:26:53.960  INFO 7652 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.32
2018-10-18 22:26:53.966  INFO 7652 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_162\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files (x86)/Java/jre1.8.0_181/bin/client;C:/Program Files (x86)/Java/jre1.8.0_181/bin;C:/Program Files (x86)/Java/jre1.8.0_181/lib/i386;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin;C:\phython3.6\Scripts\;C:\phython3.6\;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Java\jre1.8.0_131\bin;C:\cuia\bat;C:\apache-maven-3.5.0-bin\apache-maven-3.5.0\bin;JAVA_HOME;SPRING_HOME;C:\Program Files (x86)\Symantec\VIP Access Client\;C:\phython3.6;C:\Program Files\Git\cmd;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;TESTNG_HOME;C:\TestNg\testng-6.8.jar;C:\python-3.6.5\Scripts;C:\python-3.6.5;C:\Program Files (x86)\Yarn\bin\;C:\Program Files\nodejs\;;C:\Program Files\Microsoft VS Code\bin;C:\Users\Ansar.Samad\AppData\Local\Yarn\bin;C:\Users\Ansar.Samad\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\Ansar.Samad\AppData\Roaming\npm;C:\spring-tool-suite-3.9.5.RELEASE-e4.8.0-win32\sts-bundle\sts-3.9.5.RELEASE;;.]
2018-10-18 22:26:54.081  INFO 7652 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-10-18 22:26:54.082 DEBUG 7652 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT]
2018-10-18 22:26:54.082  INFO 7652 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3468 ms
2018-10-18 22:26:54.192  INFO 7652 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-18 22:26:54.193  INFO 7652 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-18 22:26:54.193  INFO 7652 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-18 22:26:54.193  INFO 7652 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-18 22:26:54.194  INFO 7652 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-10-18 22:26:54.194  INFO 7652 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-10-18 22:26:54.274 DEBUG 7652 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Replacing PropertySource 'servletContextInitParams' with 'servletContextInitParams'
2018-10-18 22:26:54.308 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : Driver class com.mysql.jdbc.Driver found in Thread context class loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@4e843ef9
2018-10-18 22:26:54.407 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : HikariPool-1 - configuration:
2018-10-18 22:26:54.409 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : allowPoolSuspension.............false
2018-10-18 22:26:54.409 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : autoCommit......................true
2018-10-18 22:26:54.409 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : catalog.........................none
2018-10-18 22:26:54.409 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : connectionInitSql...............none
2018-10-18 22:26:54.409 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : connectionTestQuery.............none
2018-10-18 22:26:54.410 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : connectionTimeout...............30000
2018-10-18 22:26:54.410 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : dataSource......................none
2018-10-18 22:26:54.410 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : dataSourceClassName.............none
2018-10-18 22:26:54.410 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : dataSourceJNDI..................none
2018-10-18 22:26:54.411 DEBUG 7652 --- [  restartedMain] com.zaxxer.hikari.HikariConfig           : dataSourceProperties............{password=<masked>}
2018-10-18 22:22018-10-18 22:35:45.240 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'operationAuthReader': no URL paths identified
2018-10-18 22:35:45.240 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'operationHiddenReader': no URL paths identified
2018-10-18 22:35:45.240 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'operationHttpMethodReader': no URL paths identified
2018-10-18 22:35:45.240 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'operationImplicitParameterReader': no URL paths identified
2018-10-18 22:35:45.240 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'operationImplicitParametersReader': no URL paths identified
2018-10-18 22:35:45.240 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'operationNicknameIntoUniqueIdReader': no URL paths identified
2018-10-18 22:35:45.240 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'operationNotesReader': no URL paths identified
2018-10-18 22:35:45.256 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'systemProperties': no URL paths identified
2018-10-18 22:35:45.256 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'systemEnvironment': no URL paths identified
2018-10-18 22:35:45.256 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry': no URL paths identified
2018-10-18 22:35:45.256 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'messageSource': no URL paths identified
2018-10-18 22:35:45.256 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'applicationEventMulticaster': no URL paths identified
2018-10-18 22:35:45.256 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'servletContext': no URL paths identified
2018-10-18 22:35:45.256 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'contextParameters': no URL paths identified
2018-10-18 22:35:45.256 DEBUG 6720 --- [  restartedMain] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'contextAttributes': no URL paths identified
2018-10-18 22:35:45.256  INFO 6720 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-18 22:35:45.256  INFO 6720 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-18 22:35:45.271 DEBUG 6720 --- [  restartedMain] .m.m.a.ExceptionHandlerExceptionResolver : Looking for exception mappings: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@275b060b: startup date [Thu Oct 18 22:35:35 IST 2018]; root of context hierarchy
2018-10-18 22:35:45.599  INFO 6720 --- [  restartedMain] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: e67dca07-3bc3-49e2-bc33-84c9643ef09a

2018-10-18 22:35:45.740  INFO 6720 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@6abf32c0, org.springframework.security.web.context.SecurityContextPersistenceFilter@b2b202e, org.springframework.security.web.header.HeaderWriterFilter@23ff67f5, org.springframework.security.web.csrf.CsrfFilter@a493c40, org.springframework.security.web.authentication.logout.LogoutFilter@776a660, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@334ce4e9, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@1f4c6b47, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@4a4c14a3, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@7793ba1a, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4edda6d8, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3e492163, org.springframework.security.web.session.SessionManagementFilter@68661010, org.springframework.security.web.access.ExceptionTranslationFilter@6920b121, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@35279a68]
2018-10-18 22:35:45.836  INFO 6720 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2018-10-18 22:35:45.867  INFO 6720 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-10-18 22:35:45.867  INFO 6720 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-10-18 22:35:45.883  INFO 6720 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-10-18 22:35:45.883  INFO 6720 --- [  restartedMain] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 2147483647
2018-10-18 22:35:45.883  INFO 6720 --- [  restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2018-10-18 22:35:45.899  INFO 6720 --- [  restartedMain] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2018-10-18 22:35:45.914  INFO 6720 --- [  restartedMain] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2018-10-18 22:35:46.086  INFO 6720 --- [  restartedMain] .d.s.w.r.o.CachingOperationNameGenerator : Generating unique operation named: testUsingPOST_1
2018-10-18 22:35:46.101  INFO 6720 --- [  restartedMain] .d.s.w.r.o.CachingOperationNameGenerator : Generating unique operation named: getDataUsingGET_1
2018-10-18 22:35:46.117 DEBUG 6720 --- [  restartedMain] o.s.w.s.resource.ResourceUrlProvider     : Looking for resource handler mappings
2018-10-18 22:35:46.117 DEBUG 6720 --- [  restartedMain] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**/favicon.ico", locations=[class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], ServletContext resource [/], class path resource []], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@3914bc92]
2018-10-18 22:35:46.117 DEBUG 6720 --- [  restartedMain] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/webjars/**", locations=[class path resource [META-INF/resources/webjars/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@3dc6f1f0]
2018-10-18 22:35:46.117 DEBUG 6720 --- [  restartedMain] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**", locations=[class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], ServletContext resource [/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@315362d4]
2018-10-18 22:35:47.196 DEBUG 6720 --- [onnection adder] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection com.mysql.jdbc.JDBC4Connection@edd709c
2018-10-18 22:35:49.180  INFO 6720 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-10-18 22:35:49.180 DEBUG 6720 --- [  restartedMain] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'server.ports' with highest search precedence
2018-10-18 22:35:49.180  INFO 6720 --- [  restartedMain] c.c.U.UdeManagerServiceApplication       : Started UdeManagerServiceApplication in 14.132 seconds (JVM running for 14.884)
2018-10-18 22:35:50.929 DEBUG 6720 --- [onnection adder] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection com.mysql.jdbc.JDBC4Connection@7a5e8413

最佳答案

在您的 application.properties 文件中添加此代码

spring.security.user.name = root -- 这是你的用户名

spring.security.user.password = root -- 这是你的密码

spring.security.user.roles = user --这是你的角色

关于Spring boot - 如何覆盖spring security中的默认用户名和密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879261/

相关文章:

spring-boot - 如何创建用于签署 JWT token 的 Spring 安全 key ?

java - Spring security - 指定顺序时多个 httpsecurity 不起作用

spring-security - 在 Auth0 中同时使用机器对机器和常规身份验证

java - Java Spring框架: Multiple Threads and TaskExecutor

java - REST 中的 @DateTimeFormat 变量给出 null

java - @RequestParam 对象中的枚举列表

linux - Spring Boot 应用程序即服务 + VM 选项

java - 使用 Java DSL 成功 ftp 传输后移动文件

javascript - 无法在spring security中加载静态内容

java - Spring Java Mail - 如何知道发送的邮件被收件人阅读、退回或转发?