> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/28.-security.md).

# 28. 安全

如果Spring Security在类路径上，那么web应用默认是安全的。Spring Boot依靠Spring Security的内容协商策略，决定是使用httpBasic，还是formLogin。为了给web应用添加方法级别（method-level）的保护，你可以添加`@EnableGlobalMethodSecurity`并使用想要的设置。其它信息参考[Spring Security参考指南](https://docs.spring.io/spring-security/site/docs/5.0.3.RELEASE/reference/htmlsingle#jc-method)。

默认的`AuthenticationManager`只有一个用户。用户名是user，密码随机，会在应用启动时以INFO日志级别打印出来。如下：

```java
Using generated security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35
```

**注** 如果你对日志配置进行微调，确保`org.springframework.boot.autoconfigure.security`类别记录日志级别为`INFO`，否则默认的密码不会打印出来。

你可以通过提供`spring.security.user.name`和`spring.security.user.password`，改变用户名和密码。

在web应用中，你默认能得到如下的基本特性：

* 一个`UserDetailsService`（如果是WebFlux应用的话，则是`ReactiveUserDetailsService`）bean，存储在内存中。还有一个用户，用户的密码是生成的（关于这个用户的属性，请查看[`SecurityProperties.User`](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/autoconfigure/security/SecurityProperties.User.html)）。
* 应用在整个应用上的基于表单的登录或是HTTP Basic security（取决于Content-Type）。如果执行器在类路径上，则包含执行器端点。
* 一个`DefaultAuthenticationEventPublisher`，用来发布认证事件。

你可以通过添加一个bean，为它提供一个不同的`AuthenticationEventPublisher`。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/28.-security.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
