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

一、前言

此篇內容較多,我是一步一個腳印(坑),以至於寫了好久,主要是這幾部分:後台升級 .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 = '//localhost:8000/';
        const clientRoot = '//homejok.wintersir.com/';        
        const settings = {
            authority: '//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  //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 //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 ^(.*)$ //$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 //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 //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 //www.wintersir.com:5000/;
  }
}

六、效果圖

1、React前端

2、Mvc網站測試

七、各種踩坑

1、CentOS8不支持 .NET6

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

sudo rpm -Uvh //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的,不太確定,大佬懂的可以說一下

八、前人栽樹,後人乘涼

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

九、代碼已上傳

//github.com/wintersir

十、後續

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

寫在最後

博客名:WinterSir,學習目錄 //www.cnblogs.com/WinterSir/p/13942849.html