Using default security password

 

不展示Using default security password的解决办法:

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
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;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        // ALTOUGH THIS SEEMS LIKE USELESS CODE,
        // ITS REQUIRED TO PREVEND SPRING BOOT AUTO-CONFIGURATION
        return super.authenticationManagerBean();
    }
}

http://techqa.info/programming/question/30761253/Remove--Using-default-security-password--on-Spring-Boot

上面解决办法解析:

2017-08-01 11:21:51.295  INFO 4224 --- [           main] b.a.s.AuthenticationManagerConfiguration : 

Using default security password: b6adf691-a379-4bf4-aa84-95c20f5292b3

上述打印的条件:
org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration.DefaultInMemoryUserDetailsManagerConfigurer#configure

    private static class DefaultInMemoryUserDetailsManagerConfigurer
            extends InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> {

        private final SecurityProperties securityProperties;

        DefaultInMemoryUserDetailsManagerConfigurer(
                SecurityProperties securityProperties) {
            this.securityProperties = securityProperties;
        }

        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            if (auth.isConfigured()) {
                return;
            }
            User user = this.securityProperties.getUser();
            if (user.isDefaultPassword()) {
                logger.info(String.format("%n%nUsing default security password: %s%n",
                        user.getPassword()));
            }
            Set<String> roles = new LinkedHashSet<String>(user.getRole());
            withUser(user.getName()).password(user.getPassword())
                    .roles(roles.toArray(new String[roles.size()]));
            setField(auth, "defaultUserDetailsService", getUserDetailsService());
            super.configure(auth);
        }

只要auth.isConfigured()成立,则就不会打印。
org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder#isConfigured

    public boolean isConfigured() {
        return !this.authenticationProviders.isEmpty() || this.parentAuthenticationManager != null;
    }

因为上面的Java Config中配置了AuthenticationManager,代码逻辑就走不到打印的代码

Although the Spring suite of projects is usually easy to integrate, you might have noticed that you usually end up typing the same configuration again and again, with only a few (but important!) details changing from project to project. Teams usually end up setting a “template” configuration which they clone and adapt for every new application. Isn’t there a better way to start a Spring project?

Well yes Sir: there’s Spring Boot!

Off with the configuration chore!

The aim of Spring Boot is to get you started as easily as possible. It proposes tosetup and auto-configure your Spring-based project based on specified starter POMs and sensible default settings.

For example, have a look at this POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>MyProject</name>
    <groupId>com.mycompany</groupId>
    <artifactId>myproject</artifactId>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId><strong>spring-boot-starter-parent</strong></artifactId>
        <version>1.1.6.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId><strong>spring-boot-starter-web</strong></artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId><strong>spring-boot-starter-logging</strong></artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId><strong>spring-boot-starter-jetty</strong></artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId><strong>spring-boot-starter-security</strong></artifactId>
        </dependency>
    </dependencies>
</project>

The above loads Spring Boot as the parent, then uses the four “starter” dependencies to:

  • add support for web development, including Spring MVC
  • support logging with the LogBack framework
  • import Jetty as the engine to run your application as standalone
  • add support for Spring Security

How easy was that?

Want to add support for Velocity or JPA? Just add the correct starter POM to the dependencies. Want to start writing those unit tests? Add the “test” starter POM and get JUnit, Hamcrest, Mockito and the Spring Test module all  at once.

Setting up an initial, vanilla configuration for your project is as easy as:

@ComponentScan
@EnableAutoConfiguration
public class MyApp {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApp.class);
        app.run(args);
    }
}

Notice the @EnableAutoConfiguration annotation? That tells SpringBoot to try and guess the most sensible configuration based on the specified dependencies.

Agreed, that won’t take you very far. But it’s a good starting point. From here you can start overriding Spring Boot defaults in order to customize the configuration based on what you need.

There would be a lot to write about Spring Boot, and to be honest I probably just started to scratch the surface of it. I kindly invite you to check spring.io for tutorials and examples on this. Mind you, their manual is also very well written!

Enabling Spring Security on Spring Boot

In this article I want to focus on some basic Spring Security configuration when working on top of Spring Boot.

As with every other feature, spring security is added by including the matching starter POM. Just by including that POM will get you a basic configuration setup that includes HTTP Basic authentication for all material except common static resources (css, js, etc.), low-level features such as XSS and CSRF protection , and an AuthenticationManager bean with an in-memory default user created for you.

When you run your Spring Boot application as a Java Application from your IDE, you will then notice the generated default user’s password in the logs :

Using default security password: 8a20d976-f937-49d3-a55f-059a1f6964ea

 

This is a great initial setup when you are at the very first development phases: you can now log in using “ user ” as the username and… that thing up there as the password.

Overriding the security defaults

Of course you might end up getting annoyed with this: every time you restart the application and need to log in, you need to search the generated password and copy-paste it to authenticate. Hardly practical!

Hopefully Spring Boot allows you to easily override this password generation by specifying these properties in an application.properties file located at the root of your resources (that is, src/main/resources ):

 

 

security.user.name=myOwnUser
security.user.password=myOwnPassword
security.user.role=ADMIN

 

security . user . name = myOwnUser

security . user . password = myOwnPassword

security . user . role = ADMIN

Restart the application and you can now log in using those credentials. That’s better!

… Although at some point you might end up needing more than one user for testing purposes. In order to do that we will need to bring in some Java configuration.

Authentication customization

In order to register more than one user, we need to build our ownAuthenticationManager configuration. The easiest way is to extend an instance of a WebSecurityConfigurerAdapter and override whatever we need, then expose that adapter as a bean.

For example, to build our own AuthenticationManager we can continue implementing the  MyApp class like this:

 

 

@ComponentScan
@EnableAutoConfiguration
public class MyApp {

    @Bean
    public WebSecurityConfigurerAdapter <strong>webSecurityConfigurerAdapter</strong>() {
        return <strong>new MySecurityConfigurer()</strong>;
    }

    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    public static class MySecurityConfigurer extends WebSecurityConfigurerAdapter {

        <strong>@Override</strong>
        protected void <strong>configure(AuthenticationManagerBuilder builder)</strong> throws Exception {
            builder.inMemoryAuthentication()
              .withUser("user").password("user").roles("USER")
              .and().withUser("admin").password("admin").roles("ADMIN");
        }
    }
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApp.class);
        app.run(args);
    }
}

 

@ ComponentScan

@ EnableAutoConfiguration

public class MyApp {

@ Bean

public WebSecurityConfigurerAdapter < strong > webSecurityConfigurerAdapter </ strong > ( ) {

return < strong > new MySecurityConfigurer ( ) < / strong > ;

}

@ Order ( SecurityProperties . ACCESS_OVERRIDE_ORDER )

public static class MySecurityConfigurer extends WebSecurityConfigurerAdapter {

< strong > @ Override < / strong >

protected void < strong > configure ( AuthenticationManagerBuilder builder ) < /strong > throws Exception {

builder . inMemoryAuthentication ( )

. withUser ( "user" ) . password ( "user" ) . roles ( "USER" )

. and ( ) . withUser ( "admin" ) . password ( "admin" ) . roles ( "ADMIN" ) ;

}

}

public static void main ( String [ ] args ) {

SpringApplication app = new SpringApplication ( MyApp . class ) ;

app . run ( args ) ;

}

}

The overridden method in the the static class exposes a builder instance which allows you to configure your users in a very straightforward manner. We use an in-memory authentication in our example, for simplicity reasons. But rest assured that you are not limited to in-memory storage for your application’s users!

When running the application again you will be able to log in using your configured users. However you will notice that the HTTP Basic authentication is gone: Spring Security now presents you a basic form to enter your credentials.

HTTP security customization

Let’s take back control of our HTTP security. In order to restore the HTTP Basic authentication, we override another configuration()  method from the extended WebSecurityConfigurerAdapter :

 

 

@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public static class MySecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.inMemoryAuthentication()
          .withUser("user").password("user").roles("USER")
          .and().withUser("admin").password("admin").roles("ADMIN");
    }

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

 

@ Order ( SecurityProperties . ACCESS_OVERRIDE_ORDER )

public static class MySecurityConfigurer extends WebSecurityConfigurerAdapter {

@ Override

protected void configure ( AuthenticationManagerBuilder builder ) throws Exception{

builder . inMemoryAuthentication ( )

. withUser ( "user" ) . password ( "user" ) . roles ( "USER" )

. and ( ) . withUser ( "admin" ) . password ( "admin" ) . roles ( "ADMIN" ) ;

}

 

< strong > @ Override < / strong >

protected void < strong > configure ( HttpSecurity http ) < / strong > throwsException {

http . authorizeRequests ( ) . anyRequest ( ) . authenticated ( ) . and ( ) . httpBasic( ) ;

}

}

This should give us back our beloved HTTP Basic authentication.

Of course, you might probably prefer a custom implementation of a login page. This can also be done using the HttpSecurity instance exposed by that configure()method:

 

 

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().<strong>antMatchers("/fonts/**")</strong>.permitAll().anyRequest().authenticated()
        .and().<strong>formLogin()</strong>.loginPage("/login.jsp").permitAll();
}

 

@ Override

protected void configure ( HttpSecurity http ) throws Exception {

http . authorizeRequests ( ) . < strong > antMatchers ( "/fonts/**" ) < / strong > .permitAll ( ) . anyRequest ( ) . authenticated ( )

. and ( ) . < strong > formLogin ( ) < / strong > . loginPage ( "/login.jsp" ) . permitAll( ) ;

}

The above code states that a form-based login will be enforced when authentication is needed. It will use the specified login page , which must beaccessible (permitted) to all (otherwise no one will be able to access that login page, which might be a bummer!).

So how about the rest of the chained methods?

Well, there’s a good chance that you will want your login page to be nice to look at. In order to do that, you will need for some resources to be accessible no matter what. Spring Boot makes some static resources accessible by default through Ant matchers: /css/**, /js/**, /images/** and **/favicon.ico will be permitted by default.

In the example above though, we also need access to a fonts folder which containsglyphicons used by the login page. So we specify that the default static resources, plus the content of the fonts folder specified by the ant matcher , should be permitted to all , while any other request to a resource should require authentication .

You can take it from here…

From this point on you should be able to take things into your hand by leveraging your Spring Security knowledge.

Usually the tricky part when working on top of Spring Boot is to understand what the framework provides by default and know how to override that, so that you can start using your configuration. I remember fighting Spring Boot in order to configure persistence with JPA, until I finally understood that it was all already configured for me.

Same thing goes with security: try to just override what needs to be, and let Spring Boot guide you for the rest.

Or if you really want to switch off the defaults entirely, you can add that@EnableWebSecurity annotation to your java configuration and take it from there. You’re the boss.

Cheers!

Like this? Why not sharing it?

 

http://www.tuicool.com/articles/i2YZvu

 

时间: 2024-10-27 17:15:22

Using default security password的相关文章

《Spring Boot官方指南》28.安全

28. 安全 如果Spring Security位于类路径上,那么Web应用程序将默认使用所有HTTP端点上的'basic'身份验证.要向Web应用程序添加方法级安全性,还可以为你想要的设置添加"@EnableGlobalMethodSecurity".通过点击Spring Security Reference能够找到更多的信息. 'AuthenticationManager' 有一个默认用户(用户名为'user' ,密码随机,在应用程序启动时在INFO级别输出) Using defa

spring security之httpSecurity 专题

  37.5.2 Resolving the CsrfToken Spring Security provides CsrfTokenArgumentResolver which can automatically resolve the current CsrfToken for Spring MVC arguments. By using @EnableWebSecurity you will automatically have this added to your Spring MVC

ORA-28002: the password will expire within 7 days 解决方法(后面部分为拷贝,前面加上了自己遇到的问题的时候解决方案)

  首先以管理员密码登录 如果发现仍然登录不进去了,可以将Oracle安装的Linux的系统时间提前,修改方法是: date -s 04/29/2014 date -s 17:52:00 clock -w   1. 查看用户的profile设置: SELECT username,profile FROM dba_users;   SELECT username,profile FROM dba_users; 一般用户的profile设置都为DEFAULT.2. 查看系统profiles中PASS

Spring Security笔记:使用BCrypt算法加密存储登录密码

在前一节使用数据库进行用户认证(form login using database)里,我们学习了如何把"登录帐号.密码"存储在db中,但是密码都是明文存储的,显然不太讲究.这一节将学习如何使用spring security3新加入的bcrypt算法,将登录加密存储到db中,并正常通过验证. 一.Bcrypt算法 1 int t = 0; 2 String password = "123456"; 3 System.out.println(password + &q

深入挖掘Windows脚本技术

window|脚本 [目录]1,前言2,回顾WSH对象3,WMI服务4,脚本也有GUI5,反查杀6,来做个后门7,结语8,参考资料 [前言]本文讲述一些Windows脚本编程的知识和技巧.这里的Windows脚本是指"Windows Script Host"(WSH Windows脚本宿主),而不是HTML或ASP中的脚本.前者由Wscript或Cscript解释,后两者分别由IE和IIS负责解释.描述的语言是VBScript.本文假设读者有一定的Windows脚本编程的基础.如果你对

用Visual C#中实现DB2数据库编程(转)

visual|编程|数据|数据库 在Visual Studio.NET Beta 1版本中访问IBM DB2等非SQL Server数据库通常是使用ADO.NET的ODBC方法,而在Beta 2中则改用OLE DB方式存取数据库. Beta1中连接字符串主要需声明数据库的ODBC的DNS名字,但Beta 2中的OLE DB连接的字符串就较复杂了,使用的类也不相同.由于DB2等数据库在大型机等应用中使用非常广泛,.NET自然会全力支持此类编程开发,为此,下文将逐步阐述OLE DB的DB2开发. O

Visual C#中实现DB2数据库编程

visual|编程|数据|数据库 在Visual Studio.NET Beta 1版本中访问IBM DB2等非SQL Server数据库通常是使用ADO.NET的ODBC方法,而在Beta 2中则改用OLE DB方式存取数据库. Beta1中连接字符串主要需声明数据库的ODBC的DNS名字,但Beta 2中的OLE DB连接的字符串就较复杂了,使用的类也不相同.由于DB2等数据库在大型机等应用中使用非常广泛,.NET自然会全力支持此类编程开发,为此,下文将逐步阐述OLE DB的DB2开发. O

.net下模拟不同身份登陆以获取不同权限

不管是asp.net.web service还是window service,程序运行的时候只有本地计算机的部分权限,有时候需要更大的权限,比如读写某台服务器或域中的一台计算机上的文件等,这就需要更大的权限,比如域帐户权限. 通过获取不同身份的WindowsImpersonationContext对象,可以模拟不同用户登陆,请看我生成的NetworkSecurity类的public static WindowsImpersonationContext ImpersonateUser(string

WCF 配置服务 演示

1.搭建IIS(具体步骤略)2.服务契约如下: namespace JianKunKing.NewVersion.Service { // 注意: 使用"重构"菜单上的"重命名"命令,可以同时更改代码.svc 和配置文件中的类名"NewVersionService". //[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.