Spring Boot中使用 Spring Security 構(gòu)建權(quán)限系統(tǒng)的示例代碼
Spring Security是一個(gè)能夠?yàn)榛赟pring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪(fǎng)問(wèn)控制解決方案的安全框架。它提供了一組可以在Spring應(yīng)用上下文中配置的Bean,為應(yīng)用系統(tǒng)提供聲明式的安全訪(fǎng)問(wèn)控制功能,減少了為企業(yè)系統(tǒng)安全控制編寫(xiě)大量重復(fù)代碼的工作。
權(quán)限控制是非常常見(jiàn)的功能,在各種后臺(tái)管理里權(quán)限控制更是重中之重.在Spring Boot中使用 Spring Security 構(gòu)建權(quán)限系統(tǒng)是非常輕松和簡(jiǎn)單的.下面我們就來(lái)快速入門(mén) Spring Security .在開(kāi)始前我們需要一對(duì)多關(guān)系的用戶(hù)角色類(lèi),一個(gè)restful的controller.
- 添加 Spring Security 依賴(lài)
首先我默認(rèn)大家都已經(jīng)了解 Spring Boot 了,在 Spring Boot 項(xiàng)目中添加依賴(lài)是非常簡(jiǎn)單的.把對(duì)應(yīng)的spring-boot-starter-*** 加到pom.xml文件中就行了
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
- 配置 Spring Security
簡(jiǎn)單的使用 Spring Security 只要配置三個(gè)類(lèi)就完成了,分別是:
UserDetails
這個(gè)接口中規(guī)定了用戶(hù)的幾個(gè)必須要有的方法
public interface UserDetails extends Serializable { //返回分配給用戶(hù)的角色列表 Collection<? extends GrantedAuthority> getAuthorities(); //返回密碼 String getPassword(); //返回帳號(hào) String getUsername(); // 賬戶(hù)是否未過(guò)期 boolean isAccountNonExpired(); // 賬戶(hù)是否未鎖定 boolean isAccountNonLocked(); // 密碼是否未過(guò)期 boolean isCredentialsNonExpired(); // 賬戶(hù)是否激活 boolean isEnabled(); }
UserDetailsService
這個(gè)接口只有一個(gè)方法 loadUserByUsername,是提供一種用 用戶(hù)名 查詢(xún)用戶(hù)并返回的方法。
public interface UserDetailsService { UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException; }
WebSecurityConfigurerAdapter
這個(gè)內(nèi)容很多,就不貼代碼了,大家可以自己去看.
我們創(chuàng)建三個(gè)類(lèi)分別繼承上述三個(gè)接口
此 User 類(lèi)不是我們的數(shù)據(jù)庫(kù)里的用戶(hù)類(lèi),是用來(lái)安全服務(wù)的.
/** * Created by Yuicon on 2017/5/14. */ public class User implements UserDetails { private final String id; //帳號(hào),這里是我數(shù)據(jù)庫(kù)里的字段 private final String account; //密碼 private final String password; //角色集合 private final Collection<? extends GrantedAuthority> authorities; User(String id, String account, String password, Collection<? extends GrantedAuthority> authorities) { this.id = id; this.account = account; this.password = password; this.authorities = authorities; } //返回分配給用戶(hù)的角色列表 @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @JsonIgnore public String getId() { return id; } @JsonIgnore @Override public String getPassword() { return password; } //雖然我數(shù)據(jù)庫(kù)里的字段是 `account` ,這里還是要寫(xiě)成 `getUsername()`,因?yàn)槭抢^承的接口 @Override public String getUsername() { return account; } // 賬戶(hù)是否未過(guò)期 @JsonIgnore @Override public boolean isAccountNonExpired() { return true; } // 賬戶(hù)是否未鎖定 @JsonIgnore @Override public boolean isAccountNonLocked() { return true; } // 密碼是否未過(guò)期 @JsonIgnore @Override public boolean isCredentialsNonExpired() { return true; } // 賬戶(hù)是否激活 @JsonIgnore @Override public boolean isEnabled() { return true; } }
繼承 UserDetailsService
/** * Created by Yuicon on 2017/5/14. */ @Service public class UserDetailsServiceImpl implements UserDetailsService { // jpa @Autowired private UserRepository userRepository; /** * 提供一種從用戶(hù)名可以查到用戶(hù)并返回的方法 * @param account 帳號(hào) * @return UserDetails * @throws UsernameNotFoundException */ @Override public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException { // 這里是數(shù)據(jù)庫(kù)里的用戶(hù)類(lèi) User user = userRepository.findByAccount(account); if (user == null) { throw new UsernameNotFoundException(String.format("沒(méi)有該用戶(hù) '%s'.", account)); } else { //這里返回上面繼承了 UserDetails 接口的用戶(hù)類(lèi),為了簡(jiǎn)單我們寫(xiě)個(gè)工廠類(lèi) return UserFactory.create(user); } } }
UserDetails 工廠類(lèi)
/** * Created by Yuicon on 2017/5/14. */ final class UserFactory { private UserFactory() { } static User create(User user) { return new User( user.getId(), user.getAccount(), user.getPassword(), mapToGrantedAuthorities(user.getRoles().stream().map(Role::getName).collect(Collectors.toList())) ); } //將與用戶(hù)類(lèi)一對(duì)多的角色類(lèi)的名稱(chēng)集合轉(zhuǎn)換為 GrantedAuthority 集合 private static List<GrantedAuthority> mapToGrantedAuthorities(List<String> authorities) { return authorities.stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } }
重點(diǎn), 繼承 WebSecurityConfigurerAdapter 類(lèi)
/** * Created by Yuicon on 2017/5/14. */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // Spring會(huì)自動(dòng)尋找實(shí)現(xiàn)接口的類(lèi)注入,會(huì)找到我們的 UserDetailsServiceImpl 類(lèi) @Autowired private UserDetailsService userDetailsService; @Autowired public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder // 設(shè)置UserDetailsService .userDetailsService(this.userDetailsService) // 使用BCrypt進(jìn)行密碼的hash .passwordEncoder(passwordEncoder()); } // 裝載BCrypt密碼編碼器 @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } //允許跨域 @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*") .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS") .allowCredentials(false).maxAge(3600); } }; } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity // 取消csrf .csrf().disable() // 基于token,所以不需要session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 允許對(duì)于網(wǎng)站靜態(tài)資源的無(wú)授權(quán)訪(fǎng)問(wèn) .antMatchers( HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js", "/webjars/**", "/swagger-resources/**", "/*/api-docs" ).permitAll() // 對(duì)于獲取token的rest api要允許匿名訪(fǎng)問(wèn) .antMatchers("/auth/**").permitAll() // 除上面外的所有請(qǐng)求全部需要鑒權(quán)認(rèn)證 .anyRequest().authenticated(); // 禁用緩存 httpSecurity.headers().cacheControl(); } }
- 控制權(quán)限到 controller
使用 @PreAuthorize("hasRole('ADMIN')") 注解就可以了
/** * 在 @PreAuthorize 中我們可以利用內(nèi)建的 SPEL 表達(dá)式:比如 'hasRole()' 來(lái)決定哪些用戶(hù)有權(quán)訪(fǎng)問(wèn)。 * 需注意的一點(diǎn)是 hasRole 表達(dá)式認(rèn)為每個(gè)角色名字前都有一個(gè)前綴 'ROLE_'。所以這里的 'ADMIN' 其實(shí)在 * 數(shù)據(jù)庫(kù)中存儲(chǔ)的是 'ROLE_ADMIN' 。這個(gè) @PreAuthorize 可以修飾Controller也可修飾Controller中的方法。 **/ @RestController @RequestMapping("/users") @PreAuthorize("hasRole('USER')") //有ROLE_USER權(quán)限的用戶(hù)可以訪(fǎng)問(wèn) public class UserController { @Autowired private UserRepository repository; @PreAuthorize("hasRole('ADMIN')")//有ROLE_ADMIN權(quán)限的用戶(hù)可以訪(fǎng)問(wèn) @RequestMapping(method = RequestMethod.GET) public List<User> getUsers() { return repository.findAll(); } }
- 結(jié)語(yǔ)
Spring Boot中 Spring Security 的入門(mén)非常簡(jiǎn)單,很快我們就能有一個(gè)滿(mǎn)足大部分需求的權(quán)限系統(tǒng)了.而配合 Spring Security 的好搭檔就是 JWT 了,兩者的集成文章網(wǎng)絡(luò)上也很多,大家可以自行集成.因?yàn)槠蛴胁簧俅a省略了,需要的可以參考項(xiàng)目代碼
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java中的類(lèi)加載器_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了Java中類(lèi)加載器的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06Java實(shí)現(xiàn)線(xiàn)程插隊(duì)的示例代碼
在編寫(xiě)多線(xiàn)程的業(yè)務(wù)時(shí),會(huì)遇到讓一個(gè)線(xiàn)程優(yōu)先于其他線(xiàn)程運(yùn)行的情況,除了可以設(shè)置線(xiàn)程的優(yōu)先級(jí)高于其他線(xiàn)程,還有更直接的方式:線(xiàn)程插隊(duì)。本文將用Java實(shí)現(xiàn)線(xiàn)程插隊(duì),需要的可以參考一下2022-08-08spring boot集成shiro詳細(xì)教程(小結(jié))
這篇文章主要介紹了spring boot 集成shiro詳細(xì)教程,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01簡(jiǎn)單了解java集合框架LinkedList使用方法
這篇文章主要介紹了簡(jiǎn)單了解java集合框架LinkedList使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08使用Springboot對(duì)配置文件中的敏感信息加密
這篇文章主要介紹了使用Springboot對(duì)配置文件中的敏感信息加密方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08如何禁用IntelliJ IDEA的LightEdit模式(推薦)
這篇文章主要介紹了如何禁用IntelliJ IDEA的LightEdit模式,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04