程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

如何基于Spring Security框架实现权限管理

balukai 2024-12-30 01:57:52 文章精选 12 ℃

Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架,用于保护基于Spring的应用程序。

Spring Security主要是从两个方面解决安全性问题:

  1. web请求级别:使用Servlet规范中的过滤器(Filter)保护Web请求并限制URL级别的访问。
  2. 方法调用级别:使用Spring AOP保护方法调用,确保具有适当权限的用户才能访问安全保护的方法。

基于Maven的Springboot项目中若要集成Spring Security,pom文件中要添加spring security的依赖。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

接下来最主要是配置Spring Security,可以通过XML文件或者配置类的方式来配置,当然推荐使用配置类的方式。

Spring Security的配置类需要实现 WebSecurityConfigurer 或者继承 WebSecurityConfigurerAdapter 类。继承 WebSecurityConfigurerAdapter 类的示例代码如下。

@Configuration
@EnableWebSecurity // 注解开启Spring Security的功能
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
        ... ...
  }
	@Override
	public void configure(WebSecurity web) throws Exception {
		   web.ignoring().antMatchers("/static/**");
	}
	@Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("user").password(new BCryptPasswordEncoder().encode("password")).roles("USER");
      }  
}

@EnableWebSecurity注解的作用就是启用Web安全功能,但并没有任何实际动作。具体的Web安全配置细节,都是通过重载WebSecurityConfigurerAdapter类的三个configure()方法来实现。

  • configure(WebSecurity):通过重载该方法,可配置Spring Security的Filter链。
  • configure(HttpSecurity):通过重载该方法,可配置如何通过拦截器保护请求。
  • configure(AuthenticationManagerBuilder):通过重载该方法,可配置基于用户详情(User Details)的权限。

这三个方法主要区别就是参数不同,下面分别举例说明这三种带有不同参数类型的方法。

WebSecurity类

WebSecurity类与HttpSecurity类、AuthenticationManagerBuilder类都继承自AbstractConfiguredSecurityBuilder抽象类,AbstractConfiguredSecurityBuilder又继承自AbstractSecurityBuilder。SpringSecurity在AbstractSecurityBuilder类中实现了创建FilterChain的方法performbuild()。

configure(WebSecurity web) 方法用于配置影响全局的安全性设置,常用于配置静态资源的访问权限。以下设置说明在static目录下的静态资源,不需要权限认证即可访问。

public void configure(WebSecurity web) throws Exception {
		   web.ignoring().antMatchers("/static/**");
	}

HttpSecurity

configure(HttpSecurity)实现了在资源级(URL)来配置网络的安全性,也就是对角色的权限——所能访问的路径做出限制。以下代码展示了该方法定义的示例。

@Override
  protected void configure(HttpSecurity http) throws Exception {
      http
          .authorizeRequests()  //定义哪些url需要保护,哪些url不需要保护
              .antMatchers("/", "/home").permitAll()    //定义不需要认证就可以访问
              .anyRequest().authenticated()
              .and()
          .formLogin()
              .loginPage("/login")  //定义当需要用户登录时候,转到的登录页面
              .permitAll()
              .and()
          .logout()
              .permitAll();
      http.csrf().disable();
  }
  • 通过 authorizeRequests() 定义哪些URL需要被保护,哪些不需要被保护。以上代码指定了 / 和 /home 不需要任何认证就可以访问,其他的路径都必须通过身份验证。
  • 通过 formLogin() 定义当需要用户登录时候,转到的登录页面。

AuthenticationManagerBuilder

AuthenticationManagerBuilder是基于用户信息来配置权限。涉及到权限的用户信息存储方式共有三种:

1、使用基于内存的用户认证:通过 inMemoryAuthentication() 方法,可以启用和配置基于内存的用户权限。

2、基于数据库表的用户认证:用户数据通常会存储在关系型数据库中,并通过JDBC进行访问。使用jdbcAuthentication()方法可以让Spring Security使用以关系型数据库存储的用户权限认证。

3、基于LDAP的用户认证:使用ldapAuthentication()方法,可以让Spring Security使用基于LDAP的认证。

以下代码展示了基于内存的用户认证。

@Autowired
  public void configureGlobal(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
					authManagerBuilder
                .inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("USER").and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("456")).roles("USER","ADMIN");
  }

调用 withUser() 方法可以在内存中添加新的用户。withUser() 方法返回的是 UserDetailsManagerConfigurer.UserDetailsBuilder,这个对象提供了多个进一步配置用户权限信息的方法,包括设置用户密码的password()方法以及为给定用户授予一个或多个角色权限的roles()方法。

roles()方法会在给定的角色值上添加一个ROLE_前缀,并将其作为权限授予给用户。因此上述代码中用户user具有的权限为:ROLE_USER,用户admin具有的权限为ROLE_USERROLE_ADMIN

借助 passwordEncoder() 方法来指定一个密码转码器(encoder),可以对用户密码进行加密存储。

以上就是Spring Security的基本用法。

总结

Spring Security框架实际上非常复杂,这里只是就Spring Security的简单使用做一个分享,后续文章会进一步介绍Spring Security框架。

Tags:

最近发表
标签列表