Spring-Securty(Spring安全框架):项目实战

一、简单了解 Spring-security:

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于spring的应用程序的事实标准。
Spring Security是一个重点为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring Security的真正强大之处在于它可以很容易地扩展以满足定制需求
1.1 构建Spring-Boot项目,并导入依赖
Gradle:

 implementation 'org.springframework.boot:spring-boot-starter-security'

Maven:

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

1.2 编写配置类
参考官网

@EnableWebSecurity // 开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	
   @Override
   protected void configure(HttpSecurity http) throws Exception {
       
  }
}

配置好这些后可通过 configure方法中的 http参数进行访问控制
在这里贴出了一些常用的方法

// 定制请求的授权规则
   
   http.authorizeRequests().antMatchers("/").permitAll()// 首页所有人可以访问
  .antMatchers("/level1/**").hasRole("vip1")//level1文件夹下的所有页面,只有vip1的角色可以访问
  .antMatchers("/level2/**").hasRole("vip2")//level2文件夹下的所有页面,只有vip2的角色可以访问
  .antMatchers("/level3/**").hasRole("vip3");//level3文件夹下的所有页面,只有vip3的角色可以访问
// 开启自动配置的登录功能
// login 请求来到登录页
// login?error 重定向到这里表示登录失败
http.formLogin();
注意:Spring-Security在5.0版本之后对密码进行了加密,5.0版本后使用需要给密码进行加密
//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
   //在内存中定义,也可以在jdbc中去拿....
   auth.inMemoryAuthentication()
          .withUser("kuangshen").password("123456").roles("vip2","vip3")
          .and()
          .withUser("root").password("123456").roles("vip1","vip2","vip3")
          .and()
          .withUser("guest").password("123456").roles("vip1","vip2");
}

以上的文章只是帮助我们完成了简单权限的访问控制,Spring-Security提供了很多强大的功能,需要详情了解的朋友参考官网。
创作不易,有用的朋友点个赞吧!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值