最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Spring Security 單點(diǎn)登錄簡(jiǎn)單示例詳解

 更新時(shí)間:2019年02月28日 10:30:24   作者:WeYunx  
這篇文章主要介紹了Spring Security 單點(diǎn)登錄簡(jiǎn)單示例詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

Overview

最近在弄單點(diǎn)登錄,踩了不少坑,所以記錄一下,做了個(gè)簡(jiǎn)單的例子。

目標(biāo):認(rèn)證服務(wù)器認(rèn)證后獲取 token,客戶端訪問(wèn)資源時(shí)帶上 token 進(jìn)行安全驗(yàn)證。

可以直接看源碼。

關(guān)鍵依賴

<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>

認(rèn)證服務(wù)器

認(rèn)證服務(wù)器的關(guān)鍵代碼有如下幾個(gè)文件:

AuthServerApplication:

@SpringBootApplication
@EnableResourceServer
public class AuthServerApplication {
  public static void main(String[] args) {
    SpringApplication.run(AuthServerApplication.class, args);
  }

}

AuthorizationServerConfiguration 認(rèn)證配置:

@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 {
    //允許表單認(rèn)證
    oauthServer
        .allowFormAuthenticationForClients()
        .checkTokenAccess("permitAll()")
        .tokenKeyAccess("permitAll()");
  }
}

代碼中配置了一個(gè) client,id 是 client,密碼 123456。 authorizedGrantTypespasswordrefresh_token 兩種方式。

SecurityConfiguration 安全配置:

@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();
  }
}

上面在內(nèi)存中創(chuàng)建了兩個(gè)用戶,角色分別是 USERADMIN。后續(xù)可考慮在數(shù)據(jù)庫(kù)或者 Redis 中存儲(chǔ)相關(guān)信息。

AuthUser 配置獲取用戶信息的 Controller:

@RestController
public class AuthUser {
    @GetMapping("/oauth/user")
    public Principal user(Principal principal) {
      return principal;
    }

}

application.yml 配置,主要就是配置個(gè)端口號(hào):

---
spring:
 profiles:
  active: dev
 application:
  name: auth-server
server:
 port: 8101

客戶端配置

客戶端的配置比較簡(jiǎn)單,主要代碼結(jié)構(gòu)如下:

application.yml 配置:

---
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

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

HelloController 訪問(wèn)的資源,配置了 ADMIN 的角色才可以訪問(wèn):

@RestController
public class HelloController {
  @RequestMapping("/hi")
  @PreAuthorize("hasRole('ADMIN')")
  public ResponseEntity<String> hi() {
    return ResponseEntity.ok().body("auth success!");
  }
}

WebSecurityConfiguration 相關(guān)安全配置:

@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 配置了單點(diǎn)登錄。

ClientApplication

@SpringBootApplication
@EnableResourceServer
public class ClientApplication {
  public static void main(String[] args) {
    SpringApplication.run(ClientApplication.class, args);
  }

}

驗(yàn)證

啟動(dòng)項(xiàng)目后,我們使用 postman 來(lái)進(jìn)行驗(yàn)證。

首先是獲取 token:

選擇 POST 提交,地址為驗(yàn)證服務(wù)器的地址,參數(shù)中輸入 username,password,grant_typescope ,其中 grant_type 需要輸入 password。

然后在下面等 Authorization 標(biāo)簽頁(yè)中,選擇 Basic Auth,然后輸入 client 的 id 和 password。

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

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

然后我們?cè)龠M(jìn)行獲取資源的驗(yàn)證:

使用 GET 方法,參數(shù)中輸入 access_token,值輸入 02f501a9-c482-46d4-a455-bf79a0e0e728

點(diǎn)擊提交后即可獲取到結(jié)果。

如果我們不加上 token ,則會(huì)提示無(wú)權(quán)限。同樣如果我們換上 user_1 獲取的 token,因 user_1 的角色是 USER,此資源需要 ADMIN 權(quán)限,則此處還是會(huì)獲取失敗。

簡(jiǎn)單的例子就到這,后續(xù)有時(shí)間再加上其它功能吧,謝謝~

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java上傳文件到服務(wù)器指定文件夾實(shí)現(xiàn)過(guò)程圖解

    Java上傳文件到服務(wù)器指定文件夾實(shí)現(xiàn)過(guò)程圖解

    這篇文章主要介紹了Java上傳文件到服務(wù)器指定文件夾實(shí)現(xiàn)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Java 遞歸查詢部門樹形結(jié)構(gòu)數(shù)據(jù)的實(shí)踐

    Java 遞歸查詢部門樹形結(jié)構(gòu)數(shù)據(jù)的實(shí)踐

    本文主要介紹了Java 遞歸查詢部門樹形結(jié)構(gòu)數(shù)據(jù)的實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Java中遞歸構(gòu)建樹形結(jié)構(gòu)的算法解讀

    Java中遞歸構(gòu)建樹形結(jié)構(gòu)的算法解讀

    該文章介紹了如何使用Java遞歸算法構(gòu)建樹形結(jié)構(gòu),通過(guò)定義樹節(jié)點(diǎn)類,遍歷扁平數(shù)據(jù)列表,將節(jié)點(diǎn)加入對(duì)應(yīng)父節(jié)點(diǎn)的子節(jié)點(diǎn)列表中,實(shí)現(xiàn)從扁平數(shù)據(jù)到樹形結(jié)構(gòu)的轉(zhuǎn)換
    2025-03-03
  • java 實(shí)現(xiàn)將Object類型轉(zhuǎn)換為int類型

    java 實(shí)現(xiàn)將Object類型轉(zhuǎn)換為int類型

    這篇文章主要介紹了java 實(shí)現(xiàn)將Object類型轉(zhuǎn)換為int類型的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • SpringBoot部署到外部Tomcat無(wú)法注冊(cè)到Nacos服務(wù)端的解決思路

    SpringBoot部署到外部Tomcat無(wú)法注冊(cè)到Nacos服務(wù)端的解決思路

    這篇文章主要介紹了SpringBoot部署到外部Tomcat無(wú)法注冊(cè)到Nacos服務(wù)端,本文給大家分享完美解決思路,結(jié)合實(shí)例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下
    2023-03-03
  • Java this關(guān)鍵字的使用詳解

    Java this關(guān)鍵字的使用詳解

    this 關(guān)鍵字是 Java 常用的關(guān)鍵字,可用于任何實(shí)例方法內(nèi)指向當(dāng)前對(duì)象,也可指向?qū)ζ湔{(diào)用當(dāng)前方法的對(duì)象,或者在需要當(dāng)前類型對(duì)象引用時(shí)使用
    2021-11-11
  • java中使用sax解析xml的解決方法

    java中使用sax解析xml的解決方法

    本篇文章介紹了,在java中使用sax解析xml的解決方法。需要的朋友參考下
    2013-05-05
  • Java中斷異常的正確處理方法

    Java中斷異常的正確處理方法

    這篇文章主要給大家介紹了關(guān)于Java中斷異常的正確處理方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • IDEA2023 Maven3.9.1+Tomcat10.1.8配置并搭建Servlet5.0的框架實(shí)現(xiàn)

    IDEA2023 Maven3.9.1+Tomcat10.1.8配置并搭建Servlet5.0的框架實(shí)現(xiàn)

    本文主要介紹了IDEA2023 Maven3.9.1+Tomcat10.1.8配置并搭建Servlet5.0的框架實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • 在Java中如何避免創(chuàng)建不必要的對(duì)象

    在Java中如何避免創(chuàng)建不必要的對(duì)象

    作為Java開發(fā)者,我們每天創(chuàng)建很多對(duì)象,但如何才能避免創(chuàng)建不必要的對(duì)象呢?這需要我們好好學(xué)習(xí),這篇文章主要給大家介紹了關(guān)于在Java中如何避免創(chuàng)建不必要對(duì)象的相關(guān)資料,需要的朋友可以參考下
    2021-10-10

最新評(píng)論

荥阳市| 杭锦旗| 赫章县| 汶川县| 肇州县| 三台县| 登封市| 娄底市| 老河口市| 齐齐哈尔市| 卓资县| 嘉荫县| 三江| 海原县| 门源| 梁河县| 延长县| 武夷山市| 桂东县| 武汉市| 宁国市| 柳河县| 英德市| 恭城| 巴彦淖尔市| 分宜县| 白河县| 基隆市| 大宁县| 屯门区| 西宁市| 农安县| 上饶县| 交口县| 邵武市| 甘孜县| 温宿县| 祁东县| 南部县| 东山县| 娱乐|