# 1.Spring Security

## 基本入门

添加依赖

```java
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
```

基本配置用户名密码

```java
security.user.name = admin
security.user.password = 123456
```

以上配置完成后，针对 是所有 访问进行用户密码验证，实际开发中需要进行不同的url进行权限访问控制。

## 原理

Spring Security 就是一组过滤器组成的链,这组过滤器链放置在REST API前面，所有调用REST API的请求和响应都要经过这组Spring Security 过滤器链，过滤链的顺序是固定的。

![](/files/-LfnTKNpw4Y1TOZ8qw43)

![](/files/-LfnTKNrTJODvsmFlthh)

**用户认证授权**

深绿色的方块与图一深绿色的方块对应，进行用户认证授权，认证授权完放入Authentication

**获取认证授权后的信息**

蓝色方块是保存和获取用户认证信息这个机制相关的一一些类和接口，也就是图1中的REST API内部我们可以使用这些类和接口来获取认证登录后的用户信息

* Authentication  用来保存用户认证信息的，比如认证时的用户名密码，认证以后获得的当前用户信息
* SecurityContent 安全上下文，包含着Authentication 这个对象
* SecurityContextHolderStagegy
* SecurityContextHolder

示例

```java
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // 获取当前登录用户的信息
System.out.println(authentication);
if(authentication != null) {
    System.out.println(authentication.getPrincipal()); // 当前认证后的信息
}
```

## 资料

[Spring Security 参考手册](https://springcloud.cc/spring-security-zhcn.html)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://spring-boot.shujuwajue.com/an-quan/spring-security.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
