spring security的核心功能爲認證(Authentication),受權(Authorization),即認證用戶是否能訪問該系統,和受權用戶能夠在系統中進行哪些操做。html
在 pom.xml 中加入java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency>
驗證組件是否起到做用,如今不更改框架內的任何內容,啓動項目,瀏覽器中依舊輸入 http://localhost:8080 ,可看到以下界面,以前能夠直接進入spring boot的初始界面,如今已經看不見了,spring security 導入後默認已經開啓了驗證,必須先登陸驗證經過後才能訪問。web
若是代碼中不作任何設置,默認的帳戶是 user,默認的密碼隨着項目的啓動,會打印在控制檯中。spring
輸入帳號密碼,便可進入默認的初始界面。數據庫
爲了最快最簡單最直接的認識這個組件,直接把用戶密碼寫入內存中,項目啓動即存在,避免還有建表,實體類,數據庫操做等與之無關的內容。命名使用最爲簡單粗暴的方式,排除一切干擾,用最少的精力掌握該組件的使用。編程
新增代碼目錄瀏覽器
index.html安全
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> SPRING BOOT !!! </body> </html>
error.htmlapp
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 錯誤 </body> </html>
UserController框架
package com.example.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("user") public class UserController { @RequestMapping("/addUser") @ResponseBody String addUser() { return "這是添加用戶!!!"; } @RequestMapping("/deleteUser") @ResponseBody String deleteUser() { return "這是刪除用戶!!!"; } @RequestMapping("/updateUser") @ResponseBody String updateUser() { return "這是修改用戶!!!"; } @RequestMapping("/findAllUsers") @ResponseBody String findAllUsers() { return "這是查詢用戶!!!"; } }
UserSecurityConfig
package com.example.config; 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.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; //註解開啓 Spring Security 安全認證與受權 @EnableWebSecurity public class UserSecurityConfig extends WebSecurityConfigurerAdapter { //用戶認證 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //內存裏面放着 auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()) //添加用戶,密碼,角色 .withUser("zs").password("123456").roles("AAA") //鏈式編程 .and() .withUser("ls").password("123456").roles("BBB") .and() .withUser("ww").password("123456").roles("CCC", "primary") .and() .withUser("zl").password("123456").roles("primary"); } //用戶受權 @Override protected void configure(HttpSecurity http) throws Exception { /** * permitAll():容許一切用戶訪問 * hasRole():url請求容許訪問的角色 * hasAnyRole() : url請求容許訪問的多個角色 * access():容許訪問的角色,permitAll、hasRole、hasAnyRole 底層都是調用 access 方法 * access("permitAll") 等價於 permitAll() */ http.authorizeRequests().antMatchers("/").permitAll(); // "/":應用首頁因此用戶均可以訪問 http.authorizeRequests() .antMatchers("/user/addUser").hasRole("AAA") // 首斜槓"/"表示應用上下文,/user/addUser 請求容許 AAA 角色訪問 .antMatchers("/user/deleteUser/**").hasAnyRole("AAA", "BBB") //"/user/deleteUser/**"容許 "AAA", "BBB" 角色訪問,/**匹配任意 .antMatchers("/user/updateUser").hasAnyRole("AAA", "BBB", "CCC")//除了這種鏈式編程,也能夠分開寫 .antMatchers("/user/findAllUsers").access("permitAll"); http.authorizeRequests().anyRequest().authenticated(); /** * formLogin:指定支持基於表單的身份驗證 * 當用戶沒有登陸、沒有權限時就會自動跳轉到登陸頁面(默認 /login) * 當登陸失敗時,默認跳轉到 /error * 登陸成功時會放行 */ http.formLogin(); } }
MyPasswordEncoder
package com.example.config; import org.springframework.security.crypto.password.PasswordEncoder; //密碼編碼,Spring Security 高版本必須進行密碼編碼,不然報錯 public class MyPasswordEncoder implements PasswordEncoder { @Override public String encode(CharSequence charSequence) { return charSequence.toString(); } @Override public boolean matches(CharSequence charSequence, String s) { return s.equals(charSequence.toString()); } }
親測效果是
以用戶名 zs 登陸(其角色權限爲AAA),能夠進入系統,瀏覽器輸入地址能夠訪問, localhost:8080,localhost:8080/user/addUser,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers
以用戶名 ls 登陸(其角色權限爲BBB),能夠進入系統,瀏覽器輸入地址能夠訪問, localhost:8080,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers
以用戶名 ww 登陸(其角色權限爲CCC),能夠進入系統,瀏覽器輸入地址能夠訪問, localhost:8080,localhost:8080/user/deleteUser,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers
以用戶名 zl 登陸(其角色權限爲CCC),能夠進入系統,瀏覽器輸入地址能夠訪問, localhost:8080,localhost:8080/user/updateUser,localhost:8080/user/findAllUsers
以用戶名 admin 登陸,不能夠進入系統,由於系統中尚未該用戶。