国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

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

服務(wù)器之家 - 編程語言 - Java教程 - Spring Boot中使用 Spring Security 構(gòu)建權(quán)限系統(tǒng)的示例代碼

Spring Boot中使用 Spring Security 構(gòu)建權(quán)限系統(tǒng)的示例代碼

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

本篇文章主要介紹了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文件中就行了

?
1
2
3
4
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

- 配置 Spring Security

簡單的使用 Spring Security 只要配置三個類就完成了,分別是:

UserDetails

這個接口中規(guī)定了用戶的幾個必須要有的方法

?
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

這個內(nèi)容很多,就不貼代碼了,大家可以自己去看.

我們創(chuàng)建三個類分別繼承上述三個接口

此 User 類不是我們的數(shù)據(jù)庫里的用戶類,是用來安全服務(wù)的.

?
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;
 //帳號,這里是我數(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

?
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 {
  // 這里是數(shù)據(jù)庫里的用戶類
  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()))
  );
 }
 
 //將與用戶類一對多的角色類的名稱集合轉(zhuǎn)換為 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會自動尋找實現(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')") 注解就可以了

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * 在 @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í)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:https://segmentfault.com/a/1190000010637751

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲二区视频 | www.xxx在线观看| 中文字幕一区在线观看视频 | 亚洲精品一区二区三区在线播放 | 久久久综合网 | 久久久免费电影 | 福利网在线 | 精品欧美乱码久久久久久1区2区 | 亚洲免费a | 黄视频免费观看 | 免费又黄又爽又色的视频 | 人人99| 日韩精品视频在线 | 一级一片在线播放在线观看 | 狠狠干美女 | 国产精品香蕉 | 山岸逢花在线观看 | 最新免费av网站 | 精品美女在线观看视频在线观看 | 亚洲 综合 清纯 丝袜 自拍 | 无码日韩精品一区二区免费 | 91在线视频观看 | 亚洲免费人成在线视频观看 | 成人影院在线观看 | 99草在线视频 | 日韩在线视频中文字幕 | 一区二区视频 | 久久久久无码国产精品一区 | 中文字幕第18页 | 亚洲视频区 | 午夜精品久久久久久久久久久久久 | 久久久99国产精品免费 | 久久99深爱久久99精品 | 亚洲成人免费在线 | 亚洲欧美视频 | 91精品国产一区二区 | 精品综合久久 | 九九亚洲精品 | 国产美女一区 | av免费在线观看网站 | 粉嫩欧美一区二区三区高清影视 |