Spring Security 在 Spring Boot 中的使用詳解【集中式】
1.1 準(zhǔn)備
1.1.1 創(chuàng)建 Spring Boot 項(xiàng)目
創(chuàng)建好一個(gè)空的 Spring Boot 項(xiàng)目之后,寫(xiě)一個(gè) controller 驗(yàn)證此時(shí)是可以直接訪(fǎng)問(wèn)到該控制器的。
1.1.2 引入 Spring Security
在 Spring Boot 中引入 Spring Security 是相當(dāng)簡(jiǎn)單的,可以在用腳手架創(chuàng)建項(xiàng)目的時(shí)候勾選,也可以創(chuàng)建完畢后在 pom 文件中加入相關(guān)依賴(lài)。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
引入 Spring Security 后再次訪(fǎng)問(wèn)會(huì)發(fā)現(xiàn)直接被彈到了登錄頁(yè)面,此時(shí)我們還什么都沒(méi)有配置,為什么 Security 會(huì)生效呢,這是因?yàn)?Spring Boot 幫我們完成了在 Spring 中需要完成的諸多配置【☞Spring Security 基礎(chǔ)入門(mén)】。也正是因?yàn)?Spring Boot 提供了自動(dòng)化配置方案,讓我們可以“零配置”的使用 Spring Security,所以在 Spring Boot 項(xiàng)目中我們通常使用的安全框架是 Spring Security 而在 Spring 中一般使用 Shiro。
我們并沒(méi)有配置靜態(tài)的用戶(hù)那么該如何登錄呢,Spring Boot 為我們提供了一個(gè)默認(rèn)的用戶(hù),用戶(hù)名為:user,密碼則是在啟動(dòng) Spring Boot 項(xiàng)目是隨機(jī)生成的,我們可以在控制臺(tái)找到他。
1.2 配置認(rèn)證
1.2.1 添加靜態(tài)用戶(hù)
Spring Boot 除了一些信息寫(xiě)道 yml 配置文件中,其他配置都使用配置類(lèi),Spring Security 需要繼承 WebSecurityConfigurerAdapter
,配置用戶(hù)信息需要重寫(xiě) configure(AuthenticationManagerBuilder auth)
方法。配置完畢后,將不會(huì)再使用 user 用戶(hù)。
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description Spring Security 配置類(lèi) */ @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 配置靜態(tài)用戶(hù) auth.inMemoryAuthentication() .withUser("admin") .password("{noop}123") // 此處需要加 {noop} 表示該密碼為明文 .roles("USER"); } }
1.2.2 添加數(shù)據(jù)庫(kù)認(rèn)證 ☞ 添加用戶(hù)實(shí)體類(lèi)
Spring Security 中使用的用戶(hù)是 UserDetails,我們要么讓自定義用戶(hù)類(lèi)實(shí)現(xiàn) UserDetails,要么使用時(shí)將自定義用戶(hù)類(lèi)轉(zhuǎn)換為 UserDetails。建議實(shí)現(xiàn) UserDetails。因?yàn)樵擃?lèi)中涉及到角色信息所以我們還需要?jiǎng)?chuàng)建角色類(lèi)。我們?cè)谝院蟮牟僮髦锌赡軙?huì)將對(duì)象轉(zhuǎn)為 json 或者將 json 轉(zhuǎn)為對(duì)象,所以我們重寫(xiě)的方法需要加上 @JsonIgnore
將其忽略(該類(lèi)本來(lái)就需要的不用忽略)。
/** * Created with IntelliJ IDEA. * * @author gaohu9712@163.com * @date 2020/10/18 * @description 用戶(hù)實(shí)體類(lèi) */ 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)建角色類(lèi)
Spring Security 中使用的角色信息使用的是 GrantedAuthority 所以我們的角色類(lèi)也需要實(shí)現(xiàn) GrantedAuthority。
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description 角色類(lèi) */ 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ù)庫(kù)的內(nèi)容【☞ Mybatis 使用通用 mapper】,jpa 等其他操作數(shù)據(jù)庫(kù)的方法亦可。
☞ 認(rèn)證類(lèi)
Spring Boot 中 Spring Security 的認(rèn)證類(lèi)與 Spring 中的并無(wú)區(qū)別,都需要實(shí)現(xiàn) UserDetailsService 接口,然后重寫(xiě) loadUserByUsername(String s)
方法并返回一個(gè) UserDetails。
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description 認(rèn)證類(lèi) */ public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { return userMapper.findByName(s); } }
☞ 配置類(lèi)
/** * Created with IntelliJ IDEA. * * @author Demo_Null * @date 2020/10/18 * @description Spring Security 配置類(lèi) */ @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 { // 認(rèn)證類(lèi) auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } }
1.3 授權(quán)
1.3.1 開(kāi)啟方法級(jí)授權(quán)
在啟動(dòng)類(lèi)上使用 @EnableGlobalMethodSecurity
注解開(kāi)啟方法級(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)用戶(hù)僅有 ROLE_USER
權(quán)限時(shí)僅能訪(fǎng)問(wèn) findStr 方法而不能訪(fǎng)問(wèn) get 方法;要想訪(fǎng)問(wèn) get 方法用戶(hù)必須具有 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 異常攔截頁(yè)面
@ControllerAdvice public 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)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis傳遞多個(gè)參數(shù)的解決辦法(三種)
這篇文章主要介紹了Mybatis傳遞多個(gè)參數(shù)的解決辦法(三種),個(gè)人覺(jué)得第三種解決辦法比較好用,有需要的朋友一起學(xué)習(xí)吧2016-05-05Java調(diào)用第三方接口封裝實(shí)現(xiàn)
本文主要介紹了Java調(diào)用第三方接口封裝實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02Java使用正則表達(dá)式驗(yàn)證手機(jī)號(hào)和電話(huà)號(hào)碼的方法
今天小編就為大家分享一篇關(guān)于Java使用正則表達(dá)式驗(yàn)證手機(jī)號(hào)和電話(huà)號(hào)碼的方法,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12IntelliJ IDEA修改新建文件自動(dòng)生成注釋的user名
今天小編就為大家分享一篇關(guān)于IntelliJ IDEA修改新建文件自動(dòng)生成注釋的user名,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10@PathVariable為空時(shí)指定默認(rèn)值的操作
這篇文章主要介紹了@PathVariable為空時(shí)指定默認(rèn)值的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02