# Security

## 參考資料:

SpringBoot Spring Security 基本使用及個性化登入配置詳解(<https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/296168/>)

(<https://stackoverflow.com/questions/49717573/property-security-basic-enabled-is-deprecated-the-security-auto-configuration>)

Spring Security-結合RestfulAPI的設計([https://medium.com/%E4%BC%81%E9%B5%9D%E4%B9%9F%E6%87%82%E7%A8%8B%E5%BC%8F%E8%A8%AD%E8%A8%88/spring-security-%E7%B5%90%E5%90%88restfulapi%E7%9A%84%E8%A8%AD%E8%A8%88-60b778fd3b2](https://medium.com/%E4%BC%81%E9%B5%9D%E4%B9%9F%E6%87%82%E7%A8%8B%E5%BC%8F%E8%A8%AD%E8%A8%88/spring-security-%E7%B5%90%E5%90%88restfulapi%E7%9A%84%E8%A8%AD%E8%A8%88-60b778fd3b22))

Spring Boot(四)之使用JWT和Spring Security保護REST API (<https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/309745/>)

## 如何引入Security?

build.gradle 的 dependencies 中加入

```
implementation 'org.springframework.boot:spring-boot-starter-security'
```

{% hint style="info" %}
&#x20;一旦引用 Security 就會自動啟用。

而版本 2.0.1.RELEASE之後，不可以再透過修改配置  spring.basic.enabled=false 來關閉。
{% endhint %}

## 初始頁面 & 預設帳密

一旦啟用 Security，連線到頁面，就會被導址到默認的 `/login` 去做登入的動作<br>

![](/files/-Lz14PFyp8FUvrgv-cOE)

預設帳號為：`user`\
密碼為每次服務啟動時隨機產生 (參考下圖)

![](/files/-Lz14dcP07InMkiyBXee)

## 如何調整預設的帳號密碼

那如果不希望每次都隨機密碼，到底要怎麼去做設定呢?\
可以去 設定檔 設置默認的使用者、密碼 (roles 我還沒弄清楚)。

```
spring.security.user.name=user # Default user name.
spring.security.user.password= # Password for the default user name.
spring.security.user.roles= # Granted roles for the default user name.
```

## 如何調整輸入帳密的方式

### 利用 HTTP基本認證&#x20;

```
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 直接跳過驗證
        httpSecurity.authorizeRequests().anyRequest().permitAll();
        
        // 利用 HTTP 基本認證
        // For example: Use only Http Basic and not form login.
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }
}
```

![](/files/-Lz192zNo_lpAweXbIP9)


---

# 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://brianwu.gitbook.io/brian/java/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.
