權限控制,也是我們再日常開發中經常遇到的場景,需要根據用戶的角色決定是否可以看到某個資源。目前,市面上此類框架主要有shiro與我們今天要講到的spring security。關於權限的控制有復雜的控制,例如幾乎每個公司都有單點登錄系統,根據用戶名來到數據庫中拿到對應的權限,在展示該權限下能看到的資源。還有一種就是簡單的控制,也就是我們今天所要提到的。將賬號,密碼,角色配置到代碼中,也可以進行簡單的控制,缺點不言而喻,擴展性不好,只有固定的賬號,但是作為演示還是夠用的。
好了廢話不多說,上pom
<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,可能會因為版本之間的不兼容而爆出各種問題,這都是題外話,讚歎一下,我們繼續。看下配置類
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;@EnableWebSecuritypublic 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權限對應的用戶名密碼,所以看下配置文件
security: user: name: root password: root role: ADMIN
配置都差不多了,看一眼我們的Controller
package com.shuqi.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic 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確實幫助我們做到了訪問的控制。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。