Chuyển đến nội dung chính

React Refresh Day 9: Tích hợp SSO thực tế với Google OIDC & Microsoft Entra ID (Adapter Pattern)

Ở Day 8, chúng ta đã xây dựng hệ thống Authentication & Multi-Role RBAC theo kiến trúc 4 tầng Bottom-Up với DemoAuthService. Hôm nay, ở Day 9, chúng ta sẽ chứng minh giá trị thực sự của Adapter Pattern: tích hợp đăng nhập thực tế với Google OpenID Connect (OIDC) và Microsoft Entra ID (MSAL) hoàn toàn ở phía React + TypeScript mà không phải sửa một dòng code nào trong authSchema.ts, rbac.ts, ProtectedRoute.tsx hay Sidebar.tsx.

Phạm vi Day 9 & Yêu cầu môi trường

Bài học tập trung 100% vào kiến trúc xác thực ở tầng Frontend SPA và chuẩn hóa dữ liệu người dùng từ nhiều Identity Provider. Bạn không bắt buộc phải có thẻ tín dụng Azure hay Google Cloud để thực hành: chế độ VITE_AUTH_PROVIDER=demo vẫn được giữ làm mặc định, đồng thời cả Google Cloud Console lẫn Microsoft Entra Free Tier đều cho phép tạo App Registration miễn phí.

1. Nền tảng OAuth 2.0, OpenID Connect (OIDC) & PKCE

Trước khi cài đặt thư viện, hãy nắm vững 4 khái niệm cốt lõi và 3 loại Token vận hành đằng sau mọi nút bấm "Sign in with Google / Microsoft":

Khái niệm Vai trò trong hệ thống
OAuth 2.0 Giao thức ủy quyền (Authorization): Cấp quyền cho ứng dụng truy cập tài nguyên/API thay mặt người dùng thông qua Access Token.
OpenID Connect (OIDC) Lớp xác thực danh tính (Authentication) xây dựng bên trên OAuth 2.0: Bổ sung ID Token (chuẩn JWT) để ứng dụng biết "Bạn là ai?".
Single Sign-On (SSO) Cơ chế đăng nhập một lần tại Identity Provider để sử dụng xuyên suốt nhiều ứng dụng tin cậy mà không cần nhập lại mật khẩu.
Identity Provider (IdP) Hệ thống quản lý và xác thực định danh tập trung (Google Identity, Microsoft Entra ID, Okta, Keycloak...).

Phân biệt 3 loại Token trong OIDC

Loại Token Mục đích sử dụng Quy tắc sống còn trên Frontend
ID Token Chuẩn JWT chứa hồ sơ định danh (sub, oid, name, email, roles) dành riêng cho ứng dụng Frontend đọc thông tin người dùng. Không dùng ID Token làm Bearer Token để gọi API Backend.
Access Token Chứng chỉ ủy quyền (kèm scopes và aud) dùng để gửi lên Backend API (Authorization: Bearer ...). Sẽ được dùng ở Day 10 khi kết nối .NET 10 Web API.
Refresh Token Dùng để xin cấp lại Access Token mới khi hết hạn mà không bắt người dùng đăng nhập lại. Trong SPA hiện đại, thư viện như MSAL quản lý vòng đời làm mới token tự động qua acquireTokenSilent().

Authorization Code Flow + PKCE hoạt động ra sao?

Ứng dụng React SPA chạy hoàn toàn trên trình duyệt của người dùng — mã nguồn JavaScript và biến môi trường đóng gói vào bundle đều có thể bị đọc qua DevTools. Vì vậy, SPA là Public Client và tuyệt đối không được chứa Client Secret. Thay vào đó, OAuth 2.1 / OIDC sử dụng Authorization Code Flow + PKCE (Proof Key for Code Exchange):

  1. Trước khi chuyển hướng sang IdP, SPA sinh ngẫu nhiên một chuỗi bí mật tạm thời gọi là code_verifier và băm SHA-256 thành code_challenge.
  2. SPA chuyển hướng người dùng kèm client_id và code_challenge lên IdP.
  3. Sau khi người dùng đăng nhập thành công, IdP trả về một authorization_code ngắn hạn trên URL redirect.
  4. SPA gửi authorization_code kèm code_verifier gốc lên token endpoint. IdP băm lại code_verifier, khớp với code_challenge ban đầu rồi mới cấp Token — ngăn chặn kẻ tấn công đánh cắp authorization_code trên đường truyền.

Phân biệt luồng tích hợp Google vs Microsoft Entra ID

Google Identity Services cung cấp nhiều chế độ: component nút bấm <GoogleLogin /> sử dụng ID Token Credential Flow (trả thẳng ID Token về callback onSuccess), trong khi @azure/msal-browser thực thi đầy đủ Authorization Code Flow + PKCE. Kiến trúc Adapter Pattern của chúng ta sẽ bọc cả hai cơ chế này sau cùng một giao diện AuthService.

2. Kiến trúc Adapter Pattern & Cấu hình Multi-Provider

Thay vì nhồi nhét if (provider === 'google') ... else if (provider === 'entra') vào trong AuthProvider hay Header, ta giữ AuthProvider chỉ làm việc với hợp đồng AuthService. Tầng Factory sẽ đọc biến môi trường VITE_AUTH_PROVIDER để cung cấp Adapter tương ứng:

flowchart TD UI["UI Components (LoginPage, Header, Sidebar, ProtectedRoute)"] --> Ctx["AuthProvider (user, isLoading, providerType)"] Ctx --> Factory["getAuthService() Factory"] Factory --> Contract["interface AuthService"] Contract --> Demo["DemoAuthService\n(Mock Session)"] Contract --> Google["GoogleAuthService\n(Google ID Token JWT)"] Contract --> Entra["EntraAuthService\n(MSAL PKCE + idTokenClaims)"] Demo & Google & Entra --> Schema["userSchema.safeParse()\n(Normalized User Model)"]

Bước 1: Khai báo biến môi trường trong .env.example và .env.local

# Chọn provider hoạt động: demo | google | entra
VITE_AUTH_PROVIDER=demo

# Cấu hình Google OIDC (Public Client ID)
VITE_GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com

# Cấu hình Microsoft Entra ID (Public Client ID & Tenant ID)
VITE_ENTRA_CLIENT_ID=your-entra-application-client-id
VITE_ENTRA_TENANT_ID=your-entra-directory-tenant-id

Quy tắc bảo mật biến môi trường trong Vite

Mọi biến bắt đầu bằng VITE_ đều được Vite nhúng công khai vào mã JavaScript phía trình duyệt. Client ID và Tenant ID là thông tin định danh công khai (không phải bí mật), nhưng tuyệt đối không bao giờ đặt Client Secret vào file .env của dự án React.

Bước 2: Tạo src/config/authConfig.ts & Helper chuẩn hóa

// src/config/authConfig.ts
export type AuthProviderType = 'demo' | 'google' | 'entra';

const rawProvider = import.meta.env.VITE_AUTH_PROVIDER as string | undefined;

export const AUTH_CONFIG = {
  provider: (['demo', 'google', 'entra'].includes(rawProvider ?? '')
    ? rawProvider
    : 'demo') as AuthProviderType,
  googleClientId: (import.meta.env.VITE_GOOGLE_CLIENT_ID as string) || '',
  entraClientId: (import.meta.env.VITE_ENTRA_CLIENT_ID as string) || '',
  entraTenantId: (import.meta.env.VITE_ENTRA_TENANT_ID as string) || 'common',
};
// src/utils/authHelpers.ts
import { roleSchema, type Role } from '../schemas/authSchema';

export function buildAvatarInitials(name: string): string {
  const initials = name
    .trim()
    .split(/\s+/)
    .map((part) => part[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);

  return initials || 'U';
}

// Lọc và chuẩn hóa mảng roles thô từ IdP (ví dụ ["Admin", "Reader"]) về Role[] hợp lệ
export function normalizeRoles(rawRoles: unknown): Role[] {
  if (!Array.isArray(rawRoles)) return [];

  const validRoles: Role[] = [];
  for (const item of rawRoles) {
    if (typeof item === 'string') {
      const parsed = roleSchema.safeParse(item.toLowerCase());
      if (parsed.success && !validRoles.includes(parsed.data)) {
        validRoles.push(parsed.data);
      }
    }
  }
  return validRoles;
}

Bước 3: Cập nhật Hợp đồng AuthService & Factory (src/services/authService.ts)

Để hỗ trợ đồng thời cả luồng đăng nhập truyền tham số (Demo nhận profile, Google nhận credential JWT) lẫn luồng tự bật cửa sổ (Entra gọi loginPopup()), ta định nghĩa kiểu LoginPayload linh hoạt trên cùng một phương thức login():

// src/services/authService.ts
import { AUTH_CONFIG, type AuthProviderType } from '../config/authConfig';
import type { Role, User } from '../schemas/authSchema';
import { demoAuthService } from './demoAuthService';
import { googleAuthService } from './googleAuthService';
import { entraAuthService } from './entraAuthService';

export type LoginPayload =
  | { type: 'demo'; name: string; email: string; roles: Role[] }
  | { type: 'google'; credential: string }
  | { type: 'entra' };

export interface AuthService {
  readonly providerType: AuthProviderType;
  login(payload?: LoginPayload): Promise<User>;
  logout(): Promise<void>;
  getCurrentUser(): Promise<User | null>;
}

export function getAuthService(): AuthService {
  switch (AUTH_CONFIG.provider) {
    case 'google':
      return googleAuthService;
    case 'entra':
      return entraAuthService;
    case 'demo':
    default:
      return demoAuthService;
  }
}

3. Implement Google OIDC Adapter (@react-oauth/google)

Cấu hình nhanh trên Google Cloud Console

  1. Truy cập Google Cloud Console → Tạo hoặc chọn Project → Vào APIs & Services > OAuth consent screen (chọn External và thêm email của bạn vào danh sách Test users).
  2. Vào Credentials > Create Credentials > OAuth client ID → Chọn loại ứng dụng là Web application.
  3. Tại mục Authorized JavaScript origins, thêm http://localhost:5173 (lưu ý không có dấu / ở cuối), sau đó copy Client ID dán vào VITE_GOOGLE_CLIENT_ID.

Cài đặt thư viện & Viết src/services/googleAuthService.ts

yarn add @react-oauth/google

Khi người dùng bấm nút đăng nhập Google, thư viện trả về chuỗi credential (chính là Google ID Token dạng JWT gồm 3 phần Header.Payload.Signature). Ở tầng Frontend, ta giải mã phần Payload (Base64URL hỗ trợ ký tự tiếng Việt UTF-8) để lấy sub, name, email và validate bằng userSchema:

// src/services/googleAuthService.ts
import { googleLogout } from '@react-oauth/google';
import { userSchema, type User } from '../schemas/authSchema';
import { buildAvatarInitials } from '../utils/authHelpers';
import type { AuthService, LoginPayload } from './authService';

const GOOGLE_SESSION_KEY = 'booknest_google_session';

function decodeJwtPayload(token: string): Record<string, unknown> {
  const base64Url = token.split('.')[1];
  if (!base64Url) {
    throw new Error('ID Token không đúng định dạng JWT');
  }

  const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  const jsonPayload = decodeURIComponent(
    atob(base64)
      .split('')
      .map((c) => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`)
      .join('')
  );

  return JSON.parse(jsonPayload) as Record<string, unknown>;
}

export const googleAuthService: AuthService = {
  providerType: 'google',

  async login(payload?: LoginPayload) {
    if (!payload || payload.type !== 'google') {
      throw new Error('Thiếu Google credential token');
    }

    const claims = decodeJwtPayload(payload.credential);
    const sub = String(claims.sub ?? '');
    const name = String(claims.name ?? 'Google User');
    const email = String(claims.email ?? '');

    // Google OIDC mặc định không kèm App Roles -> gán 'reader' trong phạm vi Frontend Day 9
    const candidateUser = {
      id: `google_${sub}`,
      name,
      email,
      avatarInitials: buildAvatarInitials(name),
      roles: ['reader'],
    };

    const parsed = userSchema.safeParse(candidateUser);
    if (!parsed.success) {
      throw new Error('Dữ liệu hồ sơ Google không hợp lệ');
    }

    sessionStorage.setItem(GOOGLE_SESSION_KEY, JSON.stringify(parsed.data));
    return Promise.resolve(parsed.data);
  },

  async logout() {
    // Tắt tự động đăng nhập lại (One Tap) của Google cho BookNest, không đăng xuất tài khoản Google toàn trình duyệt
    googleLogout();
    sessionStorage.removeItem(GOOGLE_SESSION_KEY);
    return Promise.resolve();
  },

  async getCurrentUser() {
    try {
      const raw = sessionStorage.getItem(GOOGLE_SESSION_KEY);
      if (!raw) return null;

      const parsed = userSchema.safeParse(JSON.parse(raw));
      if (!parsed.success) {
        sessionStorage.removeItem(GOOGLE_SESSION_KEY);
        return null;
      }
      return parsed.data;
    } catch {
      return null;
    }
  },
};

JWT Decode KHÔNG phải là JWT Verify

Hàm decodeJwtPayload() phía trên chỉ giải mã Base64 để hiển thị giao diện. Bất kỳ ai cũng có thể tự tạo một chuỗi JWT giả nếu không kiểm tra chữ ký số bằng Public Key của Google. Ở Day 10, Backend .NET 10 sẽ đảm nhiệm việc xác minh chữ ký thật sự trước khi cấp quyền truy cập dữ liệu.

4. Implement Microsoft Entra ID Adapter (MSAL)

Đây là phần trọng tâm cho các ứng dụng doanh nghiệp: Microsoft Entra ID hỗ trợ sẵn App Roles và nhúng trực tiếp danh sách vai trò vào bên trong claim roles của ID Token.

Cấu hình App Registration & App Roles trên Microsoft Entra Admin Center

  1. Truy cập Microsoft Entra Admin Center → Identity > Applications > App registrations > New registration.
  2. Đặt tên BookNest-SPA, chọn Supported account types phù hợp, tại mục Redirect URI chọn nền tảng Single-page application (SPA) và nhập http://localhost:5173.
  3. Copy Application (client) ID và Directory (tenant) ID vào .env.local.
  4. Vào mục App roles > Create app role để tạo 2 vai trò (chọn Allowed member types: Users/Groups):
    • Display name: Administrator — Value: admin
    • Display name: Reader — Value: reader
  5. Vào Enterprise applications → Tìm BookNest-SPA → Users and groups > Add user/group để gán vai trò Administrator hoặc Reader cho tài khoản của bạn.

Cài đặt MSAL & Cấu hình src/config/msalConfig.ts

yarn add @azure/msal-browser @azure/msal-react
// src/config/msalConfig.ts
import { PublicClientApplication, type Configuration } from '@azure/msal-browser';
import { AUTH_CONFIG } from './authConfig';

export const msalConfig: Configuration = {
  auth: {
    clientId: AUTH_CONFIG.entraClientId,
    authority: `https://login.microsoftonline.com/${AUTH_CONFIG.entraTenantId}`,
    redirectUri: window.location.origin,
  },
  cache: {
    // Dùng sessionStorage để phiên tự hủy khi đóng tab, giảm bề mặt tồn tại token so với localStorage
    cacheLocation: 'sessionStorage',
  },
};

export const loginRequest = {
  scopes: ['openid', 'profile', 'email'],
};

export const msalInstance = new PublicClientApplication(msalConfig);

Viết src/services/entraAuthService.ts (Xử lý initialize() & Đọc idTokenClaims.roles)

Từ phiên bản @azure/msal-browser v3 trở lên, msalInstance.initialize() là bắt buộc và trả về một Promise. Ta bọc logic khởi tạo một lần (idempotent initialization) ngay bên trong entraAuthService để AuthProvider không cần quan tâm đến chi tiết vòng đời riêng của MSAL:

// src/services/entraAuthService.ts
import type { AccountInfo } from '@azure/msal-browser';
import { msalInstance, loginRequest } from '../config/msalConfig';
import { userSchema, type User } from '../schemas/authSchema';
import { buildAvatarInitials, normalizeRoles } from '../utils/authHelpers';
import type { AuthService } from './authService';

let msalInitPromise: Promise<void> | null = null;

async function ensureMsalInitialized(): Promise<void> {
  if (!msalInitPromise) {
    msalInitPromise = msalInstance
      .initialize()
      .then(() => msalInstance.handleRedirectPromise())
      .then(() => undefined);
  }
  return msalInitPromise;
}

function mapEntraAccountToUser(account: AccountInfo): User {
  const claims = (account.idTokenClaims ?? {}) as Record<string, unknown>;

  // Ưu tiên 'oid' (Object ID cố định trong Tenant) trước 'sub'
  const stableId = String(claims.oid ?? claims.sub ?? account.localAccountId);
  const name = account.name || String(claims.name ?? 'Entra User');
  const email =
    account.username ||
    String(claims.email ?? claims.preferred_username ?? '');

  // Trích xuất claim 'roles' từ ID Token và lọc an toàn qua Zod schema
  const roles = normalizeRoles(claims.roles);

  const parsed = userSchema.safeParse({
    id: `entra_${stableId}`,
    name,
    email,
    avatarInitials: buildAvatarInitials(name),
    roles,
  });

  if (!parsed.success) {
    throw new Error('Không thể chuẩn hóa thông tin tài khoản Microsoft Entra ID');
  }

  return parsed.data;
}

export const entraAuthService: AuthService = {
  providerType: 'entra',

  async login() {
    await ensureMsalInitialized();
    const result = await msalInstance.loginPopup(loginRequest);
    msalInstance.setActiveAccount(result.account);
    return mapEntraAccountToUser(result.account);
  },

  async logout() {
    await ensureMsalInitialized();
    const activeAccount =
      msalInstance.getActiveAccount() ?? msalInstance.getAllAccounts()[0] ?? null;
    msalInstance.setActiveAccount(null);

    if (activeAccount) {
      await msalInstance.logoutPopup({ account: activeAccount });
    }
  },

  async getCurrentUser() {
    try {
      await ensureMsalInitialized();
      const activeAccount =
        msalInstance.getActiveAccount() ?? msalInstance.getAllAccounts()[0] ?? null;

      if (!activeAccount) return null;
      msalInstance.setActiveAccount(activeAccount);
      return mapEntraAccountToUser(activeAccount);
    } catch {
      return null;
    }
  },
};

5. Chuẩn hóa User & Tích hợp vào Giao diện BookNest

Bảng dưới đây cho thấy cách cả 3 Identity Provider đều được quy về cùng một mô hình User duy nhất trước khi đi vào AuthContext:

Trường dữ liệu User Demo Provider Google OIDC Microsoft Entra ID
id user_1733... google_${claims.sub} entra_${claims.oid ?? claims.sub}
name Mock Name claims.name account.name
email Mock Email claims.email account.username / preferred_username
roles Mock Role[] ['reader'] (mặc định Lab) normalizeRoles(claims.roles)

Vì sao không dùng email làm khóa định danh id?

Trong doanh nghiệp, email có thể thay đổi khi nhân sự đổi họ tên hoặc chuyển tên miền công ty, thậm chí tái sử dụng cho nhân viên mới. Định danh bền vững phải là sub (Google OIDC) hoặc oid — Object ID duy nhất của người dùng trong Microsoft Entra Tenant.

Tạo src/components/auth/AppAuthWrapper.tsx (Bọc Provider có điều kiện)

Để <GoogleOAuthProvider> không báo lỗi thiếu clientId khi bạn đang chạy chế độ demo hoặc entra, ta tạo một Wrapper bọc đúng thư viện theo AUTH_CONFIG.provider:

// src/components/auth/AppAuthWrapper.tsx
import type { ReactNode } from 'react';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { MsalProvider } from '@azure/msal-react';
import { AUTH_CONFIG } from '../../config/authConfig';
import { msalInstance } from '../../config/msalConfig';
import { AuthProvider } from '../../contexts/AuthProvider';

export function AppAuthWrapper({ children }: { children: ReactNode }) {
  if (AUTH_CONFIG.provider === 'google') {
    return (
      <GoogleOAuthProvider clientId={AUTH_CONFIG.googleClientId}>
        <AuthProvider>{children}</AuthProvider>
      </GoogleOAuthProvider>
    );
  }

  if (AUTH_CONFIG.provider === 'entra') {
    return (
      <MsalProvider instance={msalInstance}>
        <AuthProvider>{children}</AuthProvider>
      </MsalProvider>
    );
  }

  return <AuthProvider>{children}</AuthProvider>;
}

Cập nhật AuthContext, LoginPage.tsx & Header.tsx

Trong AuthContextValue, ta đổi loginAsDemo thành login(payload?: LoginPayload) và expose thêm providerType để giao diện tự thích ứng:

// Trích đoạn cập nhật trong src/pages/LoginPage.tsx
import { GoogleLogin } from '@react-oauth/google';
import { useAuth } from '../hooks/useAuth';

// Bên trong LoginPage:
const { providerType, login } = useAuth();

// 1. Khi providerType === 'google':
{providerType === 'google' && (
  <div className="flex justify-center py-4">
    <GoogleLogin
      onSuccess={(credentialResponse) => {
        if (credentialResponse.credential) {
          void login({
            type: 'google',
            credential: credentialResponse.credential,
          }).then(() => navigate(fromPath, { replace: true }));
        }
      }}
      onError={() => {
        console.error('Google Sign-In thất bại');
      }}
    />
  </div>
)}

// 2. Khi providerType === 'entra':
{providerType === 'entra' && (
  <button
    type="button"
    onClick={() => {
      void login({ type: 'entra' }).then(() =>
        navigate(fromPath, { replace: true })
      );
    }}
    className="w-full rounded-xl bg-slate-900 px-4 py-3 text-sm font-semibold text-white hover:bg-slate-800 transition-colors cursor-pointer"
  >
    Sign in with Microsoft Entra ID
  </button>
)}

// 3. Khi providerType === 'demo': giữ nguyên danh sách DEMO_ACCOUNTS từ Day 8!

Tương tự trên Header.tsx, bạn chỉ cần thêm điều kiện {providerType === 'demo' && (...)} bao quanh mục "Đổi nhanh Role (Demo)" để khi chạy SSO thật, menu người dùng chỉ hiển thị thông tin tài khoản, Role Badges và nút Đăng xuất. Đặc biệt, ProtectedRoute.tsx và Sidebar.tsx giữ nguyên 100% mã nguồn của Day 8.

6. Nguyên tắc Bảo mật & Bảng Xử lý Lỗi SSO (Troubleshooting)

Mã lỗi / Hiện tượng Nguyên nhân phổ biến Cách khắc phục
redirect_uri_mismatch (Google) Origin trên Google Cloud Console không khớp chính xác với URL đang chạy (khác port hoặc thừa dấu /). Kiểm tra đúng http://localhost:5173 trong mục Authorized JavaScript origins.
AADSTS50011 (Entra ID) redirectUri gửi lên không khớp với danh sách SPA Redirect URI đã đăng ký trên Azure. Vào Authentication > Single-page application trên Azure Portal và thêm http://localhost:5173.
interaction_in_progress Người dùng bấm nút Login nhiều lần khi popup MSAL trước đó chưa đóng hoặc bị chặn bởi trình duyệt. Disable nút Login trong lúc đang xử lý đăng nhập và cho phép Popup trên trình duyệt.
BrowserAuthError: uninitialized_public_client_application Gọi loginPopup() hoặc getAllAccounts() trước khi msalInstance.initialize() hoàn tất. Luôn gọi thông qua hàm ensureMsalInitialized() trước mọi thao tác MSAL.
Đăng nhập Entra thành công nhưng roles: [] Chưa gán User vào Enterprise Application hoặc giá trị role không khớp roleSchema. Kiểm tra lại mục Users and groups trong Enterprise Application và đảm bảo Value là admin hoặc reader.

7. Tổng kết Day 9 & Chuẩn bị cho Day 10

Sau Day 9, BookNest đã nâng cấp từ một ứng dụng dùng phiên đăng nhập giả lập thành một kiến trúc SPA chuẩn doanh nghiệp có khả năng hoán đổi linh hoạt giữa Demo Auth, Google OIDC và Microsoft Entra ID thông qua biến môi trường.

Bước tiếp theo ở Day 10: Full-stack Authentication với .NET 10 Web API

Hiện tại Frontend đã xác thực được người dùng và đọc Role để điều hướng UI. Ở Day 10, chúng ta sẽ xây dựng Backend ASP.NET Core Web API (.NET 10) cấu hình JWT Bearer Authentication để xác minh chữ ký thật của Access Token, áp dụng Authorization Policy trên từng endpoint, viết Axios/Fetch Interceptor tự động đính kèm Token và đồng bộ dữ liệu sách lên Server thay cho localStorage.

Nhận xét

Bài đăng phổ biến từ blog này

[ASP.NET MVC] Authentication và Authorize

Một trong những vấn đề bảo mật cơ bản nhất là đảm bảo những người dùng hợp lệ truy cập vào hệ thống. ASP.NET đưa ra 2 khái niệm: Authentication và Authorize Authentication xác nhận bạn là ai. Ví dụ: Bạn có thể đăng nhập vào hệ thống bằng username và password hoặc bằng ssh. Authorization xác nhận những gì bạn có thể làm. Ví dụ: Bạn được phép truy cập vào website, đăng thông tin lên diễn đàn nhưng bạn không được phép truy cập vào trang mod và admin.

Tổng hợp một số kiến thức lập trình về Amibroker

Giới thiệu về Amibroker Amibroker theo developer Tomasz Janeczko được xây dựng dựa trên ngôn ngữ C. Vì vậy bộ code Amibroker Formula Language sử dụng có syntax khá tương đồng với C, ví dụ như câu lệnh #include để import hay cách gói các object, hàm trong các block {} và kết thúc câu lệnh bằng dấu “;”. AFL trong Amibroker là ngôn ngữ xử lý mảng (an array processing language). Nó hoạt động dựa trên các mảng (các dòng/vector) số liệu, khá giống với cách hoạt động của spreadsheet trên excel.

ASP.NET MVC: Cơ bản về Validation

Validation (chứng thực) là một tính năng quan trọng trong ASP.NET MVC và được phát triển trong một thời gian dài. Validation vắng mặt trong phiên bản đầu tiên của asp.net mvc và thật khó để tích hợp 1 framework validation của một bên thứ 3 vì không có khả năng mở rộng. ASP.NET MVC2 đã hỗ trợ framework validation do Microsoft phát triển, tên là Data Annotations. Và trong phiên bản 3, framework validation đã hỗ trợ tốt hơn việc xác thực phía máy khách, và đây là một xu hướng của việc phát triển ứng dụng web ngày nay.