【SpringBoot】Spring Security(1):初體驗

如果餓了就吃,困了就睡,渴了就喝,人生就太無趣了
源碼地址:https://github.com/keer123456789/springbootstudy/tree/master/security_demo_1


1.Spring Security 簡介

Spring Security是一個能夠爲基於Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反轉Inversion of Control ,DI:Dependency Injection 依賴注入)和AOP(面向切面編程)功能,爲應用系統提供聲明式的安全訪問控制功能,減少了爲企業系統安全控制編寫大量重複代碼的工作。

以上解釋來源於百度百科。可以一句話來概括,SpringSecurity 是一個安全框架。
作用大致分爲以下幾個方面:

  • 身份認證(你是誰?)
  • 權限校驗(你能做什麼?允許操作的範圍)
  • 攻擊防護(防止僞造身份)

2.添加依賴

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

3.添加hello_world 接口

@RestController
@RequestMapping("/security")
public class Controller {
    protected Logger logger= LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "hello",method = RequestMethod.GET)
    public String hello() {
        return "hello_world";
    }
}

4.直接運行

完成上述操作後,運行SpringBoot項目,瀏覽器訪問http://127.0.0.1/security/hello
預期結果是返回字符串:hello_world
但結果是:

在這裏插入圖片描述

可以看到瀏覽器的地址自動跳轉到http://127.0.0.1:8080/login,說明此時Spring Security已經起作用了,因爲Spring Security提供了一個簡單的登錄界面。
用戶名默認爲user,密碼則需要看springboot啓動時的日誌:

在這裏插入圖片描述

冒號後面的就是密碼,粘貼複製即可。

輸入完用戶名密碼之後,結果如:此時瀏覽器的地址就是當初的地址了。

在這裏插入圖片描述

5.配置添加用戶信息

如果不想使用默認用戶登錄信息,則可以在application.properties文件添加配置

spring.security.user.name=admin
spring.security.user.password=admin

重新啓動項目,輸入自定義的用戶名密碼即可登錄

6.關閉 Security 功能

在開發其他功能時調試時,如果總是需要登錄,則過於麻煩,此時可以在啓動類上添加註解來關閉Spring Security功能。再去訪問http://127.0.0.1/security/hello,直接返回hello_world

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class SecurityDemo1Application {

    public static void main(String[] args) {
        SpringApplication.run(SecurityDemo1Application.class, args);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章