第一个 SpringSecurity 应用
Spring Security 官方介绍 https://spring.io/projects/spring-security#learn
Spring Security 目标是解决 “你是谁?”、“你能做什么?”两个问题。
实现步骤
1. 创建目录结构
|____spring-security-learn-1 | |____build.gradle | |____src | | |____main | | | |____java | | | |____resources
2. 创建文件 build.gradle
重点引入 spring-boot-starter-security 依赖项,完整的 gradle 配置如下:
plugins { id 'java' id "io.spring.dependency-management" version "1.0.8.RELEASE" } group 'net.txt100.learn' version '1.0' sourceCompatibility = 1.8 apply plugin: 'application' mainClassName = 'net.txt100.learn.springsecurity.base.case1.Case1Application' repositories { maven { url "http://maven.aliyun.com/nexus/content/groups/public" } mavenCentral() } dependencyManagement { imports { mavenBom 'org.springframework.boot:spring-boot-dependencies:2.1.6.RELEASE' } } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' // spring boot compile group: 'org.springframework.boot', name: 'spring-boot-starter-web' compile group: 'org.springframework.boot', name: 'spring-boot-starter-security' }
3. 创建一个资源服务 UserController.java
package net.txt100.learn.springsecurity.base.case1.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Title: UserController * Package: net.txt100.learn.springsecurity.base.case1.controller * Creation date: 2019-08-08 * Description: * * @author <a href="me@tonglei.win">Tonglei</a> * @since 1.0 */ @RestController @RequestMapping("/user") public class UserController { @RequestMapping("/all") public String getAllUsers() { return "这是一个被保护的资源 /user/all"; } }
4. 创建 spring-boot 启动类 Case1Application.java
package net.txt100.learn.springsecurity.base.case1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author <a href="mailto:me@tonglei.win">Tonglei</a> * @since 1.0 */ @SpringBootApplication public class Case1Application { public static void main(String[] args) { SpringApplication.run(Case1Application.class, args); } }
5. 编译及执行
打开命令行,进入工程根目录,执行编译命令
gradle compileJava
执行运行命令
gradle run
访问 http://localhost:8080/user/all
此时浏览器显示如下
用户名填入 user
密码每次启动时自动生成,可以在日志中找到
...
2019-08-08 15:13:10.028 INFO 824 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 8c20d4a7-7507-41ce-a271-a75fbe0c7dee
认证通过后,可看到 User 控制器返回内容
总结
最简单的 spring-security 项目只需要在项目依赖中增加 spring-boot-starter-security 即可。
默认情况下,该项目的所有资源地址均需认证成功后才能访问。默认账户 user,密码可从日志中找到。
如果想取消默认的安全设置,需要在配置文件中增加以下内容:
security.basic.enabled = false # 默认禁用 spring-security 安全配置