美文网首页Spring Security
SpringSecurity匹配规则

SpringSecurity匹配规则

作者: FlyXhc | 来源:发表于2019-02-20 11:44 被阅读26次

    SpringSecurity匹配规则

    一 URL匹配

    1. requestMatchers() 配置一个request Mather数组,参数为RequestMatcher 对象,其match 规则自定义,需要的时候放在最前面,对需要匹配的的规则进行自定义与过滤
    2. authorizeRequests() URL权限配置
    3. antMatchers() 配置一个request Mather 的 string数组,参数为 ant 路径格式, 直接匹配url
    4. anyRequest 匹配任意url,无参 ,最好放在最后面

    二 保护URL

    1. authenticated() 保护UrL,需要用户登录
    2. permitAll() 指定URL无需保护,一般应用与静态资源文件
    3. hasRole(String role) 限制单个角色访问,角色将被增加 “ROLE_” .所以”ADMIN” 将和 “ROLE_ADMIN”进行比较. 另一个方法是hasAuthority(String authority)
    4. hasAnyRole(String… roles) 允许多个角色访问. 另一个方法是hasAnyAuthority(String… authorities)
    5. access(String attribute) 该方法使用 SPEL, 所以可以创建复杂的限制 例如如access("permitAll"), access("hasRole('ADMIN') and hasIpAddress('123.123.123.123')")
    6. hasIpAddress(String ipaddressExpression) 限制IP地址或子网

    三 登录login

    1. formLogin() 基于表单登录
    2. loginPage() 登录页
    3. defaultSuccessUrl 登录成功后的默认处理页
    4. failuerHandler登录失败之后的处理器
    5. successHandler登录成功之后的处理器
    6. failuerUrl登录失败之后系统转向的url,默认是this.loginPage + "?error"

    四 登出logout

    1. logoutUrl 登出url , 默认是/logout, 它可以是一个ant path url
    2. logoutSuccessUrl 登出成功后跳转的 url 默认是"/login?logout"
    3. logoutSuccessHandler 登出成功处理器,设置后会把logoutSuccessUrl 置为null

    下面的代码片段就不会拦截/user,因为只会匹配"/api/**"

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            http.requestMatchers().antMatchers("/api/**")
            .and().authorizeRequests().antMatchers("/user","/api/user").authenticated()
            .anyRequest().authenticated()
            .and().formLogin().loginPage("/login");
            //需要人证
       //     http.authorizeRequests().antMatchers("/user").hasRole("Admin");
           // .and().formLogin().loginPage("/login");
            //api请求都不需要权限认证
         //   http.authorizeRequests().antMatchers("/api").permitAll();
            // data/** Get请求不需要权限人证
         //   http.authorizeRequests().antMatchers(HttpMethod.GET,"/data/**").permitAll();
        }
    }
    

    相关文章

      网友评论

        本文标题:SpringSecurity匹配规则

        本文链接:https://www.haomeiwen.com/subject/zjncyqtx.html