Spring Security
Spring Security是作为过滤器控制权限的,在web.xml中配置过滤器。
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
定义security配置
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
//使用and()添加新的配置选项
//登录页设置为允许所有用户访问
.and().formLogin().loginPage("/login").permitAll()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
配置类需要@EnableWebSecurity、@EnableGlobalMethodSecurity、@EnableGlobalAuthentication中的一个标注。
access(“hasRole(‘ADMIN’)”) =access(“ROLE_ADMIN”)
configure()函数的配置对应XML为:
<http auto-config="true">
<intercept-url pattern="/*" access="ROLE_USER" />
<form-login login-page="/" default-target-url="/" authentication-failure-url="/? login=error" />
<logout logout-success-url="/" />
</http>
环境初始化
1.单独使用spring security,需要将MySecurityConfig传入并构造初始化Security环境的实例。该类自动将应用中的每个url注册到SpringSecurityFilterChain,并且加载Security的配置。
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(MySecurityConfig.class);
}
}
2.如果项目中使用了Spring,则项目中存在初始化Web环境的类,这时将Spring Security注册到已经存在的ApplicationContext中。
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
}
这个类将应用中的url注册到SpringSecurityFilterChain。然后需要将MySecurityConfig加载到已经存在的程序上下文中。
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { MySpringSecurityConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Security中的类
Authentication
Authentication接口表示用户认证信息,用户登录认证之前相关信息会封装为一个Authentication具体实现类的对象,登录认证后会生成一个包含用户权限的Authentication对象,并保存在SecurityContextHolder的Context中。
//获得用户名
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username=((UserDetails) principal).getUsername();
AuthenticationManager
AuthenticationManager是一个用来处理认证(Authentication)请求的接口。在其中只定义了一个方法authenticate(),该方法只接收一个代表认证请求的Authentication对象作为参数,如果认证成功,则会返回一个封装了当前用户权限等信息的Authentication对象进行返回。
AuthenticationManager的默认实现是ProviderManager,但是它不直接自己处理认证请求,而是委托给其所配置的AuthenticationProvider列表,然后会依次使用每一个AuthenticationProvider进行认证,如果有一个AuthenticationProvider认证后的结果不为null,则表示该AuthenticationProvider已经认证成功,之后的AuthenticationProvider将不再继续认证。如果所有的AuthenticationProvider的认证结果都为null,则表示认证失败,将抛出一个ProviderNotFoundException。
<authentication-manager>
//user-service-ref指定关联哪个AuthenticationProvider,默认为DaoAuthenticationProvider
<authentication-provider user-service-ref="">
</authentication-provider>
</authentication-manager>
默认情况下,认证成功后ProviderManager将清除返回的Authentication中的凭证信息(密码等),因此无法直接将Authentication缓存用于以后的登录认证。一种办法是设置ProviderManager的eraseCredentialsAfterAuthentication属性为false。