使用SpringSecurity 實現 OAuth2 資源服務器認證服務器分離( 注冊碼模式)


    要解決的問題:不暴露客戶密碼的情況下授權三方服務訪問客戶資源

    角色:資源擁有者,客戶端應用(三方服務),授權服務器,資源服務器

    模式:授權碼模式:需要客戶授權得到授權碼后再次通過三方服務的密碼取得token,雙重校驗,最安全,最復雜

               簡易模式:無需授權碼對用戶暴露返回的Token,不安全

               密碼模式:客戶端應用需要資源擁有者密碼。全鏈路可信情況下使用

               客戶端模式:無需資源擁有者密碼,只需要客戶端應用密碼進行校驗,服務器對服務器使用

       本試驗主要演示注冊碼模式,分為授權服務器和資源服務器倆個應用,后續會持續擴展為單個授權服務器和多個資源服務器。

試驗步驟

按照以下截圖創建授權服務器,授權服務器包結構如下

1 使用pom文件導入相應依賴,主要導入了以下依賴包

1)SpringBoot的security和web,

2)SpringSecurity的OAuth2

pom文件如下

 

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.spring2go</groupId>
    <artifactId>authcode-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>authcode-server</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
</parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <!-- for OAuth 2.0 -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</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>
    </dependencies>

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


</project>

2 修改application.properties設置用戶登錄密碼

 

# Spring Security Setting
security.user.name=bobo
security.user.password=xyz

3 制作SpringBoot的啟動文件

 

package com.test.authcodeserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AuthCodeServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(AuthCodeServerApplication.class, args);
    }
}
4 設置授權服務代碼

 

 
             
package com.test.authcodeserver.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

@Configuration
@EnableAuthorizationServer
public class AuthCodeServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        //JdbcClientDetailsService可以動態管理數據庫中客戶端數據
        //http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo
clients.inMemory()
                .withClient("testclientid")//clientId:(必須的)用來標識客戶的Id。
.secret("1234")//secret:(需要值得信任的客戶端)客戶端安全碼,如果有的話。
.redirectUris("http://localhost:9001/authCodeCallback")//客戶端應用負責獲取授權碼的endpoint
.authorizedGrantTypes("authorization_code")// 授權碼模式
.scopes("read_userinfo", "read_contacts");//scope:用來限制客戶端的訪問范圍,如果為空(默認)的話,那么客戶端擁有全部的訪問范圍。
}

}

5 啟動SpringBoot服務

6 客戶端服務訪問授權服務器,銅鼓訪問如下url取得授權碼

http://localhost:8080/oauth/authorize?client_id=testclientid&redirect_uri=http://localhost:9001/authCodeCallback&response_type=code&scope=read_userinfo

訪問完成后會redirect回客戶端服務器並將授權碼作為參數傳回,其中localhost:9001即為客戶端應用

7 客戶端使用返回的授權碼獲取訪問令牌

發送請求參數如下

url:http://localhost:8080/oauth/token

code=ifz2BV&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A9001%2FauthCodeCallback&scope=read_userinfo

得到的令牌數據

 

{
access_token: "554338cd-cab0-4ba0-b5bf-3ebd55db3196"
token_type: "bearer"
expires_in: 43199
scope: "read_userinfo"

}

以上授權服務器就簡單完成了,下面將制作資源服務器

 

--------------------------------------------------------------------------------------------------

 

資源服務器

0 資源服務器的包結構

1 資源服務器配置,使用RemoteTokenServices調取認證服務器的認證方法來對Token進行認證

 

package com.test.resourceserver.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//資源服務配置
@Configuration
@EnableResourceServer
public class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {

    @Primary
    @Bean
    public RemoteTokenServices tokenServices() {
        final RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        tokenService.setClientId("testclientid");
        tokenService.setClientSecret("1234");
        return tokenService;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

//        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
//                .and()
//                .authorizeRequests()
//                .anyRequest()
//                .authenticated()
//                .and()
//                .requestMatchers()
//                .antMatchers("/api/**");
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .authorizeRequests().anyRequest().permitAll();
    }
}

2 提供對外的API接口

 

package com.test.resourceserver.api;

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserController {

   // 資源API
@RequestMapping("/api/userinfo")
    public ResponseEntity<UserInfo> getUserInfo() {

        String  user  = (String) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        String email = user+ "@test.com";
        UserInfo userInfo = new UserInfo();
        userInfo.setName(user);
        userInfo.setEmail(email);
        return ResponseEntity.ok(userInfo);
    }

}
調用getUserInfo

http://localhost:8004/api/userinfo 

authorization: Bearer 638aa01c-4ccd-4873-ab86-d46f22aea091

調用后返回資源服務器的結果

至此一個資源服務器和認證服務器分離的資源調用就結束了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM