HttpSecurity用于在实际的业务场景中针对不同的URL采用不同的权限处理策略,一般会在重载WebSecurityConfigurerAdapter基类的configure(HttpSecurity httpSecurity)方法中完成权限策略的处理。
HttpSecurity是SecurityBuilder接口的一个实现类,这是一个HTTP安全相关的构建器。当然我们在构建时可能需要一些配置,当我们调用HttpSecurity对象的方法时,实际上就是在进行配置。
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// 注解标记允许匿名访问的url
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
httpSecurity
// CSRF禁用,因为不使用session
.csrf().disable()
// 认证失败处理类
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// 基于token,所以不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 过滤请求
.authorizeRequests()
// 1. 对于登录、注册和验证码等方法允许匿名访问
.antMatchers("/login", "/register", "/captchaImage").anonymous()
// 2. 对于静态资源允许任何用户访问
.antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
// 3. 对于SWAGGER相关信息允许任何用户访问
.antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
// 除上面1.2.3.以外的所有请求全部需要鉴权认证
.anyRequest().authenticated()
.and()
.headers().frameOptions().disable();
// 添加自定义的登出处理器
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 在UsernamePasswordAuthenticationFilter之前添加自定义的JWT过滤器
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 在自定义的JWT过滤器前添加跨域过滤器
httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
// 在用户登出过滤器前添加跨域过滤器
httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
// 限定"/user/welcome"请求,需要赋予角色 ROLE_USER 或者 ROLE_ADMIN
.antMatchers("/user/welcome").hasAnyRole("USER", "ADMIN")
// 限定"/admin/**"下所有请求,需要赋予角色 ROLE_ADMIN
.antMatchers("/admin/**").hasAnyAuthority("ROLE_ADMIN")
// 其他路径允许签名后访问
.anyRequest().permitAll()
// 对于没有配置权限的其他请求允许匿名访问
.and().anonymous()
// 使用spring security 默认的登录页面
.and().formLogin()
// 启动 HTTP 基础验证
.and().httpBasic();
}
①. antMatchers:用于添加地址匹配规则,支持正则表达式;
②. hasAnyRole:一般和antMatchers成对出现,用于设定antMatchers的访问权限,只要具有指定权限,即可访问前面配置的访问规则;
③. hasAnyAuthority:和hasAnyRole类似也和antMatchers成对出现,不同的是hasAnyAuthority指定的是具体的权限;
④. and方法 :它是连接词,表示可以重新加入新的权限验证规则,相当于返回配置对象;
⑤. anyRequest:表示上面限定的所有请求,如:antMatchers(“/user/welcome”).hasAnyRole(“USER”, “ADMIN”)这样的配置;
⑥. permitAll:表示对请求无条件允许访问;
⑦. anonymous:表示对请求允许匿名访问;
⑧. formLogin:表示开启security默认的登录页,也可以自定义登录页和登录成功的页面。
| 方法 | 说明 |
|---|---|
| openidLogin() | 基于 OpenId 的验证 |
| headers() | 将安全头添加到响应 |
| cors() | 配置跨域资源共享 |
| sessionManagement() | 允许配置会话管理 |
| portMapper() | 允许配置一个PortMapper(HttpSecurity#(getSharedObject(class))),其他提供SecurityConfigurer的对象使用 PortMapper 从 HTTP 重定向到 HTTPS 或者从 HTTPS 重定向到 HTTP。默认情况下,Spring Security使用一个PortMapperImpl映射 HTTP 端口8080到 HTTPS 端口8443,HTTP 端口80到 HTTPS 端口443 |
| jee() | 配置基于容器的预认证,在这种情况下,认证由Servlet容器管理 |
| x509() | 配置基于x509的认证 |
| rememberMe | 配置“记住我”的验证 |
| authorizeRequests() | 配置基于使用HttpServletRequest限制访问 |
| requestCache() | 配置请求缓存 |
| exceptionHandling() | 配置错误处理 |
| securityContext() | 在HttpServletRequests之间的SecurityContextHolder上设置SecurityContext的管理,当使用WebSecurityConfigurerAdapter时,默认启用 |
| servletApi() | 将HttpServletRequest方法与在其上找到的值集成到SecurityContext中, 当使用WebSecurityConfigurerAdapter时,默认启用 |
| csrf() | 添加 CSRF 支持,使用WebSecurityConfigurerAdapter时,默认启用 |
| logout() | 添加退出登录支持,当使用WebSecurityConfigurerAdapter时,默认启用。默认情况是,访问URL”/ logout”,使HTTP Session无效来清除用户,清除已配置的任何#rememberMe()身份验证,清除SecurityContextHolder,然后重定向到”/login?success” |
| anonymous() | 配置匿名用户的表示方法, 当与WebSecurityConfigurerAdapter结合使用时,默认启用。 默认情况下,匿名用户将使用org.springframework.security.authentication.AnonymousAuthenticationToken表示,并包含角色 “ROLE_ANONYMOUS” |
| formLogin() | 配置支持基于表单的身份验证。如果未指定FormLoginConfigurer#loginPage(String),则将生成默认登录页面 |
| oauth2Login() | 根据外部OAuth 2.0或OpenID Connect 1.0提供程序配置身份验证 |
| requiresChannel() | 配置通道安全,为了使该配置有用,必须提供至少一个到所需信道的映射 |
| httpBasic() | 配置 Http Basic 验证 |
| addFilterBefore() | 在指定的Filter类之前添加过滤器 |
| addFilterAt() | 在指定的Filter类的位置添加过滤器 |
| addFilterAfter() | 在指定的Filter类的之后添加过滤器 |
| and() | 连接以上策略的连接器,用来组合安全策略,实际上就是"而且"的意思 |