1. 程式人生 > 其它 >Spring Security Oauth2 整合單點登入簡易demo

Spring Security Oauth2 整合單點登入簡易demo

Spring Security Oauth2 整合單點登入(SSO)

建立客戶端

新增依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.2.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.yjxxt</groupId>
   <artifactId>oauth2client01demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>oauth2client01demo</name>
   <description>Demo project for Spring Boot</description>

   <properties>
      <java.version>1.8</java.version>
      <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-oauth2</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-security</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>io.jsonwebtoken</groupId>
         <artifactId>jjwt</artifactId>
         <version>0.9.0</version>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

修改配置檔案

application.properties

server.port=8081
#防止Cookie衝突,衝突會導致登入驗證不通過
server.servlet.session.cookie.name=OAUTH2-CLIENT-SESSIONID01
#授權伺服器地址
oauth2-server-url: http://localhost:8080
#與授權伺服器對應的配置
security.oauth2.client.client-id=admin
security.oauth2.client.client-secret=112233
security.oauth2.client.user-authorization-uri=${oauth2-server-url}/oauth/authorize
security.oauth2.client.access-token-uri=${oauth2-server-url}/oauth/token
security.oauth2.resource.jwt.key-uri=${oauth2-server-url}/oauth/token_key

在啟動類上新增@EnableOAuth2Sso註解來啟用單點登入功能

package com.yjxxt.oauth2client01demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;

@SpringBootApplication
@EnableOAuth2Sso
public class Oauth2client01demoApplication {

   public static void main(String[] args) {
      SpringApplication.run(Oauth2client01demoApplication.class, args);
   }

}

新增介面用於獲取當前登入使用者資訊

package com.yjxxt.oauth2client01demo.controller;

import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication;
    }

}

修改認證伺服器配置

修改授權伺服器中的AuthorizationServerConfig類,將繫結的跳轉路徑為

http://localhost:8081/login,並新增獲取祕鑰時的身份認證

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            //配置client_id
            .withClient("admin")
            //配置client-secret
            .secret(passwordEncoder.encode("112233"))
            //配置訪問token的有效期
            .accessTokenValiditySeconds(3600)
            //配置重新整理token的有效期
            .refreshTokenValiditySeconds(864000)
            //配置redirect_uri,用於授權成功後跳轉
            // .redirectUris("http://www.baidu.com")
            //單點登入時配置
            .redirectUris("http://localhost:8081/login")
            //配置申請的許可權範圍
            .scopes("all")
            //自動授權配置
            .autoApprove(true) 
            //配置grant_type,表示授權型別
            .authorizedGrantTypes("authorization_code","password","refresh_token");
}

@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
    // 獲取金鑰需要身份認證,使用單點登入時必須配置
    security.tokenKeyAccess("isAuthenticated()");
}  

測試

啟動授權服務和客戶端服務;

訪問客戶端需要授權的介面http://localhost:8081/user/getCurrentUser

會跳轉到授權服務的登入介面;

授權後會跳轉到原來需要許可權的介面地址,展示登入使用者資訊;