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 工程 ...
随机推荐
- CPU、内存、硬盘之间的关系
要完完全全地讲清楚cpu.内存.硬盘之间的关系,博客的篇幅是不够的.这里简单的介绍以下它们之间的关系,抛砖引玉. 1.CPU即中央处理器,是英语“Central Processing Unit”的缩写 ...
- ubuntu 环境下pycharm的 安装与激活教程
1. 基本安装: 1.1 打开Ubuntu的应用市场,并在搜索栏搜索pycharm,结果如下图所示 1.2 选择pro版本进行安装,结果如下图所示: 1.3打开安装后的pycharm,如果出现下图所示 ...
- 怎样管理Exchange Server 2013资源邮箱
1. exchange资源邮箱介绍 这次将介绍Exchange Server 2013的资源邮箱相关内容. Exchange Server 2013的资源邮箱包含两类,其一为“会议室邮箱”,另一类是“ ...
- shell-Startup-Files
shell-Startup-Files 1. 相关阅读 2. 主流shell 3. shell实例类型 4. Shell启动文件的必要元素 4.1 路径: 命令路径, 4.2 提示符 5. 主流she ...
- epoll源码分析(基于linux-5.1.4)
API epoll提供给用户进程的接口有如下四个,本文基于linux-5.1.4源码详细分析每个API具体做了啥工作,通过UML时序图理清内核内部的函数调用关系. int epoll_create1( ...
- 洛谷 P1247 取火柴游戏
题目传送门 暴力 \((\)由于我这样的初中蒟蒻不\((bu)\)喜\((hui)\)欢\((xie)\)数学证明,所以题解中的证明全是其他大佬的题解已经多次证明过的,这里就不再啰嗦了.\()\) - ...
- 深入理解JVM Note
第2章 Java内存区域与内存溢出异常 运行时数据区域 在虚拟机有栈.堆和方法区. 线程共享的:堆.方法区 不共享的:栈.程序计数器(代码执行的行号) 程序计数器(Program Counter Re ...
- HashMap之Hash碰撞源码解析
转自:https://blog.csdn.net/luo_da/article/details/77507315 https://www.cnblogs.com/tongxuping/p/827619 ...
- delphi中json转dataset
unit uJSONDB; interface uses SysUtils, Classes, Variants, DB, DBClient, SuperObject, Dialogs; type T ...
- Acwing199 余数之和
原题面:https://www.acwing.com/problem/content/201/ 题目大意:给出正整数n和k,计算j(n, k)=k mod 1 + k mod 2 + k mod 3 ...