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@EnableWebSecuritypublic 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@EnableWebSecuritypublic 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 異常攔截頁面
@ControllerAdvicepublic 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使用內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: