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

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

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

服務器之家 - 編程語言 - Java教程 - Spring Security 單點登錄簡單示例詳解

Spring Security 單點登錄簡單示例詳解

2021-07-17 12:36WeYunx Java教程

這篇文章主要介紹了Spring Security 單點登錄簡單示例詳解,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

overview

最近在弄單點登錄,踩了不少坑,所以記錄一下,做了個簡單的例子。

目標:認證服務器認證后獲取 token,客戶端訪問資源時帶上 token 進行安全驗證。

可以直接看源碼

關鍵依賴

?
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
<parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>2.1.2.release</version>
    <relativepath/>
</parent>
 
<dependencies>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-security</artifactid>
    </dependency>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
 
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-test</artifactid>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupid>org.springframework.security</groupid>
      <artifactid>spring-security-test</artifactid>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupid>org.springframework.security.oauth.boot</groupid>
      <artifactid>spring-security-oauth2-autoconfigure</artifactid>
      <version>2.1.2.release</version>
    </dependency>
</dependencies>

認證服務器

認證服務器的關鍵代碼有如下幾個文件:

Spring Security 單點登錄簡單示例詳解

authserverapplication:

?
1
2
3
4
5
6
7
8
@springbootapplication
@enableresourceserver
public class authserverapplication {
  public static void main(string[] args) {
    springapplication.run(authserverapplication.class, args);
  }
 
}

authorizationserverconfiguration 認證配置:

?
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
@configuration
@enableauthorizationserver
class authorizationserverconfiguration extends authorizationserverconfigureradapter {
  @autowired
  authenticationmanager authenticationmanager;
 
  @autowired
  tokenstore tokenstore;
 
  @autowired
  bcryptpasswordencoder encoder;
 
  @override
  public void configure(clientdetailsserviceconfigurer clients) throws exception {
    //配置客戶端
    clients
        .inmemory()
        .withclient("client")
        .secret(encoder.encode("123456")).resourceids("hi")
        .authorizedgranttypes("password","refresh_token")
        .scopes("read");
  }
 
  @override
  public void configure(authorizationserverendpointsconfigurer endpoints) throws exception {
    endpoints
        .tokenstore(tokenstore)
        .authenticationmanager(authenticationmanager);
  }
 
 
  @override
  public void configure(authorizationserversecurityconfigurer oauthserver) throws exception {
    //允許表單認證
    oauthserver
        .allowformauthenticationforclients()
        .checktokenaccess("permitall()")
        .tokenkeyaccess("permitall()");
  }
}

代碼中配置了一個 client,id 是 client,密碼 123456authorizedgranttypespasswordrefresh_token 兩種方式。

securityconfiguration 安全配置:

?
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
@configuration
@enablewebsecurity
public class securityconfiguration extends websecurityconfigureradapter {
  @bean
  public tokenstore tokenstore() {
    return new inmemorytokenstore();
  }
 
  @bean
  public bcryptpasswordencoder encoder() {
    return new bcryptpasswordencoder();
  }
 
  @override
  protected void configure(authenticationmanagerbuilder auth) throws exception {
    auth.inmemoryauthentication()
        .passwordencoder(encoder())
        .withuser("user_1").password(encoder().encode("123456")).roles("user")
        .and()
        .withuser("user_2").password(encoder().encode("123456")).roles("admin");
  }
 
  @override
  protected void configure(httpsecurity http) throws exception {
    // @formatter:off
    http.csrf().disable()
        .requestmatchers()
        .antmatchers("/oauth/authorize")
        .and()
        .authorizerequests()
        .anyrequest().authenticated()
        .and()
        .formlogin().permitall();
    // @formatter:on
  }
 
  @override
  @bean
  public authenticationmanager authenticationmanagerbean() throws exception {
    return super.authenticationmanagerbean();
  }
}

上面在內存中創建了兩個用戶,角色分別是 useradmin。后續可考慮在數據庫或者 redis 中存儲相關信息。

authuser 配置獲取用戶信息的 controller:

?
1
2
3
4
5
6
7
8
@restcontroller
public class authuser {
    @getmapping("/oauth/user")
    public principal user(principal principal) {
      return principal;
    }
 
}

application.yml 配置,主要就是配置個端口號:

?
1
2
3
4
5
6
7
8
---
spring:
 profiles:
  active: dev
 application:
  name: auth-server
server:
 port: 8101

客戶端配置

客戶端的配置比較簡單,主要代碼結構如下:

Spring Security 單點登錄簡單示例詳解

application.yml 配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
---
spring:
 profiles:
  active: dev
 application:
  name: client
 
server:
 port: 8102
security:
 oauth2:
  client:
   client-id: client
   client-secret: 123456
   access-token-uri: http://localhost:8101/oauth/token
   user-authorization-uri: http://localhost:8101/oauth/authorize
   scope: read
   use-current-uri: false
  resource:
   user-info-uri: http://localhost:8101/oauth/user

這里主要是配置了認證服務器的相關地址以及客戶端的 id 和 密碼。user-info-uri 配置的就是服務器端獲取用戶信息的接口。

hellocontroller 訪問的資源,配置了 admin 的角色才可以訪問:

?
1
2
3
4
5
6
7
8
@restcontroller
public class hellocontroller {
  @requestmapping("/hi")
  @preauthorize("hasrole('admin')")
  public responseentity<string> hi() {
    return responseentity.ok().body("auth success!");
  }
}

websecurityconfiguration 相關安全配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@configuration
@enableoauth2sso
@enableglobalmethodsecurity(prepostenabled = true)
class websecurityconfiguration extends websecurityconfigureradapter {
 
  @override
  public void configure(httpsecurity http) throws exception {
 
    http
        .csrf().disable()
        // 基于token,所以不需要session
       .sessionmanagement().sessioncreationpolicy(sessioncreationpolicy.stateless)
        .and()
        .authorizerequests()
        .anyrequest().authenticated();
  }
 
 
}

其中 @enableglobalmethodsecurity(prepostenabled = true) 開啟后,spring security 的 @preauthorize,@postauthorize 注解才可以使用。

@enableoauth2sso 配置了單點登錄。

clientapplication

?
1
2
3
4
5
6
7
8
@springbootapplication
@enableresourceserver
public class clientapplication {
  public static void main(string[] args) {
    springapplication.run(clientapplication.class, args);
  }
 
}

驗證

啟動項目后,我們使用 postman 來進行驗證。

首先是獲取 token:

Spring Security 單點登錄簡單示例詳解

選擇 post 提交,地址為驗證服務器的地址,參數中輸入 username,password,grant_typescope ,其中 grant_type 需要輸入 password

然后在下面等 authorization 標簽頁中,選擇 basic auth,然后輸入 client 的 id 和 password。

?
1
2
3
4
5
6
7
{
  "access_token": "02f501a9-c482-46d4-a455-bf79a0e0e728",
  "token_type": "bearer",
  "refresh_token": "0e62dddc-4f51-4cb5-81c3-5383fddbb81b",
  "expires_in": 41741,
  "scope": "read"
}

此時就可以獲得 access_token 為: 02f501a9-c482-46d4-a455-bf79a0e0e728。需要注意的是這里是用 user_2 獲取的 token,即角色是 admin

然后我們再進行獲取資源的驗證:

Spring Security 單點登錄簡單示例詳解

使用 get 方法,參數中輸入 access_token,值輸入 02f501a9-c482-46d4-a455-bf79a0e0e728

點擊提交后即可獲取到結果。

如果我們不加上 token ,則會提示無權限。同樣如果我們換上 user_1 獲取的 token,因 user_1 的角色是 user,此資源需要 admin 權限,則此處還是會獲取失敗。

簡單的例子就到這,后續有時間再加上其它功能吧,謝謝~

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 午夜国产精品福利在线观看 | 国产区一二三四区2021 | 黄色cc| 暖暖在线精品日本中文 | 国产精品久久久天天影视香蕉 | 爽好舒服把腿张小说 | 亚洲午夜久久久 | 亚洲视频在线观看地址 | 亚洲国产高清视频 | 亚洲国产高清视频 | 亚洲国产精品婷婷久久久久 | 高h辣h双处全是肉军婚 | 奇米激情 | 欧美视频一区二区专区 | 18美女光胸光屁屁洗澡 | 黑人异族日本人hd | www四虎影视| 日韩亚洲国产激情在线观看 | 青青青在线视频 | 全程粗语对白视频videos | 国产成+人+综合+欧美 亚洲 | 美女禁区视频免费观看精选 | 奇米影视久久 | 3d肉浦团在线观看 | 亚洲精品国精品久久99热 | 91精品综合久久久久久五月天 | 日本一道本视频 | 爸爸的宝贝小说全文在线阅读 | boobsmilking流奶水野战 | 猫影视tv接口 | 春光乍泄在线 | 秋霞717理论片在线观看 | 欧美极品摘花过程 | 国语视频高清在线观看 | 免费午夜影片在线观看影院 | 国产精品原创视频 | 无套内射在线观看THEPORN | 亚洲成人看片 | 日韩成a人片在线观看日本 日韩不卡一区二区 | 思思99热久久精品在2019线 | 欧美成人在线影院 |