默认的用户名和密码
配置用户名和密码
重写WebSecurityConfigurerAdapter方法
auth.inMemoryAuthentication()
.withUser("root")
.password(password)
.authorities("ADMIN");
密码编码器
配置多个用户名和密码
配置请求路径
http.formLogin()// 表单认证
.loginPage(securityProperties.getAuthentication().getLoginPage())// 交给 /login/page 响应认证(登录)页面
.loginProcessingUrl(securityProperties.getAuthentication().getLoginProcessingUrl())// 登录表单提交处理Url, 默认是 /login
.usernameParameter(securityProperties.getAuthentication().getUsernameParameter())// 默认用户名的属性名是 username
.passwordParameter(securityProperties.getAuthentication().getPasswordParameter())// 默认密码的属性名是 password
.successHandler(customAuthenticationSuccessHandler)//认证成功处理器
.failureHandler(customAuthenticationFailureHandler)//认证失败处理器
.and()
.authorizeRequests()//认证请求
.antMatchers(securityProperties.getAuthentication().getLoginPage(),"/code/image").permitAll()// 放行跳转认证请求
.anyRequest().authenticated()// 所有进入应用的HTTP请求都要进行认证
代码片段
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}
http.authorizeRequests()方法有多个子节点,每个macher按照他们的声明顺序执行。
我们指定任何用户都可以通过访问的多个URL模式。任何用户都可以访问URL以"/resources/", equals “/signup”,
或者 “/about"开头的URL。 以 “/admin/” 开头的URL只能由拥有 “ROLE_ADMIN"角色的用户访问。请注意我们使用
hasRole 方法,没有使用 “ROLE_” 前缀. 任何以”/db/” 开头的URL需要用户同时具有 “ROLE_ADMIN” 和
“ROLE_DBA”。和上面一样我们的 hasRole 方法也没有使用 “ROLE_” 前缀. 尚未匹配的任何URL要求用户进行身份验证
LDAP 验证
多个HttpSecurity
我们可以配置多个HttpSecurity实例,就像我们可以有多个块. 关键在于对WebSecurityConfigurationAdapter进行多次扩展。例如下面是一个对/api/开头的URL进行的不同的设置。
@EnableWebSecurity
public class MultiHttpSecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}
@Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
}
- 配置正常的验证。
- 创建一个WebSecurityConfigurerAdapter,包含一个@Order注解,用来指定个哪一个WebSecurityConfigurerAdapter更优先。
- http.antMatcher指出,这个HttpSecurity只应用到以/api/开头的URL上。
- 创建另外一个WebSecurityConfigurerAdapter实例。用于不以/api/开头的URL,这个配置的顺序在ApiWebSecurityConfigurationAdapter之后,因为他没有指定@Order值为1(没有指定@Order默认会被放到最后).