(十二).NET6 + React :升級!升級!還是***升級!!!+ IdentityServer4實戰

冬先生發表於2022-05-30

一、前言

此篇內容較多,我是一步一個腳印(坑),以至於寫了好久,主要是這幾部分:後臺升級 .NET6  VS2022、前臺升級Ant Design Pro V5 、前後臺聯調 IdentityServer4 實戰,以及各部分在Linux環境下部署等等。

二、後臺升級.NET6

WebApi和類庫都升級到.NET6,依賴包都升級到6.0以上最新,好像沒什麼感知,略感easy。(附一張寫完後最新的專案結構圖)

三、IdentityServer4實戰

1、使用者管理

還好上篇持久化已經做了90%的工作,不過是在Demo裡面,現在搬到主專案裡來,使用者部分、客戶端配置部分根據實際情況稍加改動。

這裡需要解釋一下,使用者、角色管理這塊可以用Identity進行管理,也可以在業務系統裡管理,id4只做登入鑑權,這裡只是舉個例子,ApplicationUser繼承IdentityUser,定義欄位UserInfoId關聯UserInfo表,具體需求根據專案實際情況來設計。

2、配置修改

簡化、授權碼是給React前端用的,混合模式給 Mvc 客戶端用的(一個空.NET6 Mvc專案,也搬到主專案了,具體的可以看程式碼)

3、資料遷移

依次在程式包管理器控制檯輸入遷移命令,其他表結構資料相同就不貼了,上篇持久化過程都有詳細步驟和結果。

四、前臺升級 Ant Design Pro V5

前臺升級 Ant Design Pro V5,之前用的是V5預覽版,已經是一年前的事情了。。。我反思。。。?

1、安裝元件 oidc-client

cnpm install oidc-client --save,新建認證服務類 auth.ts ,跟後臺 IdentityServer4 認證服務配合使用。

import { Log, User, UserManager } from 'oidc-client';

export class AuthService {
    public userManager: UserManager;
    constructor() {
        // const clientRoot = 'http://localhost:8000/';
        const clientRoot = 'https://homejok.wintersir.com/';        
        const settings = {
            authority: 'https://login.wintersir.com',
            //client_id: 'antdview',
            //response_type: 'id_token token',
            client_id: 'antdviewcode',
            client_secret: 'antdviewcode',
            response_type: 'code',
            redirect_uri: `${clientRoot}callback`,
            post_logout_redirect_uri: `${clientRoot}`,
            // silent_redirect_uri: `${clientRoot}silent-renew.html`,
            scope: 'openid profile HomeJokScope'
        };
        this.userManager = new UserManager(settings);

        Log.logger = console;
        Log.level = Log.WARN;
    }

    public login(): Promise<void> {
        //記錄跳轉登入前的路由
        return this.userManager.signinRedirect({ state: window.location.href });
    }

    public signinRedirectCallback(): Promise<User> {
        return this.userManager.signinRedirectCallback();
    }

    public logout(): Promise<void> {
        return this.userManager.signoutRedirect();
    }

    public getUser(): Promise<User | null> {
        return this.userManager.getUser();
    }

    public renewToken(): Promise<User> {
        return this.userManager.signinSilent();
    }
}

2、登入認證設定

修改app.tsx,初始化認證服務類,判斷登入狀態,設定請求後臺攔截器,新增 headers 和 token

import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@/components/PageLoading';
import type { RequestConfig, RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import RightContent from '@/components/RightContent';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import { AuthService } from '@/utils/auth';

const isDev = process.env.NODE_ENV === 'development';

const authService: AuthService = new AuthService();

/** 獲取使用者資訊比較慢的時候會展示一個 loading */
export const initialStateConfig = {
    loading: <PageLoading />
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
    settings?: Partial<LayoutSettings>;
}> {
    const init = localStorage.getItem('init');
    const token = localStorage.getItem('token');
    const user = localStorage.getItem('user');
    if (!token && !init && !user) {
        localStorage.setItem('init', 'true');
        authService.login();
    }
    return {
        settings: {}
    };
}

// ProLayout 支援的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
    const token = localStorage.getItem('token');
    const user = localStorage.getItem('user');
    return {
        rightContentRender: () => <RightContent />,
        disableContentMargin: false,
        waterMarkProps: {
            //content: initialState?.currentUser?.name,
        },
        // footerRender: () => <Footer />,
        onPageChange: () => {
            const { location } = history;
            if (!token && !user && location.pathname != "/callback") {
                authService.login();
            }
        },
        links: isDev
            ? [
                <Link to="/umi/plugin/openapi" target="_blank">
                    <LinkOutlined />
                    <span>OpenAPI 文件</span>
                </Link>,
                <Link to="/~docs">
                    <BookOutlined />
                    <span>業務元件文件</span>
                </Link>,
            ]
            : [],
        menuHeaderRender: undefined,
        // 自定義 403 頁面
        // unAccessible: <div>unAccessible</div>,
        ...initialState?.settings,
        //防止未登入閃屏選單問題
        pure: token ? false : true 
    }
};

const authHeaderInterceptor = (url: string, options: RequestOptionsInit) => {
    const token = localStorage.getItem('token');
    const authHeader = { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: 'Bearer ' + token };
    return {
        url: `${url}`,
        options: { ...options, interceptors: true, headers: authHeader },
    };
};
export const request: RequestConfig = {
    //timeout: 10000,
    // 新增自動新增AccessToken的請求前攔截器
    requestInterceptors: [authHeaderInterceptor],
};

3、登入回撥、獲取使用者、登出

(1)新增callback.tsx,這是登入成功的回撥地址,儲存登入狀態token、user等,跳轉頁面。

import { message, Result, Spin } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { AuthService } from '@/utils/auth';
import { useRequest } from 'umi';
import { login } from '@/services/accountService';

const authService: AuthService = new AuthService();

const callback: React.FC = () => {
    const [msg, setMsg] = useState('玩命登入中......');
    const authRedirect = useRef("/");
    const { run, loading } = useRequest(login, {
        manual: true,
        onSuccess: (result, params) => {
            if (result && result.responseData) {
                localStorage.setItem('user', JSON.stringify(result.responseData));
                window.location.href = authRedirect.current;
            } else {
                setMsg('登入失敗,即將跳轉重新登入......');
                setTimeout(() => {
                    localStorage.removeItem('init');
                    localStorage.removeItem('token');
                    window.location.href = authRedirect.current;
                }, 3000);
            }
        },
        onError: (error) => {
            message.error(error.message);
        }
    });
    useEffect(() => {
        authService.signinRedirectCallback().then(auth => {
            authRedirect.current = auth.state;
            localStorage.setItem('token', auth.access_token);
            run({ account: auth.profile.sub });
        })
    }, [])

    return (
        <>
            <Result status="success" title={<Spin spinning={loading} tip={msg}></Spin>} />
        </>
    )
};

export default callback;

(2)accountService.tsx Umi的useRequest、Request 配合使用

import { request } from 'umi';
export async function login(payload: { account: string }, options?: { [key: string]: any }) {
    return request('/api/Account/Login', {
        method: 'POST',
        params: payload,
        ...(options || {}),
    });
}

AvatarDropdown.tsx 登出核心方法

const onMenuClick = useCallback(
  (event: MenuInfo) => {
    const { key } = event;
    if (key === 'logout') {
      localStorage.removeItem('init');
      localStorage.removeItem('user');
      localStorage.removeItem('token');
      authService.logout();
      return;
    }
    history.push(`/account/${key}`);
  },
  [],
);

4、自定義其他配置

如:PageLoading 等待框元件、defaultSettings.ts 顏色、圖示等配置項、routes.ts 路由,詳細見程式碼。

五、Linux伺服器部署

1、.NET6 環境

坑1有CentOS7安裝.NET6的步驟,其他linux版本參考

2、服務資源分配

因為只有一臺伺服器,用nginx進行轉發:React前端埠80,IdentityServer4埠5000,WebApi資源埠8000,Mvc網站埠9000
啟動命令分兩步,舉個例子:

cd /指定目錄
nohup dotnet ./BKYL.WEB.API.dll &

3、nginx配置https

因為全部使用了https,所有域名、二級域名都搞了ssl證書,一一對應,通過 nginx 配置部署,貼上nginx.conf關鍵部分以供參考。

如何設定二級域名、申請ssl證書、nginx配置ssl證書,網上資料很多,不再贅述,有需要的可以私

server {
  listen       80;
  server_name  *.wintersir.com;
  
  rewrite ^(.*)$ https://$host$1;
  #charset koi8-r;
  error_page   500 502 503 504  /50x.html;
  location = /50x.html {
      root   html;
  }     
}
 
server {
  listen       443 ssl;
  server_name  www.wintersir.com wintersir.com;
  ssl_certificate      /app/nginx/conf/index/cert.pem;
  ssl_certificate_key  /app/nginx/conf/index/cert.key;
  ssl_session_cache    shared:SSL:1m;
  ssl_session_timeout  5m;
  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers  on;
  location / {
    root   /app/wintersir/index;
    index  index.html index.htm;
  }
}

server {
  listen       443 ssl;
  server_name  homejok.wintersir.com;
  ssl_certificate      /app/nginx/conf/view/cert.pem;
  ssl_certificate_key  /app/nginx/conf/view/cert.key;
  ssl_session_cache    shared:SSL:1m;
  ssl_session_timeout  5m;
  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers  on;
  location / {
  
    proxy_set_header X-Forearded-Proto $scheme;
    proxy_set_header Host $http_host;		
    proxy_set_header X-Real-IP $remote_addr;		
    
    add_header 'Access-Control-Allow-Origin' "$http_origin";		
    add_header 'Access-Control-Allow-Credentials' 'true';		
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';		
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,Content-Type';
  
    root   /app/wintersir/view;
    index  index.html index.htm;
  }
  
  location /api/ {
  
    proxy_set_header X-Forearded-Proto $scheme;
    proxy_set_header Host $http_host;		
    proxy_set_header X-Real-IP $remote_addr;		
    
    add_header 'Access-Control-Allow-Origin' "$http_origin";		
    add_header 'Access-Control-Allow-Credentials' 'true';		
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';		
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,Content-Type';
    proxy_pass https://www.wintersir.com:8000;
  }
}
 
server {
  listen       443 ssl;
  server_name  mvc.wintersir.com;
  ssl_certificate      /app/nginx/conf/mvc/cert.pem;
  ssl_certificate_key  /app/nginx/conf/mvc/cert.key;
  ssl_session_cache    shared:SSL:1m;
  ssl_session_timeout  5m;
  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers  on;
  location / {
    proxy_set_header X-Forearded-Proto $scheme;
    proxy_set_header Host $http_host;		
    proxy_set_header X-Real-IP $remote_addr;		
    add_header 'Access-Control-Allow-Origin' "$http_origin";		
    add_header 'Access-Control-Allow-Credentials' 'true';		
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';		
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,Content-Type';
    proxy_pass https://www.wintersir.com:9000/;
  }
}

server {
  isten       443 ssl;
  server_name  login.wintersir.com;
 
  ssl_certificate      /app/nginx/conf/login/cert.pem;
  ssl_certificate_key  /app/nginx/conf/login/cert.key;
 
  ssl_session_cache    shared:SSL:1m;
  ssl_session_timeout  5m;
 
  ssl_ciphers  HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers  on;
 
  location / {
  
    if ($request_method = 'OPTIONS') { 
       add_header 'Access-Control-Allow-Origin' "$http_origin";
       add_header 'Access-Control-Allow-Credentials' 'true';
       add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
       add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,Content-Type';
       return 200; 
    }
  
    proxy_set_header X-Forearded-Proto $scheme;
    proxy_set_header Host $http_host;		
    proxy_set_header X-Real-IP $remote_addr;		
    add_header 'Access-Control-Allow-Origin' "$http_origin";		
    add_header 'Access-Control-Allow-Credentials' 'true';		
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';		
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,Content-Type';
    proxy_pass https://www.wintersir.com:5000/;
  }
}

六、效果圖

1、React前端

2、Mvc網站測試

七、各種踩坑

1、CentOS8不支援 .NET6

當初阿里雲裝了CentOS8,現在想哭,邊哭邊裝CentOS7.9,把資料庫、nginx等環境又都裝一遍(前幾篇都有)?
CentOS7 安裝 .NET6 官方教程 ,分別執行以下命令,中間輸入了兩次y

sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm
sudo yum install dotnet-sdk-6.0

2、nginx傳輸資料過大、轉發跨域

簡單模式 token 等資訊帶在了回撥頁面url裡,nginx 502 無法跳轉,解決參考,nginx http 新增以下程式碼:

proxy_buffer_size   128k;
proxy_buffers   4 256k;
proxy_busy_buffers_size   256k;
large_client_header_buffers 4 16k;

處理proxy_pass轉發:

proxy_set_header X-Forearded-Proto $scheme;
proxy_set_header Host $http_host;		
proxy_set_header X-Real-IP $remote_addr;
add_header 'Access-Control-Allow-Origin' "$http_origin";		
add_header 'Access-Control-Allow-Credentials' 'true';		
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';		
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,Content-Type';

處理OPTIONS預檢

if ($request_method = 'OPTIONS') { 
  add_header 'Access-Control-Allow-Origin' "$http_origin";
  add_header 'Access-Control-Allow-Credentials' 'true';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since,Content-Type';
  return 200; 
}

3、js客戶端token傳輸、授權

js(react、vue等)客戶端需要在授權服務配置時,設定允許將token通過瀏覽器傳遞 AllowAccessTokensViaBrowser = true,客戶端設定禁用了授權頁面,登入鑑權後直接跳回對應 RequireConsent = false

4、前端統一介面返回格式

Umi框架預設格式與後臺介面返回不一致就會導致獲取不到,config.ts 加上以下程式碼,就可以使用後臺自定義返回的資料格式了

request: {
    dataField: ""  //忽略框架處理
}

5、PostLogoutRedirectUris無效

本以為配置了退出跳轉路由就OK了,結果還是得自己加程式碼手動跳轉,在授權服務中AccountController,Logout方法

6、EFCore連線資料庫偶爾異常:An exception has been raised that is likely due to a transient failure.

查資料說是ssl問題,連線字串server改成https的,不太確定,大佬懂的可以說一下

八、前人栽樹,後人乘涼

https://github.com/skoruba/react-oidc-client-js

九、程式碼已上傳

https://github.com/wintersir

十、後續

後面學習要往容器、微服務方向走了,Docker、Jenkins、DDD 等等,想學哪個學哪個,寫了也不一定學,哈哈~~~,還是那句話:
(個人學習記錄分享,堅持更新,也有可能爛尾,最終解釋權歸本人所有,哈哈哈哈,嗝~~~)

寫在最後

部落格名:WinterSir,學習目錄 https://www.cnblogs.com/WinterSir/p/13942849.html

相關文章