spring-security中 HttpSecurity 的语法规则

May 9, 2018

Spring scurity 的配置需要继承自 WebSecurityConfigurerAdapter 覆盖对应的方法就可以了。

  1. HttpSecurity.antMatcher(...)

    表示该安全规则只针对参数指定的路径进行过滤, 因为只可以接受一个参数, 所以如果想指定多个使用下一个方法.

  2. HttpSecurity.requestMatchers.requestMatchers(...)

    同上, 唯一的区别是可以接受多个参数, 注意:两者不能同时使用, 如果没有指定则是指匹配所有,即相当于匹配 “ /** “!

  3. HttpSecurity.authorizeRequests()

    该方法用于配置权限,如 hasAnyRole(…), access(….)。

  4. HttpSecurity.authorizeRequests().antMatchers(...).authenticated()

    对匹配参数指定的路径进行权限认证, 如果没有认证或者认证失败 返回 HttpServletResponse.SC_FORBIDDEN(403) 对于没有指定的路径, 但是匹配(1)/(2)中指定的路径, 将跳过权限认证, 而且不执行之后的权限认证(如果配置了多个安全认证), 相当于匿名认证

  5. HttpSecurity.authorizeRequests().antMatchers(...).anonymous()

    匿名的权限认证(即:权限认证通过,并且为匿名), (4)中的第二条相当于该权限.

  6. .authorizeRequests().anyRequest()

    除去已经配置了的路径之外的其他路径, 即包含在(1)/(2)中不包含在 HttpSecurity.authorizeRequests().antMatchers(…) 中的其他路径.

  7. HttpSecurity.httpBasic

    表示认证方式使用浏览器默认的方式(弹出用户名密码的对话框,即curl -u 选项)。如果不匹配返回 HttpServletResponse.SC_UNAUTHORIZED(401)

如果需要多个认证方式 (有的需要httpbase认证, 有的需要登录认证, 有的需要oauth认证等等),直接实现多个 WebSecurityConfigurerAdapter 即可,每次配置不同的过滤地址 (配置前面1或2的规则) 即可。注意:需要根据需要配置不同的 @Order(…) 因为默认为100,当配置多个会产生冲突!

Demo 如下:

    @Configuration
    @Order(101)
    public static class LoginAuthorizationConfig extends WebSecurityConfigurerAdapter {

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.requestMatchers().antMatchers("/i/**", "/admin/**", "/info/**")//
                    .and().authorizeRequests()//
                    .antMatchers("/i/**").hasAnyRole("USER")//
                    .antMatchers("/admin/**").hasAnyRole("ADMIN")//
                    .and().formLogin().loginPage("/login.html")//
                    .and().csrf().disable();
        }

    }

    @Configuration
    @Order(102)
    public static class HttpBasicAuthorizationConfig extends WebSecurityConfigurerAdapter {

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/rpc/**")//
                    .authorizeRequests().antMatchers("/rpc/**").authenticated()//
                    .and().httpBasic().and().csrf().disable();
        }

    }

    @Configuration
    @Order(103)
    public static class Oauth2AuthorizationServerConfig extends ResourceServerConfiguration {
        //ResourceServerConfiguration  继承自 WebSecurityConfigurerAdapter 需要解析 access(...)

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.requestMatchers().antMatchers("/me/**")//
                    .and().authorizeRequests()//
                    .antMatchers("/me/**").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))")//
                    .and().csrf().disable();
        }

    }

(完)