角色訪問控制 通常情況下,我們需要實現“特定資源只能由特定角色訪問”的功能。假設我們的系統 有如下兩個角色: ADMIN 可以訪問所有資源 USER 只能訪問特定資源 現在我們給系統增加“/user/**”接口代表用戶信息方面的資源(USER 可以訪問);增加"/admin/**"接口代表管理員方面的資源(USER 不能訪問),代碼如下:
/*用戶信息方面的資源*/ @RestController public class UserController { @RequestMapping("/user/hello") public String hello() { return "user,Hello !"; } }
/*管理員方面的資源*/ @RestController public class AdminController { @RequestMapping("/admin/hello") public String hello() { return "admin,Hello !"; } }
在實際開發中,我們的用戶和角色是保存在數據庫中的
為了方便演示,我們來創建兩個存放於內存的用戶和角色。我們可以自定義類並集成 WebSecurityConfigurerAdapter 進而實現 Spring Security 的更多配置,如下代碼
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { /*不對密碼進行加密*/ @Bean PasswordEncoder passwordEncoder(){ return NoOpPasswordEncoder.getInstance(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() /*管理員用戶 具備 ADMIN 和 USER 角色*/ .withUser("admin").password("admin").roles("ADMIN", "USER") .and() /*普通用戶*/ .withUser("beixi").password("beixi").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() /*普通用戶訪問的 url*/ .antMatchers("/user/**").hasRole("USER") /*管理員用戶訪問的 url*/ .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() //其他多有路徑都必須認證 .and() .formLogin() .loginProcessingUrl("/login") .permitAll() //訪問/login 接口不需要進行身份認證了,防止重定向死循環 .and() .csrf().disable(); //關閉 csrf } }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.security</groupId> <artifactId>springsecurity</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <!-- 聲明項目配置依賴編碼格式為 utf-8 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <fastjson.version>1.2.24</fastjson.version> </properties> <dependencies> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
server.port=8087
spring.security.user.name=admin
spring.security.user.password=123456
package com.tszr.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String home() { return "Hello ,spring security!"; } }
package com.tszr.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @RequestMapping("/user/hello") public String hello() { return "user,Hello !"; } }
package com.tszr.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AdminController { @RequestMapping("/admin/hello") public String hello() { return "admin,Hello !"; } }
package com.tszr.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @SuppressWarnings("deprecation") @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { /* 不對密碼進行加密 */ @Bean PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() /* 管理員用戶 具備ADMIN和USER角色 */ .withUser("admin").password("admin").roles("ADMIN", "USER").and() /* 普通用戶 */ .withUser("beixi").password("beixi").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() /* 普通用戶訪問的url */ .antMatchers("/user/**").hasRole("USER") /* 管理員用戶訪問的url */ .antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated() // 其他多有路徑都必須認證 .and().formLogin().loginProcessingUrl("/login").permitAll() // 訪問“/login”接口不需要進行身份認證了,防止重定向死循環 .and().csrf().disable(); // 關閉csrf } }
package com.tszr.application; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }