安全模块springboot security

为什么用springboot security?

1、Spring Security是一个安全组件,为java企业级开发提供了全面的安全防护。它可以在Controller层、Service层、DAO层等以加注解的方式来保护应用程序的安全。SpringSecurity提供了细粒度的权限控制,可以精细到每一个API接口,每一个业务方法,或者每一个DAO层的方法。SpringSecurity提供的是应用程序层的安全解决方案。
2、SpringSecurity对环境无依赖性、低耦合性,提供了数十个安全模块,模块间耦合性低,可以自由组合来定制安全功能。
安全领域的两大模块是认证和授权
认证是要确认身份,可以是执行操作的用户、设备或者其他系统。
授权是赋予权限,给认证后的身份确定能做什么操作。

3、SpringSecurity采用了注解的方式控制权限,熟悉spring的开发者很容易上手;且很容易集成到springboot工程中。
4、与shiro对比
shiro一般使用在单体应用中,但在微服务架构中,它是无能为力的。

springboot security和spring security的关系

spring security框架中,主要包含两个jar:

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

springboot对spring security框架做了封装,并没有改动这两个包的内容

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

配置Spring Security

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http
            .authorizeRequests()
               .antMatchers("/css/**", "/index").permitAll()
               .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/qirui/**").hasRole("USER")
               .and()
            .formLogin().loginPage("/login").failureUrl("/login-error")
            .and()
            .exceptionHandling().accessDeniedPage("/401");
      http.logout().logoutSuccessUrl("/");
   }

   @Autowired
   UserDetailsService userDetailsService;

   @Autowired
   public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsService);
   }

以上配置类添加@EnableWebSecurity注解,开启WebSecurity功能。

  • 每个请求都要认证
  • 自动生成一个登陆表单
  • 可以用username和password来进行认证
  • 用户可以注销
  • 阻止了CSRF攻击
  • 排除掉了/css和/index开头的资源验证
  • 以/user开头的资源需要验证,并且需要的角色是Role
  • 表单的登录地址是/login,登录失败的地址为/login-error
  • 异常处理会重定向到/401
  • 注销成功,重定向到首页
  • @EnableGlobalMethodSecurity(prePostEnabled = true)开启方法级别的保护
    同时需要配置Controller来完成web跳转。
Spring Security方法级别的保护

在方法级别上的安全验证是通过相关的注解和配置来实现的。@EnableGlobalMethodSecurity注解开启了方法级别的保护,参数最常用的是@prePostEnabled
生产上一般从数据库中读取用户和用户的角色权限信息,springcloud中常用UserDetails接口来实现SpringSecurity认证信息;Service层通过实现UserDetailsService接口,根据用户名获取该用户的所有信息,包括yoghurt信息和权限点。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值