如何控制项目的访问权限来保证项目安全?SpringBoot 集成 Spring Security 安全框架使用指南

209 阅读2分钟

安全框架

  • shiro
  • Spring Security
  • 应用程序的两个主要区域:认证授权(这两个主要区域是Spring Security的两个目标)
    • 认证(Authentication):
      • 建立一个声明的主体过程
      • 一个[主体]一般是指[用户],[设备]或一些可以[在应用程序中执行动作的其它系统]
    • 授权(Authorization):
      • 访问控制确定一个主体是否允许在你的应用程序执行一个动作的过程
      • 为了抵达需要授权的点,主体身份已经有认证过程的建立

Spring Security

  • 针对Spring项目的安全框架,是Spring Boot底层安全模块默认的技术选型
  • 可以实现web安全控制,只需要引入spring-boot-starter-security依赖配置即可
  • Spring Security中的类:
    • WebSecurityConfigurerAdapter: 自定义Security策略
    • AuthenticationManagerBuilder: 自定义认证策略
    • @EnableWebSecurity: 开启WebSecurity模式
1.引入spring-boot-starter-security依赖

2.编写SpringSecurity配置类
2.1 定制请求的授权规则
2.2 开启自动配置的登录功能(/login来到登录页;重庆向到/login?error表示登录失败)
2.3 开启自动配置的注销功能(访问/logout请求,表示用户注销并清空session;注销成功返回/login?logout)
2.4 开启自动配置的记住密码功能(http.rememberMe();)-登录成功以后,将Cookie发送给浏览器保存,可以实现记住密码功能;点击注销会删除Cookie,就没有记住密码功能
	默认post形式的/login代表处理登录
2.5定义认证规则
@EnableSecurity
public class MySecurityConfig extends WebSecurityConfigureAdapter{
	@Override
	protected void configure(HttpSecurity http) throws Exception{
		// 定制请求的授权规则
		http.authorizeRequest().antMatches("/").permitAll()
			.antMatches("/level/**").hasRole("VIP");
		// 开启自动配置的登录功能,如果没有权限就会跳转到登录页面
		http.formLogin().loginPage("/");	// 跳转到自定义登录页
		http.logout().logoutSuccessUrl("/");	// 注销成功返回首页
		http.rememberMe().rememberMeParameter("remember");	// 开启自动配置的记住密码功能
	}
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception{
		auth.inMemoryAuthentication().withUser("username").password("password").roles("role1","role2")
									 .and()
									 .withUser("username").password("password").roles("role1","role2")
}


3.控制请求的访问权限
  • Thymeleaf Extras Springsecurity4