《Spring实战》笔记(五):Spring Security

简介

Spring Security从两个角度来解决安全性问题:

  • 使用Servlet规范中的Filter保护Web请求并限制URL级别的访问。
  • 使用Spring AOP保护方法调用——借助于对象代理和使用通知,能够确保只有具备适当权限的用户才能访问安全保护的方法。

Spring Security的模块

Spring Security的模块主要如下:

模块 描述
core 提供Spring Security基本库
config 支持通过XML和Java配置Spring Security
web 提供了Spring Security基于Filter的Web安全性支持
ldap 支持基于LDAP进行认证
remoting 提供与Spring Remoting的集成
oauth2-core 提供对OAuth 2.0 Authorization FrameworkOpenID Connect Core 1.0的支持
oauth2-client 提供对OAuth 2.0 Authorization FrameworkOpenID Connect Core 1.0的客户端支持
oauth2-jose 提供了对JOSE (Javascript Object Signing and Encryption) 框架的支持
acl 支持通过访问控制列表(access control list,ACL)为域对象提供安全性
cas 提供与Jasig的中心认证服务(Central Authentication Service,CAS)进行集成的功能
openid 支持使用OpenID进行集中式认证
test 提供对Spring Security的测试支持

应用程序的类路径下至少要包含core和config这两个模块

过滤Web请求

在Spring Security中,只需要配置一个Filter就可以实现借助一系列Servlet Filter提供的各种安全性功能,DelegatingFilterProxy可以将工作委托给一个Filter的实现类,这个实现类作为bean注册在Spring容器中。
使用web.xml配置:


    springSecurityFilterChain
    
        org.springframework.web.filter.DelegatingFilterProxy
    

注意filter-name设置为springSecurityFilterChain,因为DelegatingFilterProxy会将过滤逻辑委托给一个名为springSecurityFilterChain的Filter bean,它可以链接任意一个或多个其他的Filter。
使用Java Config配置:

public class SecurityWebInitializer
        extends AbstractSecurityWebApplicationInitializer {
}

Spring已经提供了实现类来注册DelegatingFilterProxy,只需声明一个子类来继承即可。

编写安全性配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
                .and()
                .withUser("admin").password("admin")
                .roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .and()
                .authorizeRequests()
                .antMatchers("/").authenticated()
                .anyRequest().permitAll();
    }
}

使用EnableWebSecurity注解来启用Web安全功能,如果仅仅是继承WebSecurityConfigurerAdapter,那么应用将会被锁定,因为我们没有配置用户存储。如果需要指定更详细的安全设定,比如指定哪些请求需要认证或者自定义登录页面等,我们就需要重写configure()方法。WebSecurityConfigurerAdapter中重载了三个configure()方法,分别有各自的作用。

方法 作用
configure(WebSecurity) 配置Spring Security的Filter链
configure(HttpSecurity) 配置如何通过拦截器保护请求
configure(AuthenticationManagerBuilder) 配置user-detail服务

你可能感兴趣的:(《Spring实战》笔记(五):Spring Security)