一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Spring Boot中使用 Spring Security 構建權限系統的示例代碼

Spring Boot中使用 Spring Security 構建權限系統的示例代碼

2020-12-15 14:54Yuicon Java教程

本篇文章主要介紹了Spring Boot中使用 Spring Security 構建權限系統的示例代碼,具有一定的參考價值,有興趣的可以了解一下

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲黄色图 | 韩国最新理论片奇忧影院 | 人人澡人| 婷婷婷色 | 欧美同志gaypronvideos | 奇米影视久久 | 好大好猛好爽好深视频免费 | 欧美草逼网站 | 99久久久久久久 | 2020年最新国产精品视频免费 | les女同h高h喷水 | 乌克兰成人性色生活片 | 女人扒开下面让男人桶爽视频 | 亚洲久操 | 色偷偷亚洲综合网亚洲 | 激情乱文 | 香蕉视频在线观看网站 | 日本在线亚州精品视频在线 | av毛片免费看 | 国产精品久久亚洲一区二区 | 4s4s4s4s色大众影视 | 貂蝉沦为姓奴小说 | 青青草在观免费 | 香蕉大久久 | 寡妇快点好大好爽视频 | 九九99九九精彩网站 | 国产一区二区不卡视频 | 深夜激情网 | 美女的让男人桶爽30分钟的 | 日本男男gaygays | 色天使亚洲综合在线观看 | 亚洲高清中文字幕精品不卡 | 天天做日日做天天添天天欢公交车 | 日韩中文字幕视频在线观看 | 三极片在线观看 | 天堂资源wwww在线看 | 国产美女在线一区二区三区 | 息与子中文字幕完整在线 | 深夜福利一区 | 日本动漫xxxxxx | 女教师波多野结衣高清在线 |