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
    评论
Spring Security Java Config Preview: Web Security 是一个关于如何使用Java配置来设置Spring Security的博客文章。 首先,Spring Security是一个功能强大且广泛使用的安全框架,它为基于Java的应用程序提供了全面的安全服务。通过使用Java配置,开发人员可以灵活地定义和定制安全策略,而无需直接编辑XML文件。这种配置方式更加符合现代Java开发的趋势,也便于与Spring的其他功能集成。 其次,在Web安全性方面,Spring Security提供了一系列的安全控制措施,包括身份验证、授权、防止跨站请求伪造(CSRF)等。使用Java配置,可以轻松地启用这些功能,并对它们进行定制化设置。例如,可以通过编写简单的Java类来配置用户认证流程,定义哪些URL路径应该受到保护,以及哪些角色或权限的用户可以访问这些路径。 再者,Spring Security配置通常涉及以下几个步骤: 1. 创建配置类,通常需要继承`WebSecurityConfigurerAdapter`。 2. 覆盖`configure(HttpSecurity http)`方法来定义具体的安全策略。 3. 使用`http.authorizeRequests()`来指定哪些URL需要认证。 4. 使用`http.formLogin()`来配置表单登录。 5. 使用`http.csrf().disable()`来禁用CSRF保护(在必要时)。 6. 配置用户详情服务(UserDetailsService)来提供用户信息。 7. 如果有需要,还可以配置自定义的登录成功和失败处理器。 最后,为了更深入地了解Spring SecurityJava配置,建议阅读官方文档和相关的技术博客,这些都是学习的好资源。同时,实践是最好的老师,通过编写代码和实验不同的配置选项,可以更好地掌握Spring Security的使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值