不展示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

Using default security password的更多相关文章

  1. 错误的另一个常见原因是默认的安全组规则。default security group默认情况下不允许ICMP(ping命令使用的协议)

    可以在openstack horizon界面中添加ICMP和ssh(TCP)规则,也可以通过命令行.命令行方式给默认安全组添加规则的方法如下: $ nova secgroup-add-rule def ...

  2. Spring Security基本配置

    Spring Security 是一个功能强大且可高度自定义的身份验证和访问控制框架. 它是保护基于Spring的应用程序的事实上的标准.Spring Security 是一个专注于为Java应用程序 ...

  3. Spring Security构建Rest服务-0600-SpringSecurity基本原理

    一.引入 只要引入了spring-boot-starter-security,所有的服务都会被保护起来.启动项目,打开时所有的controller会被保护起来,随便访问一个,如http://local ...

  4. Spring Boot Security配置教程

    1.简介 在本文中,我们将了解Spring Boot对spring Security的支持. 简而言之,我们将专注于默认Security配置以及如何在需要时禁用或自定义它. 2.默认Security设 ...

  5. SpringBoot + Spring Security 基本使用及个性化登录配置详解

    Spring Security 基本介绍 这里就不对Spring Security进行过多的介绍了,具体的可以参考官方文档 我就只说下SpringSecurity核心功能: 认证(你是谁) 授权(你能 ...

  6. springboot security 安全

    spring security几个概念 “认证”(Authentication) 是建立一个他声明的主体的过程(一个“主体”一般是指用户,设备或一些可以在你的应用程序中执行动作的其他系统) . “授权 ...

  7. Spring Security基本原理

    近期研究了Spring Security,现进行记录. 首先先进行一个最简单的demo.默认情况下,在Spring Boot里,如果在classpath下面有Spring Security相关的jar ...

  8. trackr: An AngularJS app with a Java 8 backend – Part IV 实践篇

    REST API对于前后端或后端与后端之间通讯是一个好的接口,而单页应用Single Page Applications (SPA)非常流行. 我们依然以trackr为案例,这是一个跟踪工作时间 请假 ...

  9. SpringCloud系列三:SpringSecurity 安全访问(配置安全验证、服务消费端处理、无状态 Session 配置、定义公共安全配置程序类)

    1.概念:SpringSecurity 安全访问 2.具体内容 所有的 Rest 服务最终都是暴露在公网上的,也就是说如果你的 Rest 服务属于一些你自己公司的私人业务,这样的结果会直接 导致你信息 ...

随机推荐

  1. u-boot分析1:Nandflash、Norflash启动

    了解u-boot之前首先了解下Bootloader,简单说Bootloader就是一段小程序,它在系统上电时开始运行,初始化硬件设备,准备好软件环境,最后调用操作系统内核. u-boot全称:Univ ...

  2. 【习题 3-6 UVA - 232】Crossword Answers

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 模拟题.注意场宽为3 [代码] #include <bits/stdc++.h> using namespace std ...

  3. UVA 11728 - Alternate Task (数论)

    Uva 11728 - Alternate Task 题目链接 题意:给定一个因子和.求出相应是哪个数字 思路:数字不可能大于因子和,对于每一个数字去算出因子和,然后记录下来就可以 代码: #incl ...

  4. [Maven实战](6)仓库(本地仓库,远程仓库,镜像)

    1. 简单介绍 maven能够在某个位置统一存储全部maven项目共享的构件,这个统一的位置就是仓库.实际的Maven项目将不会各自存储其依赖文件,它们仅仅须要声明这些依赖的坐标,在须要的时候(比如. ...

  5. License控制实现原理(20140808)

    近期须要做一个License控制的实现,做了一个设计,设计图例如以下: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGVjX2Zlbmc=/font/5 ...

  6. 嵌入式arm linux环境中gdb+gdbserver调试

    一.前言嵌入式Linux系统中,应用开发过程中,很多情况下,用户需要对一个应用程序进行反复调试,特别是复杂的程序.采用GDB方法调试,由于嵌入式系统资源有限性,一般不能直接在目标系统上进行调试,通常采 ...

  7. word vba 1 页面视图

  8. UVALive - 4960 Sensor network(生成树+LCA)

    题目大意:给出N个点.M条边.问这N个点形成的生成树的最大权值边-最小权值边的最小值 解题思路:先排序,然后按生成树的kruscal算法进行加边,再维护一个最小权值边 加边的时候要考虑一下加下去的边是 ...

  9. javascrit开发的基本代码结构的

    今天看到群里一个demo,简单看了一下. 然后自己就写了一个通用的javascrit开发的基本代码结构的js文件. 代码例如以下: (function($,win){ //定义全局变量对象 var o ...

  10. php框架排名(Laravel一直第一)

    php框架排名(Laravel一直第一) 一.总结 1.Laravel,后面就用这个框架(要用好这个框架,英语得6啊) 2.YII框架和tp框架一样,也是一个国产框架 二.2017世界PHP框架排名T ...