当前位置: 首页> 教育> 高考 > Spring Security框架如何授权

Spring Security框架如何授权

时间:2025/7/11 17:59:17来源:https://blog.csdn.net/susjj663/article/details/140623604 浏览次数:0次

一、授权

授权的方式包括 web授权和方法授权

  • web授权是通过 url 拦截进行授权,重点学习内容

  • 方法授权是通过方法拦截进行授权,通过注解的方式控制权限,粒度小,耦合度高

1、WEB授权
(1)、案例

我们可以做个例子,演示一下

1.准备工作,修改HelloController,增加两个方法 (根据hello方法复制后修改即可),主要是为了方便后边进行测试

@RequestMapping("/hello/user")
public String helloUser(){Authentication authentication = SecurityContextHolder.getContext().getAuthentication();String name = authentication.getName();return "hello-user  "+name;
}@RequestMapping("/hello/admin")
public String helloAdmin(){Authentication authentication = SecurityContextHolder.getContext().getAuthentication();String name = authentication.getName();return "hello-admin  "+name;
}

2.修改 SecurityConfig 的securityFilterChain方法 ,添加对以上两个地址的角色控制

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.formLogin()             //自定义自己编写的登陆页面.loginPage("/login.html")    //登录页面设置.loginProcessingUrl("/login") //登录访问路径.permitAll()//登录页和登录访问路径无需登录也可以访问.and().authorizeRequests().antMatchers("/css/**","/images/**").permitAll().antMatchers("/hello/user").hasRole("USER").antMatchers("/hello/admin").hasAnyRole("ADMIN").anyRequest().authenticated().and().csrf().disable();    //关闭csrf防护return http.build();
}

3.测试

分别使用user和admin用户登录

  • user用户可以访问 /hello/user

  • admin用户可以访问 /hello/user/hello/admin

2、控制操作方法

上文只是将请求接口路径与配置的规则进行匹配,那匹配成功之后应该进行什么操作呢?Spring Security 内置了一些控制操作。

  • permitAll() 方法,所有用户可访问。

  • denyAll() 方法,所有用户不可访问。

  • authenticated() 方法,登录用户可访问。

  • anonymous() 方法,匿名用户可访问。

  • rememberMe() 方法,通过 remember me 登录的用户可访问。

  • fullyAuthenticated() 方法,非 remember me 登录的用户可访问。

  • hasIpAddress(String ipaddressExpression) 方法,来自指定 IP 表达式的用户可访问。

  • hasRole(String role) 方法, 拥有指定角色的用户可访问,传入的角色将被自动增加 “ROLE_” 前缀。

  • hasAnyRole(String... roles) 方法,拥有指定任意角色的用户可访问。传入的角色将被自动增加 “ROLE_” 前缀。

  • hasAuthority(String authority) 方法,拥有指定权限( authority )的用户可访问。

  • hasAnyAuthority(String... authorities) 方法,拥有指定任意权限( authority )的用户可访问。

关键字:Spring Security框架如何授权

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: