SpringSecurity常见简单应用


SpringSecurity简介

SpringSecurity是SpringBoot中集成的权限框架,可定制身份验证和权限控制。侧重于为java应用程序提供身份验证和授权。解决之前关于权限的代码十分繁琐,冗余的问题。SpringSecurity主要有两个目标:认证(Authentication)授权(Authorization)


一、搭建SpringSecurity环境

1、引入spring-boot-starter-security模板,在idea工具中,可以直接在创建SpringBoot项目时勾选。
2、也可以在maven中手动加入依赖

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

3、导入依赖之后,在项目目录下创建SpringSecurity的配置类。
在这里插入图片描述需要继承WebSecurityConfigurerAdapter类并且重写它的一些方法。

二、认证和授权

1、添加授权

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        //首页所有人可以访问,功能也需要权限
        //链式编程
        //授权
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限默认回到登录页面
        //自定义登录页,设置表单提交的name属性值,设置请求过滤路径
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
        //关闭防止网站攻击,springboot默认开启,注销失败的原因可能是开启了防止网站攻击
        http.csrf().disable();
        //注销
        http.logout();
        //开启记住我功能,cookie,默认保存两周。自定义记住我功能,需要传递参数
        http.rememberMe(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值