Spring Boot 集成教程


概述

本篇教程我们将介绍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) - 最简配置的更多相关文章

  1. spring boot rest 接口集成 spring security(2) - JWT配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  2. spring boot 中接口参数为枚举时的反序列化配置(总结)

    步骤 如果是 GET 请求中需要反序列化枚举值(即 url 中的参数[querystring]),确保以下两点 1.1. 重写 StringToEnumConverterFactory 1.2. 配置 ...

  3. 【Spring】关于Boot应用中集成Spring Security你必须了解的那些事

    Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...

  4. 关于Boot应用中集成Spring Security你必须了解的那些事

    Spring Security Spring Security是Spring社区的一个顶级项目,也是Spring Boot官方推荐使用的Security框架.除了常规的Authentication和A ...

  5. spring boot / cloud (三) 集成springfox-swagger2构建在线API文档

    spring boot / cloud (三) 集成springfox-swagger2构建在线API文档 前言 不能同步更新API文档会有什么问题? 理想情况下,为所开发的服务编写接口文档,能提高与 ...

  6. Spring Boot HikariCP 一 ——集成多数据源

    其实这里介绍的东西主要是参考的另外一篇文章,数据库读写分离的. 参考文章就把链接贴出来,里面有那位的代码,简单明了https://gitee.com/comven/dynamic-datasource ...

  7. Spring Boot 数据访问集成 MyBatis 与事物配置

    对于软件系统而言,持久化数据到数据库是至关重要的一部分.在 Java 领域,有很多的实现了数据持久化层的工具和框架(ORM).ORM 框架的本质是简化编程中操作数据库的繁琐性,比如可以根据对象生成 S ...

  8. 【ELK】4.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版+kibana管理ES的index操作

    spring boot 2.X集成ES 进行CRUD操作  完整版 内容包括: ============================================================ ...

  9. Spring Boot 使用 Micrometer 集成 Prometheus 监控 Java 应用性能

    转载自:https://cloud.tencent.com/developer/article/1508319 文章目录1.Micrometer 介绍2.环境.软件准备3.Spring Boot 工程 ...

随机推荐

  1. 非阻塞多路IO

    socket.listen() rfds=[] wfds=[] while(select(rfds,wfds,timeout)){//事件循环 client=socket.accept(timeout ...

  2. 在Anaconda3环境下安装并切换 Tensorflow 2.0 环境

    背景 Anaconda切换各种环境非常方便,现在我们就来介绍一下如何使用anaconda安装tensorflow环境. anaconda v3.5 from 清华镜像站 tensorflow v2.0 ...

  3. Centos7 静默安装 Oracle11G

    1.准备安装包: 安装包官网下载地址:https://www.oracle.com/technetwork/database/enterprise-edition/downloads/112010-l ...

  4. Ubuntu系统部署tomcat并启用JMX实战案例

    Ubuntu系统部署tomcat并启用JMX实战案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.安装JDK环境 1>.更换阿里云的软件源 [root@zabbix_g ...

  5. mysql导入导出无权限

    error:The MySQL server is running with the --secure-file-priv option so it cannot execute this state ...

  6. 13.在项目中部署redis企业级数据备份方案以及各种踩坑的数据恢复容灾演练

    到这里为止,其实还是停留在简单学习知识的程度,学会了redis的持久化的原理和操作,但是在企业中,持久化到底是怎么去用得呢? 企业级的数据备份和各种灾难下的数据恢复,是怎么做得呢? 1.企业级的持久化 ...

  7. Web基础之Spring AOP与事务

    Spring之AOP AOP 全程Aspect Oriented Programming,直译就是面向切面编程.和POP.OOP相似,它也是一种编程思想.OOP强调的是封装.继承.多态,也就是功能的模 ...

  8. SQL server 注入 和 SQL server 扩展(10.29 第二十九天)

    Step1:检测注入点 Step2: select * from sysobjects   (sysobjects 系统对象表,保存当前数据库的对象) select * from users wher ...

  9. HihoCoder第七周:完全背包问题

    1043 : 完全背包 时间限制:20000ms 单点时限:1000ms 内存限制:256MB 描述 且说之前的故事里,小Hi和小Ho费劲心思终于拿到了茫茫多的奖券!而现在,终于到了小Ho领取奖励的时 ...

  10. Python 实现类似range函数

    需求:写一个属于你自己的 frange函数,frange与range类似,一样的参数规则,但是每一项必须要是float类型 实现: 注意点,如何判断stop是否有参数传入,这里使用空字符判断,如fra ...