SpringSecurity静态资源放行,登陆页面配置,权限访问控制,自定义403

2年前 (2022) 程序员胖胖胖虎阿
107 0 0

1:静态资源和无需权限页面放行

如果是static下的静态资源或者无需验证身份即可访问的页面,可以通过在SpringSecurity的配置类中配置放行:

 @Override
    protected void configure(HttpSecurity http) throws Exception {
				  http.authorizeRequests()
                //无需认证的为static下的静态资源,以及/index请求
                .antMatchers("/static/**","/index").permitAll()
                //其它所有请求都需要进行验证
                .anyRequest().authenticated();
    }

2:配置登录页面

自定义登陆页面,在控制器方法中写一个路径用来跳转到登陆页面,则可以在SpringSecurity配置类中配置登录页:

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin()
                //设置登录成功跳转
                .successForwardUrl("/success")
                //设置登录失败跳转
                .failureForwardUrl("/fail")
                //登录的url,默认为/login
                .loginProcessingUrl("/login")
                //自定义登录页
                .loginPage("请求登录页的url")
                .usernameParameter("表单中用户名的name属性值,默认为username")
                .passwordParameter("表单中密码的name属性值,默认为password");
    }

在执行登录的时候会走一个过滤器UsernamePasswordAuthenticationFilter: 里面默认的参数为username和password,可以通过usernameParameter和passwordParameter修改。

SpringSecurity静态资源放行,登陆页面配置,权限访问控制,自定义403

11:权限访问控制

方法 解释
hasAuthority 方法 如果当前的主体具有指定的权限,则返回 true,否则返回 false
hasAnyAuthority 方法 如果当前的主体有任何提供的角色的话,返回true
hasRole方法 如果当前主体具有指定的角色,则返回 true
hasAnyRole方法 表示用户具备任何一个条件都可以访问

注意如果是hasRole方法判断权限:则在为用户设置权限时需要使用ROLE_作为前缀:

authorityList=AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_test")//添加的权限为test

而在配置文件中判断时无需添加ROLE_前缀:

antMatchers("/test").hasRole("test")//无需添加前缀

在hasRole方法底层定义了ROLE_前缀:
SpringSecurity静态资源放行,登陆页面配置,权限访问控制,自定义403

测试四个方法:

                .antMatchers("/authority").hasAuthority("admin")
                //admin common都可以访问
                .antMatchers("/anyAuthority").hasAnyAuthority("admin,common")
                //vip1才能访问
                .antMatchers("/role").hasRole("admin")
                //vip2,vip3访问
                .antMatchers("/anyRole").hasAnyRole("admin,common")

12:自定义403页面

如果当前主体没有访问此请求的权限,则会产生403错误,可以在SpringSecurity的配置文件中添加403页面配置:

 protected void configure(HttpSecurity http) throws Exception {
        //403页面,无权限跳转
        http.exceptionHandling().accessDeniedPage("/403");
 }

在控制器方法中添加跳转到无权限页面的方法:

@GetMapping("/403")
    @ResponseBody
    public String error(){
        return "这是403错误页面";
    }

配置权限:

   .antMatchers("/dbUser").hasAuthority("dbUser")
   .antMatchers("/test403").hasRole("test")

测试:登录用户权限为dbuser,访问test权限下的请求会跳转到403错误页面

SpringSecurity静态资源放行,登陆页面配置,权限访问控制,自定义403

相关文章

暂无评论

暂无评论...