Spring Security 在 Spring Boot 中的使用詳解【集中式】
1.1 準備
1.1.1 建立 Spring Boot 專案
建立好一個空的 Spring Boot 專案之後,寫一個 controller 驗證此時是可以直接訪問到該控制器的。
1.1.2 引入 Spring Security
在 Spring Boot 中引入 Spring Security 是相當簡單的,可以在用腳手架建立專案的時候勾選,也可以建立完畢後在 pom 檔案中加入相關依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
引入 Spring Security 後再次訪問會發現直接被彈到了登入頁面,此時我們還什麼都沒有配置,為什麼 Security 會生效呢,這是因為 Spring Boot 幫我們完成了在 Spring 中需要完成的諸多配置【☞Spring Security 基礎入門】。也正是因為 Spring Boot 提供了自動化配置方案,讓我們可以“零配置”的使用 Spring Security,所以在 Spring Boot 專案中我們通常使用的安全框架是 Spring Security 而在 Spring 中一般使用 Shiro。
我們並沒有配置靜態的使用者那麼該如何登入呢,Spring Boot 為我們提供了一個預設的使用者,使用者名稱為:user,密碼則是在啟動 Spring Boot 專案是隨機生成的,我們可以在控制檯找到他。
1.2 配置認證
1.2.1 新增靜態使用者
Spring Boot 除了一些資訊寫道 yml 配置檔案中,其他配置都使用配置類,Spring Security 需要繼承 WebSecurityConfigurerAdapter
,配置使用者資訊需要重寫 configure(AuthenticationManagerBuilder auth)
方法。配置完畢後,將不會再使用 user 使用者。
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description Spring Security 配置類 */ @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 配置靜態使用者 auth.inMemoryAuthentication() .withUser("admin") .password("{noop}123") // 此處需要加 {noop} 表示該密碼為明文 .roles("USER"); } }
1.2.2 新增資料庫認證 ☞ 新增使用者實體類
Spring Security 中使用的使用者是 UserDetails,我們要麼讓自定義使用者類實現 UserDetails,要麼使用時將自定義使用者類轉換為 UserDetails。建議實現 UserDetails。因為該類中涉及到角色資訊所以我們還需要建立角色類。我們在以後的操作中可能會將物件轉為 json 或者將 json 轉為物件,所以我們重寫的方法需要加上 @JsonIgnore
將其忽略(該類本來就需要的不用忽略)。
/** * Created with IntelliJ IDEA. * * @author [email protected] * @date 2020/10/18 * @description 使用者實體類 */ public class SysUser implements UserDetails { private Long id; private String username; private String passwrod; private List<SysRole> roleList = new ArrayList<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public void setUsername(String username) { this.username = username; } public void setPasswrod(String passwrod) { this.passwrod = passwrod; } public List<SysRole> getRoleList() { return roleList; } public void setRoleList(List<SysRole> roleList) { this.roleList = roleList; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return roleList; } @Override public String getPassword() { return passwrod; } @Override public String getUsername() { return username; } @Override @JsonIgnore public boolean isAccountNonExpired() { return false; } @Override @JsonIgnore public boolean isAccountNonLocked() { return false; } @Override @JsonIgnore public boolean isCredentialsNonExpired() { return false; } @Override @JsonIgnore public boolean isEnabled() { return false; } }
☞ 建立角色類
Spring Security 中使用的角色資訊使用的是 GrantedAuthority 所以我們的角色類也需要實現 GrantedAuthority。
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description 角色類 */ public class SysRole implements GrantedAuthority { private Long id; private String roleName; private String roleDesc; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleDesc() { return roleDesc; } public void setRoleDesc(String roleDesc) { this.roleDesc = roleDesc; } @Override @JsonIgnore public String getAuthority() { return roleName; } }
☞ 新增持久層
此處省略使用通用 mapper 操作資料庫的內容【☞ Mybatis 使用通用 mapper】,jpa 等其他操作資料庫的方法亦可。
☞ 認證類
Spring Boot 中 Spring Security 的認證類與 Spring 中的並無區別,都需要實現 UserDetailsService 介面,然後重寫 loadUserByUsername(String s)
方法並返回一個 UserDetails。
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description 認證類 */ public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { return userMapper.findByName(s); } }
☞ 配置類
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description Spring Security 配置類 */ @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Bean // BCrypt 交由 Ioc 容器管理 public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 認證類 auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } }
1.3 授權
1.3.1 開啟方法級授權
在啟動類上使用 @EnableGlobalMethodSecurity
註解開啟方法級授權。引數 prePostEnabled 代表 Spring 中的許可權控制註解;securedEnabled 代表 Spring Security 中的許可權控制註解; jsr250Enabled 代表 jsr250 的許可權控制註解
。
@SpringBootApplication @MapperScan("com.software.springsecurity.mapper") @EnableGlobalMethodSecurity(securedEnabled = true) public class SpringSecurityApplication { public static void main(String[] args) { SpringApplication.run(SpringSecurityApplication.class,args); } }
1.3.2 新增方法許可權
當用戶僅有 ROLE_USER
許可權時僅能訪問 findStr 方法而不能訪問 get 方法;要想訪問 get 方法使用者必須具有 ROLE_ADMIN
許可權。
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description */ @RestController @RequestMapping("/demo") public class DemoController { @GetMapping("/find") @Secured("ROLE_USER") public String findStr() { return "請求成功"; } @GetMapping("/get") @Secured("ROLE_ADMIN") public String get() { return "get"; } }
1.3.3 異常攔截頁面
@ControllerAdvice public class HandlerControllerAdvice { @ExceptionHandler(AccessDeniedException.class) public String handlerException(){ return "redirect:/403.html"; } @ExceptionHandler(RuntimeException.class) public String runtimeHandlerException(){ return "redirect:/500.html"; } }
總結
到此這篇關於Spring Security 在 Spring Boot 中的使用詳解【集中式】的文章就介紹到這了,更多相關Spring Security 在 Spring Boot使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!