spring boot rest 接口集成 spring security(1) - 最简配置
Spring Boot 集成教程
- Spring Boot 介绍
- Spring Boot 开发环境搭建(Eclipse)
- Spring Boot Hello World (restful接口)例子
- spring boot 连接Mysql
- spring boot配置druid连接池连接mysql
- spring boot集成mybatis(1)
- spring boot集成mybatis(2) – 使用pagehelper实现分页
- spring boot集成mybatis(3) – mybatis generator 配置
- spring boot 接口返回值封装
- spring boot输入数据校验(validation)
- spring boot rest 接口集成 spring security(1) – 最简配置
- spring boot rest 接口集成 spring security(2) – JWT配置
- spring boot 异常(exception)处理
- spring boot 环境配置(profile)切换
- spring boot redis 缓存(cache)集成
概述
本篇教程我们将介绍spring security的集成,为易于学习,我们会尽量剔除无关部分,用最小的配置集成spring security。当你学会怎么集成spring security之后,下一篇我们将集成jwt,在那篇教程中,我们会进一步介绍spring security,完善配置。在前后端分离的大趋势下,Java后端都是实现REST接口,所以本篇内容仅针对REST接口,如需了解不是接口的情况,可自行参考相关资料。
spring security的实现基于servlet过滤器,在每个请求被spring MVC处理之前,先要经过spring security过滤器,从而实现权限控制。权限控制分两部分,认证和授权,用户认证就是指登录,有些接口要用户登录后才能访问;授权是指根据用户角色授予不同权限,有些接口要具有一定角色的用户才能访问,如管理相关的接口只限admin角色访问。
我们会创建几个接口,部分接口需要登录才能访问,部分接口完全放开,验证spring security是否成功集成。
项目依赖
创建spring boot项目
打开Eclipse,创建spring boot的spring starter project项目,选择菜单:File > New > Project ...
,弹出对话框,选择:Spring Boot > Spring Starter Project
,在配置依赖时,勾选web, security
,如不清楚怎样创建spring boot项目,参照教程: [spring boot hello world (restful接口)例子]。
完整的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qikegu</groupId>
<artifactId>springboot-security-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-security-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
项目配置
spring security Java 配置
spring可以用java配置,也可用xml配置,spring官方推荐用java配置,我们这里用java配置。
添加java配置文件:
a. 添加spring security过滤器
最简单的注册spring security过滤器的方法是给java配置类添加@EnableWebSecurity注解:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
// ...
}
b. 用哪种方法加密密码明文
用户密码保存到数据库时,一般避免明文而以hash值的方式保存,我们可以为spring security配置用什么方法加密密码明文,此处使用官方推荐的BCryptPasswordEncoder
@Bean
public PasswordEncoder myEncoder() {
return new BCryptPasswordEncoder();
}
c. 配置用户信息加载
用户认证/登录时需要加载用户信息比对用户名与密码,一般用户信息从数据库加载,此处为简便起见,在内存中创建用户信息,包括用户名、密码、用户角色信息
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password(myEncoder().encode("12345")).roles("ADMIN")
.and()
.withUser("user").password(myEncoder().encode("12345")).roles("USER");
}
d. 配置接口权限控制
通过配置HttpSecurity,可以匹配不同的url路径,为他们指定不同权限,在这里对于/hello3
接口作了权限限制,必须登录后才能访问
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 基于token,不需要csrf
.csrf().disable()
// 基于token,不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 下面开始设置权限
.authorizeRequests()
// 需要登录
.antMatchers("/hello3").authenticated()
// 除上面外的所有请求全部放开
.anyRequest().permitAll();
}
完整的SecurityConfig.java文件
package com.qikegu.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
@EnableWebSecurity // 添加security过滤器
public class SecurityConfig extends WebSecurityConfigurerAdapter{
// 密码明文加密方式配置
@Bean
public PasswordEncoder myEncoder() {
return new BCryptPasswordEncoder();
}
// 认证用户时用户信息加载配置
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password(myEncoder().encode("12345")).roles("ADMIN")
.and()
.withUser("user").password(myEncoder().encode("12345")).roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 基于token,不需要csrf
.csrf().disable()
// 基于token,不需要session
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
// 下面开始设置权限
.authorizeRequests()
// 需要登录
.antMatchers("/hello3").authenticated()
// 除上面外的所有请求全部放开
.anyRequest().permitAll();
}
}
添加代码
添加一个控制类,实现几个测试接口。
在项目中添加文件
添加几个接口,文件内容如下
package com.qikegu.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping(value="/hello1", method=RequestMethod.GET)
public String hello1() {
return "Hello1!";
}
@RequestMapping(value="/hello2", method=RequestMethod.GET)
public String hello2() {
return "Hello2!";
}
@RequestMapping(value="/hello3", method=RequestMethod.GET)
public String hello3() {
return "Hello3!";
}
}
我们实现了3个接口,其中/hello3
被配置为需要登录访问,所以访问/hello3
时会返回权限受限的错误。
运行项目
Eclipse左侧,在项目根目录上点击鼠标右键弹出菜单,选择:run as -> spring boot app
运行程序。 打开Postman访问接口,运行结果如下:
访问/hello1
接口,不受限
访问/hello3
接口,受限。后面教程将会介绍登录访问接口的过程。
总结
本文介绍了spring boot项目中集成spring security的过程,尽量以简单的方式配置security,下一篇教程将更加详细地介绍spring security以及jwt的集成。
spring boot rest 接口集成 spring security(1) - 最简配置的更多相关文章
- spring boot rest 接口集成 spring security(2) - JWT配置
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot 中接口参数为枚举时的反序列化配置(总结)
步骤 如果是 GET 请求中需要反序列化枚举值(即 url 中的参数[querystring]),确保以下两点 1.1. 重写 StringToEnumConverterFactory 1.2. 配置 ...
- 【Spring】关于Boot应用中集成Spring Security你必须了解的那些事
Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...
- 关于Boot应用中集成Spring Security你必须了解的那些事
Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...
- spring boot / cloud (三) 集成springfox-swagger2构建在线API文档
spring boot / cloud (三) 集成springfox-swagger2构建在线API文档 前言 不能同步更新API文档会有什么问题? 理想情况下,为所开发的服务编写接口文档,能提高与 ...
- Spring Boot HikariCP 一 ——集成多数据源
其实这里介绍的东西主要是参考的另外一篇文章,数据库读写分离的. 参考文章就把链接贴出来,里面有那位的代码,简单明了https://gitee.com/comven/dynamic-datasource ...
- Spring Boot 数据访问集成 MyBatis 与事物配置
对于软件系统而言,持久化数据到数据库是至关重要的一部分.在 Java 领域,有很多的实现了数据持久化层的工具和框架(ORM).ORM 框架的本质是简化编程中操作数据库的繁琐性,比如可以根据对象生成 S ...
- 【ELK】4.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版+kibana管理ES的index操作
spring boot 2.X集成ES 进行CRUD操作 完整版 内容包括: ============================================================ ...
- Spring Boot 使用 Micrometer 集成 Prometheus 监控 Java 应用性能
转载自:https://cloud.tencent.com/developer/article/1508319 文章目录1.Micrometer 介绍2.环境.软件准备3.Spring Boot 工程 ...
随机推荐
- 【转载】Jmeter关联-正则表达式提取器
今天研发同事提供了一个验证token的接口,要验证token的正确性,现在将整个过程做如下记录: 场景:验证token的正确性 原理:首先用户登录成功后,会在Response head ...
- 设备树DTS 学习: uboot 传递 dtb 给 内核
背景 得到 dtb 文件以后,我们需要想办法下载到 板子中,并给 Linux 内核使用. (高级版本的 uboot也有了 自己使用设备树支持,我们这里不讨论 uboot 使用的设备树) Linux 内 ...
- Redis——从入门到放弃
redis简介 Redis is an open source (BSD licensed), in-memory data structure store, used as a database, ...
- Java虚拟机05.2(内存分配)
jdk1.7中堆内存分为:年轻代+老年代+永久代.但是永久代有作为非堆内存存在,也就是说堆内存的大小应该为年轻代+老年代.在tomcat容器中,如果jsp页面过多可能出现永久代溢出.通常栈溢出都是程序 ...
- 018.CI4框架CodeIgniter数据库操作之:Delete删除一条数据
01. 在Model中写数据库操作语句,代码如下: <?php namespace App\Models\System; use CodeIgniter\Model; class User_mo ...
- 007.Delphi插件之QPlugins,插件的卸载和重新加载
效果图如下,可以反复卸载和重新加载.QPlugins这个插件,还没弄明白,摸索着跟着DEMO写 主窗口代码如下 unit Frm_Main; interface uses Winapi.Windows ...
- 0106 springMVC REST风格
markdown 印象笔记语法练习带快捷键的 加粗 快捷键 cmd+b 斜体 cmd+i 分割线 cmd+u 编号列表: cmd+shift+o 无编号列表 cmd+shift+u 待办事项 cmd+ ...
- JavaScript 的一些SAO操作
IE判断检测 jQuery 在 1.9 版本之前,提供了一个浏览器对象检测的属性 .browser 的替代方案.于是各种利用 IE bug 的检测方法被搜了出来: // IE 678 最短方法 var ...
- window安装dlib、face_recognition
face_recognition简介 face_recognition是Python的一个开源人脸识别库,支持Python 3.3+和Python 2.7.引用官网介绍: Recognize and ...
- LeetCode实战练习题目 - Array
实战练习题目 - Array 盛最多水的容器 class Solution { public: int maxArea(vector<int>& height) { int res ...