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