SpringBoot与spring security的结合的示例

权限控制,也是我们再日常开发中经常遇到的场景,需要根据用户的角色决定是否可以看到某个资源。目前,市面上此类框架主要有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

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

可以看到结果

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


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

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

相关文章

今天小编给大家分享的是Springboot下使用Redis管道(pipeline...
本篇文章和大家了解一下springBoot项目常用目录有哪些。有一...
本篇文章和大家了解一下Springboot自带线程池怎么实现。有一...
这篇文章主要介绍了SpringBoot读取yml文件有哪几种方式,具有...
今天小编给大家分享的是SpringBoot配置Controller实现Web请求...
本篇文章和大家了解一下SpringBoot实现PDF添加水印的方法。有...