欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

Overview

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

目標(biāo):認(rèn)證服務(wù)器認(rèn)證后獲取 token,客戶端訪問資源時(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,密碼 123456authorizedGrantTypespasswordrefresh_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ù)庫或者 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é)構(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 訪問的資源,配置了 ADMIN 的角色才可以訪問:

@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 來進(jìn)行驗(yàn)證。

首先是獲取 token:

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

然后在下面等 Authorization 標(biāo)簽頁中,選擇 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ì)提示無權(quán)限。同樣如果我們換上 user_1 獲取的 token,因 user_1 的角色是 USER,此資源需要 ADMIN 權(quán)限,則此處還是會(huì)獲取失敗。

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

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

相關(guān)文章

  • Struts2學(xué)習(xí)筆記(4)-通配符的使用

    Struts2學(xué)習(xí)筆記(4)-通配符的使用

    本文主要介紹Struts2中通配符的使用,簡單實(shí)用,希望能給大家做一個(gè)參考。
    2016-06-06
  • java中的匿名內(nèi)部類總結(jié)

    java中的匿名內(nèi)部類總結(jié)

    這篇文章主要介紹了 java中的匿名內(nèi)部類總結(jié)的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下
    2017-09-09
  • 如何解決Gradle、Maven項(xiàng)目build后沒有mybatis的mapper.xml文件的問題

    如何解決Gradle、Maven項(xiàng)目build后沒有mybatis的mapper.xml文件的問題

    這篇文章主要介紹了如何解決Gradle、Maven項(xiàng)目build后沒有mybatis的mapper.xml文件的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • java解析XML Node與Element的區(qū)別(推薦)

    java解析XML Node與Element的區(qū)別(推薦)

    下面小編就為大家分享一篇java解析XML Node與Element的區(qū)別,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-01-01
  • MyBatis標(biāo)簽之Select?resultType和resultMap詳解

    MyBatis標(biāo)簽之Select?resultType和resultMap詳解

    這篇文章主要介紹了MyBatis標(biāo)簽之Select?resultType和resultMap,在MyBatis中有一個(gè)ResultMap標(biāo)簽,它是為了映射select標(biāo)簽查詢出來的結(jié)果集,下面使用一個(gè)簡單的例子,來介紹 resultMap 的使用方法,需要的朋友可以參考下
    2022-09-09
  • spring中AOP 注解開發(fā)示例詳解

    spring中AOP 注解開發(fā)示例詳解

    這篇文章主要介紹了spring中AOP注解開發(fā)的相關(guān)資料,文中介紹的很詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-02-02
  • 淺析java class 文件

    淺析java class 文件

    以下是對(duì)java中的class文件進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下
    2013-08-08
  • Mybatis-Plus批量插入用法詳解

    Mybatis-Plus批量插入用法詳解

    mybatis-plus的IService接口默認(rèn)提供saveBatch批量插入,也是唯一一個(gè)默認(rèn)批量插入,在數(shù)據(jù)量不是很大的情況下可以直接使用,但這種是一條一條執(zhí)行的效率上會(huì)有一定的瓶頸,今天我們就來研究研究mybatis-plus中的批量插入
    2023-02-02
  • Java servlet后端開發(fā)超詳細(xì)教程

    Java servlet后端開發(fā)超詳細(xì)教程

    Servlet指在服務(wù)器端執(zhí)行的一段Java代碼,可以接收用戶的請(qǐng)求和返回給用戶響應(yīng)結(jié)果,下面這篇文章主要給大家介紹了關(guān)于Java.servlet生命周期的相關(guān)資料,需要的朋友可以參考下
    2023-02-02
  • 詳解Java中wait和sleep的區(qū)別

    詳解Java中wait和sleep的區(qū)別

    這篇文章主要介紹了Java中wait和sleep的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03

最新評(píng)論