欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot与spring security的结合的示例

程序员文章站 2023-11-17 16:35:46
权限控制,也是我们再日常开发中经常遇到的场景,需要根据用户的角色决定是否可以看到某个资源。目前,市面上此类框架主要有shiro与我们今天要讲到的spring securit...

权限控制,也是我们再日常开发中经常遇到的场景,需要根据用户的角色决定是否可以看到某个资源。目前,市面上此类框架主要有shiro与我们今天要讲到的spring security。关于权限的控制有复杂的控制,例如几乎每个公司都有单点登录系统,根据用户名来到数据库中拿到对应的权限,在展示该权限下能看到的资源。还有一种就是简单的控制,也就是我们今天所要提到的。将账号,密码,角色配置到代码中,也可以进行简单的控制,缺点不言而喻,扩展性不好,只有固定的账号,但是作为演示还是够用的。

好了废话不多说,上pom

<dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter</artifactid>
    </dependency>

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
    </dependency>

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-security</artifactid>
    </dependency>

spring-boot-starter-security里面包装了spring security所需要的依赖。不需要我们一个个的配置,简化了我们的操作,节省了我们的时间,不得不说,这些企业级框架考虑的就是很周到,如果我们自己添加jar,可能会因为版本之间的不兼容而爆出各种问题,这都是题外话,赞叹一下,我们继续。看下配置类

package com.shuqi;
import org.springframework.context.annotation.configuration;
import org.springframework.core.annotation.order;
import org.springframework.security.config.annotation.web.builders.httpsecurity;
import org.springframework.security.config.annotation.web.configuration.enablewebsecurity;
import org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter;


@enablewebsecurity
public class securityconfig {

  @configuration
  public static class websecurityconfigurationadapter extends websecurityconfigureradapter {
    @override
    protected void configure(httpsecurity http) throws exception {
      http.csrf().disable();
      http
          .authorizerequests()
          .antmatchers(
              "/index"
          ).hasrole("admin")
          .anyrequest().permitall()
          .and()
          .httpbasic()
      ;
    }
  }
}

这段配置翻译成中文是:对于访问/index这个链接需要admin权限,其他的全都都允许。有的时候我们只会注意代码,其实这个注解@enablewebsecurity会重要更多,因为他是spring security的开始,他引入了诸多的配置类,才使得security生效。我们设置了admin权限,但是没有设置admin权限对应的用户名密码,所以看下配置文件

security:
 user:
  name: root
  password: root
  role: admin

配置都差不多了,看一眼我们的controller

package com.shuqi.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
public class hellocontroller {
  @requestmapping("/index")
  public string index(){
    return "hello world index";
  }

  @requestmapping("/index1")
  public string index1(){
    return "hello world index1";
  }
}

一个被拦截的/index,一个不会被拦截的/index1,看下区别。启动项目,访问/index

SpringBoot与spring security的结合的示例

可以看到已经加了访问控制,输入配置的root,root

可以看到结果

SpringBoot与spring security的结合的示例

输入/index1可以直接看到结果

SpringBoot与spring security的结合的示例

说明我们的配置生效了,spring security确实帮助我们做到了访问的控制。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。