javaConfig方式配置spring security

javaConfig方式配置spring security

本文介绍javaConfig方式配置spring security,通过阅读可以了解无需xml配置且较容易地配置使用spring security。
从spring framework3.1开始并支持javaConfig方式,spring security3.2中扩展了该功能,通过使用@Configuration注解方式配置。

依赖管理

为了使用spring security,需要相应的依赖。可以使用maven或gradle。这里使用gradle示例。其中spring-security-config为必须,web配置web项目使用。版本可以查询spring官网,引用合适的版本。本文基于4.2.3.RELEASE版本测试。

compile group: 'org.springframework.security', name: 'spring-security-web', version: "$springSecurity"
compile group: 'org.springframework.security', name: 'spring-security-config', version: "$springSecurity"

使用javaConfig配置Web Security

从一个基本的spring security示例开始:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth.inMemoryAuthentication().withUser("user")
          .password("password").roles("USER");
    }
}

上面我们配置搭建了基本的内存认证配置。

HTTP Security配置

启用spring的http 安全,我们需要扩展WebSecurityConfigurerAdapter类,在configure(HttpSecurity http)方法中提供缺省的配置:

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and().httpBasic();
}

上面缺省配置确保任何请求都需要基于表单登录或http基本认证。xml配置类似,代码如下:

<http>
    <intercept-url pattern="/**" access="authenticated"/>
    <form-login />
    <http-basic />
</http>

表单登录

有趣的是,spring security根据启用的配置,自动生成登录页面,使用标准url值处理登录提交:

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

自动生成登录页面可以快捷地启动并运行。

使用角色授权

我们现在给每个url配置相应角色实现授权:

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/", "/home").access("hasRole('USER')")
      .antMatchers("/admin/**").hasRole("ADMIN")
      .and()
      // some more method calls
      .formLogin();
}

注意:我们使用了两种方式配置:
- 类型安全API,hasRole
- 基于springEl表达式API,access

登出

如spring security其他方面的特性,框架提供大量的登出缺省功能。
缺省情况,登出请求会使session失效,清除素有认证缓存和SecurityContextHolder,然后重定向至登录页面。
下面是简单的登出配置:

protected void configure(HttpSecurity http) throws Exception {
    http.logout();
}

当然,如果你想做更多的登出配置,可以增加相应配置或扩展,下面示例如下:

protected void configure(HttpSecurity http) throws Exception {
    http.logout().logoutUrl("/my/logout")
      .logoutSuccessUrl("/my/index")
      .logoutSuccessHandler(logoutSuccessHandler) 
      .invalidateHttpSession(true)
      .addLogoutHandler(logoutHandler)
      .deleteCookies(cookieNamesToClear)
      .and()
      // some other method calls
}

授权

本节简要说明spring security提供的授权方式,使用基于内存和JDBC方式,当然还有其他很多方式:

基于内存

基于内存配置。

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) 
  throws Exception {
    auth.inMemoryAuthentication()
      .withUser("user").password("password").roles("USER")
      .and()
      .withUser("admin").password("password").roles("USER", "ADMIN");
}

基于jdbc授权

使用jdbc,需要在应用中配置定义数据源,然后使用该数据源:

@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
      .withDefaultSchema()
      .withUser("user").password("password").roles("USER")
      .and()
      .withUser("admin").password("password").roles("USER", "ADMIN");
}

spring security也支持自定义数据存储,甚至nosql数据库。

总结

本文简要描述了基于javaConfig方式的spring security配置,使用最简单的配置场景,说明最基本的配置。后续继续描述较为复杂的应用场景配置和实现。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值