1 Spring Security
Spring Security,这是一种基于 Spring AOP 和 Servlet 过滤器的安全框架。它提供全面的安全性解决方案,同时在 Web 请求级和方法调用级处理身份确认和授权。
它的设计是基于框架内大范围的依赖的,可以被划分为以下几块。
(1)Web/Http 安全:这是最复杂的部分。通过建立 filter 和相关的 service bean 来实现框架的认证机制。当访问受保护的 URL 时会将用户引入登录界面或者是错误提示界面。
(2)业务对象或者方法的安全:控制方法访问权限的。
(3)AuthenticationManager:处理来自于框架其他部分的认证请求。
(4)AccessDecisionManager:为 Web 或方法的安全提供访问决策。会注册一个默认的,但是我们也可以通过普通 bean 注册的方式使用自定义的 AccessDecisionManager。
(5)AuthenticationProvider:AuthenticationManager 是通过它来认证用户的。
(6)UserDetailsService:跟 AuthenticationProvider 关系密切,用来获取用户信息的。
2 添加Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3 SecurityConfig
进行请求拦截。
package com.config;
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 extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// 过滤请求
.authorizeRequests()
//允许匿名访问
.antMatchers("/test/help").anonymous()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
}
}
4 创建请求URL
TestController.java:
package com.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/help")
public String help(){
return "hello,Help!";
}
@GetMapping("/login")
public String login(){
return "hello,login!";
}
}
5 调试结果
可以请求的url,会直接显示结果。
不可以请求的url,会提示403,代表没有权限访问。