请求验证时被重定向到 /login
验证失败失败时被重定向到 /login?error
登出成功时会被重定向到 /login?logout
permitAll()方法声明允许在未验证时任何访问到的资源和URL,如果不加则连访问/login 都会一直被重定向
HttpSecurity类:类似XML配置中的元素,可以配置基于web的安全请求,默认下,它会作用于所有的请求,但是可以使用 requestMatcher(RequestMatcher)等类似方法进行限制
以下方法定义只有“USER”角色的用户才能访问“/”URL(即任何请求)
1 protected void configure(HttpSecurity http) throwsException {2 http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin();3 }
常用方法:
antMatcher(String antPattern):配置只有当匹配该路径模式时才调用 HttpSecurity
authorizeRequests():限制基于HttpServletRequest之上的使用
csrf():添加CSRF支持
configureGlobalSecurity(AuthenticationManagerBuilder auth)用来指定从何处获取用户
configure(HttpSecurity http)用来配置访问每个URL所需的对应权限
UserDetails
UserDetails 是一个 Spring Security 的核心接口,代表一个主体(包含于用户相关的信息)。
在 Authentication 接口中有一个方法 Object getPrincipal(); 这个方法返回的是一个安全主题,大多数情况下,这个对象可以强制转换成 UserDetails 对象,获取到UerDetails 对象之后,就可以通过这个对象的 getUserName()方法获取当前用户名。
自定义验证:通过暴露类型为AuthenticationProvider或者UserDetailsService的bean,使用的验证设置优先级高到低排序为AuthenticationManagerBuilder、AuthenticationProvider、UserDetailsService,即要是发现存在使用前者的配置,则后者的配置无效
通过暴露一个PasswordEncoder类型的bean来定义密码使使用何种编码,如下使用bcrypt
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
开启方法注解
在任何配置类(使用@Configuration注解的类)头上添加 @EnableGlobalMethodSecurity注解,然后就可以使用@Secured等方法级注解进行安全配置,可以为方法定义一系列属性,这些配置将会通过AccessDecisionManager来实际决定