Spring Security是一個能夠為基于Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應用上下文中配置的Bean,為應用系統提供聲明式的安全訪問控制功能,減少了為企業系統安全控制編寫大量重復代碼的工作。
權限控制是非常常見的功能,在各種后臺管理里權限控制更是重中之重.在Spring Boot中使用 Spring Security 構建權限系統是非常輕松和簡單的.下面我們就來快速入門 Spring Security .在開始前我們需要一對多關系的用戶角色類,一個restful的controller.
- 添加 Spring Security 依賴
首先我默認大家都已經了解 Spring Boot 了,在 Spring Boot 項目中添加依賴是非常簡單的.把對應的spring-boot-starter-*** 加到pom.xml文件中就行了
1
2
3
4
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-security</ artifactId > </ dependency > |
- 配置 Spring Security
簡單的使用 Spring Security 只要配置三個類就完成了,分別是:
UserDetails
這個接口中規定了用戶的幾個必須要有的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public interface UserDetails extends Serializable { //返回分配給用戶的角色列表 Collection<? extends GrantedAuthority> getAuthorities(); //返回密碼 String getPassword(); //返回帳號 String getUsername(); // 賬戶是否未過期 boolean isAccountNonExpired(); // 賬戶是否未鎖定 boolean isAccountNonLocked(); // 密碼是否未過期 boolean isCredentialsNonExpired(); // 賬戶是否激活 boolean isEnabled(); } |
UserDetailsService
這個接口只有一個方法 loadUserByUsername,是提供一種用 用戶名 查詢用戶并返回的方法。
1
2
3
|
public interface UserDetailsService { UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException; } |
WebSecurityConfigurerAdapter
這個內容很多,就不貼代碼了,大家可以自己去看.
我們創建三個類分別繼承上述三個接口
此 User 類不是我們的數據庫里的用戶類,是用來安全服務的.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
/** * Created by Yuicon on 2017/5/14. */ public class User implements UserDetails { private final String id; //帳號,這里是我數據庫里的字段 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; } //雖然我數據庫里的字段是 `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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/** * 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 { // 這里是數據庫里的用戶類 User user = userRepository.findByAccount(account); if (user == null ) { throw new UsernameNotFoundException(String.format( "沒有該用戶 '%s'." , account)); } else { //這里返回上面繼承了 UserDetails 接口的用戶類,為了簡單我們寫個工廠類 return UserFactory.create(user); } } } |
UserDetails 工廠類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
/** * 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())) ); } //將與用戶類一對多的角色類的名稱集合轉換為 GrantedAuthority 集合 private static List<GrantedAuthority> mapToGrantedAuthorities(List<String> authorities) { return authorities.stream() .map(SimpleGrantedAuthority:: new ) .collect(Collectors.toList()); } } |
重點, 繼承 WebSecurityConfigurerAdapter 類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
/** * Created by Yuicon on 2017/5/14. */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity (prePostEnabled = true ) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // Spring會自動尋找實現接口的類注入,會找到我們的 UserDetailsServiceImpl 類 @Autowired private UserDetailsService userDetailsService; @Autowired public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder // 設置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() // 允許對于網站靜態資源的無授權訪問 .antMatchers( HttpMethod.GET, "/" , "/*.html" , "/favicon.ico" , "/**/*.html" , "/**/*.css" , "/**/*.js" , "/webjars/**" , "/swagger-resources/**" , "/*/api-docs" ).permitAll() // 對于獲取token的rest api要允許匿名訪問 .antMatchers( "/auth/**" ).permitAll() // 除上面外的所有請求全部需要鑒權認證 .anyRequest().authenticated(); // 禁用緩存 httpSecurity.headers().cacheControl(); } } |
- 控制權限到 controller
使用 @PreAuthorize("hasRole('ADMIN')") 注解就可以了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/** * 在 @PreAuthorize 中我們可以利用內建的 SPEL 表達式:比如 'hasRole()' 來決定哪些用戶有權訪問。 * 需注意的一點是 hasRole 表達式認為每個角色名字前都有一個前綴 'ROLE_'。所以這里的 'ADMIN' 其實在 * 數據庫中存儲的是 'ROLE_ADMIN' 。這個 @PreAuthorize 可以修飾Controller也可修飾Controller中的方法。 **/ @RestController @RequestMapping ( "/users" ) @PreAuthorize ( "hasRole('USER')" ) //有ROLE_USER權限的用戶可以訪問 public class UserController { @Autowired private UserRepository repository; @PreAuthorize ( "hasRole('ADMIN')" ) //有ROLE_ADMIN權限的用戶可以訪問 @RequestMapping (method = RequestMethod.GET) public List<User> getUsers() { return repository.findAll(); } } |
- 結語
Spring Boot中 Spring Security 的入門非常簡單,很快我們就能有一個滿足大部分需求的權限系統了.而配合 Spring Security 的好搭檔就是 JWT 了,兩者的集成文章網絡上也很多,大家可以自行集成.因為篇幅原因有不少代碼省略了,需要的可以參考項目代碼
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000010637751