Spring Security 在 Spring Boot 中的使用詳解【集中式】
1.1 準(zhǔn)備
1.1.1 創(chuàng)建 Spring Boot 項(xiàng)目
創(chuàng)建好一個(gè)空的 Spring Boot 項(xiàng)目之后,寫一個(gè) controller 驗(yàn)證此時(shí)是可以直接訪問到該控制器的。
1.1.2 引入 Spring Security
在 Spring Boot 中引入 Spring Security 是相當(dāng)簡(jiǎn)單的,可以在用腳手架創(chuàng)建項(xiàng)目的時(shí)候勾選,也可以創(chuàng)建完畢后在 pom 文件中加入相關(guān)依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>
引入 Spring Security 后再次訪問會(huì)發(fā)現(xiàn)直接被彈到了登錄頁面,此時(shí)我們還什么都沒有配置,為什么 Security 會(huì)生效呢,這是因?yàn)?Spring Boot 幫我們完成了在 Spring 中需要完成的諸多配置【☞ Spring Security 基礎(chǔ)入門】。也正是因?yàn)?Spring Boot 提供了自動(dòng)化配置方案,讓我們可以“零配置”的使用 Spring Security,所以在 Spring Boot 項(xiàng)目中我們通常使用的安全框架是 Spring Security 而在 Spring 中一般使用 Shiro。
我們并沒有配置靜態(tài)的用戶那么該如何登錄呢,Spring Boot 為我們提供了一個(gè)默認(rèn)的用戶,用戶名為:user,密碼則是在啟動(dòng) Spring Boot 項(xiàng)目是隨機(jī)生成的,我們可以在控制臺(tái)找到他。
1.2 配置認(rèn)證
1.2.1 添加靜態(tài)用戶
Spring Boot 除了一些信息寫道 yml 配置文件中,其他配置都使用配置類,Spring Security 需要繼承 WebSecurityConfigurerAdapter,配置用戶信息需要重寫 configure(AuthenticationManagerBuilder auth) 方法。配置完畢后,將不會(huì)再使用 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 { // 配置靜態(tài)用戶 auth.inMemoryAuthentication() .withUser('admin') .password('{noop}123') // 此處需要加 {noop} 表示該密碼為明文 .roles('USER'); }}
1.2.2 添加數(shù)據(jù)庫認(rèn)證 ☞ 添加用戶實(shí)體類
Spring Security 中使用的用戶是 UserDetails,我們要么讓自定義用戶類實(shí)現(xiàn) UserDetails,要么使用時(shí)將自定義用戶類轉(zhuǎn)換為 UserDetails。建議實(shí)現(xiàn) UserDetails。因?yàn)樵擃愔猩婕暗浇巧畔⑺晕覀冞€需要?jiǎng)?chuàng)建角色類。我們?cè)谝院蟮牟僮髦锌赡軙?huì)將對(duì)象轉(zhuǎn)為 json 或者將 json 轉(zhuǎn)為對(duì)象,所以我們重寫的方法需要加上 @JsonIgnore 將其忽略(該類本來就需要的不用忽略)。
/** * Created with IntelliJ IDEA. * * @author gaohu9712@163.com * @date 2020/10/18 * @description 用戶實(shí)體類 */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; }}
☞ 創(chuàng)建角色類
Spring Security 中使用的角色信息使用的是 GrantedAuthority 所以我們的角色類也需要實(shí)現(xiàn) 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 操作數(shù)據(jù)庫的內(nèi)容【☞ Mybatis 使用通用 mapper】,jpa 等其他操作數(shù)據(jù)庫的方法亦可。
☞ 認(rèn)證類
Spring Boot 中 Spring Security 的認(rèn)證類與 Spring 中的并無區(qū)別,都需要實(shí)現(xiàn) UserDetailsService 接口,然后重寫 loadUserByUsername(String s) 方法并返回一個(gè) UserDetails。
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description 認(rèn)證類 */ 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 { // 認(rèn)證類 auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); }}
1.3 授權(quán)
1.3.1 開啟方法級(jí)授權(quán)
在啟動(dòng)類上使用 @EnableGlobalMethodSecurity 注解開啟方法級(jí)授權(quán)。參數(shù) prePostEnabled 代表 Spring 中的權(quán)限控制注解;securedEnabled 代表 Spring Security 中的權(quán)限控制注解; jsr250Enabled 代表 jsr250 的權(quán)限控制注解。
@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 添加方法權(quán)限
當(dāng)用戶僅有 ROLE_USER 權(quán)限時(shí)僅能訪問 findStr 方法而不能訪問 get 方法;要想訪問 get 方法用戶必須具有 ROLE_ADMIN 權(quán)限。
/** * 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 '請(qǐng)求成功'; } @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'; }}
總結(jié)
到此這篇關(guān)于Spring Security 在 Spring Boot 中的使用詳解【集中式】的文章就介紹到這了,更多相關(guān)Spring Security 在 Spring Boot使用內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
