權限控制,也是我們再日常開發中經常遇到的場景,需要根據用戶的角色決定是否可以看到某個資源。目前,市面上此類框架主要有shiro與我們今天要講到的spring security。關于權限的控制有復雜的控制,例如幾乎每個公司都有單點登錄系統,根據用戶名來到數據庫中拿到對應的權限,在展示該權限下能看到的資源。還有一種就是簡單的控制,也就是我們今天所要提到的。將賬號,密碼,角色配置到代碼中,也可以進行簡單的控制,缺點不言而喻,擴展性不好,只有固定的賬號,但是作為演示還是夠用的。
好了廢話不多說,上pom
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-security</artifactid> </dependency> |
spring-boot-starter-security里面包裝了spring security所需要的依賴。不需要我們一個個的配置,簡化了我們的操作,節省了我們的時間,不得不說,這些企業級框架考慮的就是很周到,如果我們自己添加jar,可能會因為版本之間的不兼容而爆出各種問題,這都是題外話,贊嘆一下,我們繼續。看下配置類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package com.shuqi; import org.springframework.context.annotation.configuration; import org.springframework.core.annotation.order; 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 { @configuration public static class websecurityconfigurationadapter extends websecurityconfigureradapter { @override protected void configure(httpsecurity http) throws exception { http.csrf().disable(); http .authorizerequests() .antmatchers( "/index" ).hasrole( "admin" ) .anyrequest().permitall() .and() .httpbasic() ; } } } |
這段配置翻譯成中文是:對于訪問/index這個鏈接需要admin權限,其他的全都都允許。有的時候我們只會注意代碼,其實這個注解@enablewebsecurity會重要更多,因為他是spring security的開始,他引入了諸多的配置類,才使得security生效。我們設置了admin權限,但是沒有設置admin權限對應的用戶名密碼,所以看下配置文件
1
2
3
4
5
|
security: user: name: root password: root role: admin |
配置都差不多了,看一眼我們的controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.shuqi.controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.restcontroller; @restcontroller public class hellocontroller { @requestmapping ( "/index" ) public string index(){ return "hello world index" ; } @requestmapping ( "/index1" ) public string index1(){ return "hello world index1" ; } } |
一個被攔截的/index,一個不會被攔截的/index1,看下區別。啟動項目,訪問/index
可以看到已經加了訪問控制,輸入配置的root,root
可以看到結果
輸入/index1可以直接看到結果
說明我們的配置生效了,spring security確實幫助我們做到了訪問的控制。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/c8c7688e2b2b