栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot与spring security的结合的示例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot与spring security的结合的示例

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

好了废话不多说,上pom


      org.springframework.boot
      spring-boot-starter
    

    
      org.springframework.boot
      spring-boot-starter-web
    

    
      org.springframework.boot
      spring-boot-starter-security
    

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确实帮助我们做到了访问的控制。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/141306.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号