Content Table

How to change default Java version

1: First run /usr/libexec/java_home -V which will output something like the following:

Matching Java Virtual Machines (2):
    1.8.0_25, x86_64:   "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home
    1.7.0_75, x86_64:   "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home

2: Pick the version you want to be the default (1.7.0_75 for arguments sake) then:

export JAVA_HOME=`/usr/libexec/java_home -v 1.7.0_75`

3: Now when you run java -version you will see:

java version "1.7.0_75"
Java(TM) SE Runtime Environment (build 1.7.0_75-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.75-b04, mixed mode)

4: Just add the above export JAVA_HOME … line to your shell’s init file(/.bash_profile).

Gradle 编码

Gradle 默认使用系统字符编码 (Windows 为 GBK,Linux 和 Mac 为 UTF-8),很多程序员都是使用 Windows,但是 Java 文件以及其他资源文件大多数都会使用 UTF-8 (因为要跨平台使用),在 Windows 开发时编译运行容易出现乱码,报错等。

Spring Security 加密密码

明文保存密码是不可取的,可以使用 SHABCrypt 等对密码进行加密。

BCrypt 算法与 MD5/SHA 算法有一个很大的区别,每次生成的 hash 值都是不同的,就可以免除存储 salt,暴力破解起来也更困难。BCrypt 加密后的字符长度比较长,有60位,所以用户表中密码字段的长度,如果打算采用 BCrypt 加密存储,字段长度不得低于 68(需要前缀 {bcrypt})。

下面的代码展示怎么使用 BCrypt 进行加密:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import org.junit.Test;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class EncryptPassword {
@Test
public void encrypt() {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

for (int i = 0; i < 5; ++i) {
// 每次生成的密码都不一样
String encryptedPassword = passwordEncoder.encode("Passw0rd");
System.out.println(encryptedPassword);
System.out.println(passwordEncoder.matches("Passw0rd", encryptedPassword)); // true
System.out.println(passwordEncoder.matches("Password", encryptedPassword)); // false
}
}
}

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$2a$10$l7vPVeqwb9GiVjURV5J2QO1CM5qxwk00/Ra5qEog0WgP7O5XV0Ble
true
false
$2a$10$jeyMfHF88mNJb9v.mQ7YiuZ8oTU.pHaiKdT1NLOM38eXj7heHZHg2
true
false
$2a$10$ux43/3JcHUC1hszyoJaH0eQhv7LkIVfL7p1cW80WxfxeTr2dUY6kO
true
false
$2a$10$KdUmhaJOJ30klEcKiYT25.fIRPrMs4xONHOQh4JvmpKSjJ8d9.QKG
true
false
$2a$10$gQKUOoFuevnCkoej3.AvAO9YzHKCKYmKuiSfEGHL22piY2FfNDQYu
true
false

随意取其中任意一个都可以,因为每次生成都是不一样的,所以取第一个就可以了。

Spring Security 用户信息数据源

前面章节中用户名、密码、权限都是写在配置文件里的,不能动态的管理用户的权限,大多数时候显然是不行的。这里介绍从其他数据源读取用户的信息,例如从数据库,LDAP 等。只需要给 authentication-provider 提供接口 UserDetailsService 的实现类即可,使用这个类获取用户的信息,涉及以下内容:

  • 修改 spring-security.xml 中的 authentication-provider
  • 类 UserDetailsService 实现了 Spring Security 的接口 UserDetailsService
  • 类 User
  • 类 UserService