mcpField
A
arcgis-authentication

arcgis-authentication

github.com/saschabrunnerch安全2373 次安装29 周前更新
代码仓库

关于 arcgis-authentication

面向使用 ArcGIS Maps SDK for JavaScript 实现身份认证的开发者,提供 ArcGIS 身份与访问管理参考。内容涵盖 API 密钥、OAuth、令牌、Portal 用户信息、凭据处理和请求配置。

主要功能

  1. 01配置 API 密钥认证
  2. 02设置 OAuth 登录与退出
  3. 03使用 Portal 身份和用户项目
  4. 04注册并获取令牌
  5. 05配置可信服务器、代理和拦截器

适用场景

  1. 01为 ArcGIS 应用添加 OAuth 登录
  2. 02访问经过认证的 Enterprise Portal 内容
  3. 03处理令牌过期和已存储凭据
  4. 04通过代理配置跨域请求

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/saschabrunnerch/arcgis-maps-sdk-js-ai-context --skill arcgis-authentication

安装后在 Claude Code 中输入/arcgis-authentication确认已加载。

附带文件AGENTS.md

详细介绍

ArcGIS 身份验证

使用此技能实现身份验证、OAuth、API 密钥和身份管理。

导入模式

直接 ESM 导入
import OAuthInfo from "@arcgis/core/identity/OAuthInfo.js";
import esriId from "@arcgis/core/identity/IdentityManager.js";
import Portal from "@arcgis/core/portal/Portal.js";
import esriConfig from "@arcgis/core/config.js";
动态导入(CDN)
const OAuthInfo = await $arcgis.import("@arcgis/core/identity/OAuthInfo.js");
const esriId = await $arcgis.import("@arcgis/core/identity/IdentityManager.js");
const Portal = await $arcgis.import("@arcgis/core/portal/Portal.js");

API 密钥

最简单的身份验证方式。为所有 SDK 请求设置一次即可。

配置 API 密钥
import esriConfig from "@arcgis/core/config.js";

esriConfig.apiKey = "YOUR_API_KEY";

// Now basemaps and services will use the API key
const map = new Map({
  basemap: "arcgis/streets",
});
HTML 中的 API 密钥(CDN)
<script src="https://js.arcgis.com/5.0/"></script>
<script>
  $arcgis.config.apiKey = "YOUR_API_KEY";
</script>

OAuth 2.0 身份验证

基本 OAuth 设置
import OAuthInfo from "@arcgis/core/identity/OAuthInfo.js";
import esriId from "@arcgis/core/identity/IdentityManager.js";

const oauthInfo = new OAuthInfo({
  appId: "YOUR_APP_ID",
  popup: false, // false = redirect, true = popup window
});

esriId.registerOAuthInfos([oauthInfo]);
检查登录状态
async function checkSignIn() {
  try {
    await esriId.checkSignInStatus(oauthInfo.portalUrl + "/sharing");
    const portal = new Portal({ authMode: "immediate" });
    await portal.load();
    console.log("Signed in as:", portal.user.username);
    return portal;
  } catch {
    console.log("Not signed in");
    return null;
  }
}
登录
async function signIn() {
  try {
    const credential = await esriId.getCredential(
      oauthInfo.portalUrl + "/sharing",
    );
    return credential;
  } catch (error) {
    console.error("Sign in failed:", error);
  }
}
登出
function signOut() {
  esriId.destroyCredentials();
  window.location.reload();
}
完整 OAuth 流程
import OAuthInfo from "@arcgis/core/identity/OAuthInfo.js";
import esriId from "@arcgis/core/identity/IdentityManager.js";
import Portal from "@arcgis/core/portal/Portal.js";

const oauthInfo = new OAuthInfo({ appId: "YOUR_APP_ID" });
esriId.registerOAuthInfos([oauthInfo]);

// Check if already signed in
esriId
  .checkSignInStatus(oauthInfo.portalUrl + "/sharing")
  .then(() => {
    const portal = new Portal({ authMode: "immediate" });
    return portal.load();
  })
  .then((portal) => {
    console.log("Welcome,", portal.user.fullName);
    displayUserContent(portal);
  })
  .catch(() => {
    showSignInButton();
  });

function showSignInButton() {
  document.getElementById("signInBtn").onclick = () => {
    esriId
      .getCredential(oauthInfo.portalUrl + "/sharing")
      .then(() => window.location.reload());
  };
}

企业门户身份验证

配置企业门户
const oauthInfo = new OAuthInfo({
  appId: "YOUR_APP_ID",
  portalUrl: "https://your-portal.com/portal",
  popup: true,
});

esriId.registerOAuthInfos([oauthInfo]);
全局设置门户 URL
import esriConfig from "@arcgis/core/config.js";

esriConfig.portalUrl = "https://your-portal.com/portal";

基于令牌的身份验证

注册令牌
esriId.registerToken({
  server: "https://services.arcgis.com/",
  token: "YOUR_TOKEN",
});
手动获取令牌
const credential = await esriId.getCredential(
  "https://services.arcgis.com/...",
);
console.log("Token:", credential.token);
console.log("Expires:", new Date(credential.expires));

门户用户信息

import Portal from "@arcgis/core/portal/Portal.js";

const portal = new Portal({ authMode: "immediate" });
await portal.load();

console.log("Username:", portal.user.username);
console.log("Full name:", portal.user.fullName);
console.log("Email:", portal.user.email);
console.log("Role:", portal.user.role);
console.log("Thumbnail:", portal.user.thumbnailUrl);
console.log("Org name:", portal.name);
console.log("Org ID:", portal.id);

查询用户项目

import PortalQueryParams from "@arcgis/core/portal/PortalQueryParams.js";

const queryParams = new PortalQueryParams({
  query: `owner:${portal.user.username}`,
  sortField: "modified",
  sortOrder: "desc",
  num: 20,
});

const result = await portal.queryItems(queryParams);
result.results.forEach((item) => {
  console.log(item.title, item.type, item.id);
});

凭据持久化

// Clear all stored credentials
esriId.destroyCredentials();

// Find a specific credential
const credential = esriId.findCredential("https://services.arcgis.com/...");

可信服务器

import esriConfig from "@arcgis/core/config.js";

esriConfig.request.trustedServers.push("https://services.arcgis.com");
esriConfig.request.trustedServers.push("https://your-server.com");

CORS 和代理

import esriConfig from "@arcgis/core/config.js";

// Configure proxy for cross-origin requests
esriConfig.request.proxyUrl = "/proxy/";

// Configure proxy rules
esriConfig.request.proxyRules.push({
  urlPrefix: "https://services.arcgis.com",
  proxyUrl: "/proxy/",
});

常见问题

  1. App ID 重定向 URI:必须在 developers.arcgis.com 上为 App ID 注册正确的重定向 URI。URI 不匹配会导致身份验证静默失败。

  2. 移动设备上的弹出窗口拦截器:基于 OAuth 弹出窗口的登录在移动浏览器中会失败。

    // Anti-pattern: using popup flow on mobile
    const oauthInfo = new OAuthInfo({
      appId: "YOUR_APP_ID",
      popup: true, // Blocked by most mobile browsers
    });
    
    // Correct: use redirect flow for mobile
    const isMobile = /iPhone|iPad|Android/i.test(navigator.userAgent);
    const oauthInfo = new OAuthInfo({
      appId: "YOUR_APP_ID",
      popup: !isMobile,
    });
    
  3. 门户 URL 末尾的斜杠:门户 URL 末尾的斜杠会导致令牌验证失败。

    // Anti-pattern
    const portal = new Portal({
      url: "https://myorg.maps.arcgis.com/", // Trailing slash
    });
    
    // Correct
    const portal = new Portal({
      url: "https://myorg.maps.arcgis.com", // No trailing slash
    });
    
  4. 令牌过期:令牌会过期。请妥善处理刷新或重新身份验证。

  5. CORS 错误:配置可信服务器,或使用代理向非 ArcGIS 服务器发起跨域请求。

请求拦截器

import esriConfig from "@arcgis/core/config.js";

esriConfig.request.interceptors.push({
  urls: "https://services.arcgis.com",
  before: (params) => {
    // Add custom headers or modify request
    console.log("Request to:", params.url);
  },
  after: (response) => {
    // Process response
    console.log("Response status:", response.httpStatus);
  },
  error: (error) => {
    console.error("Request failed:", error);
  },
});

参考示例

  • identity-oauth-basic - 基本 OAuth 2.0 身份验证设置
  • identity-oauth-component - 基于 OAuth 组件的身份验证
  • basemaps-portal - 用于底图的已验证门户访问
  • webmap-save - 保存地图(需要身份验证)

相关技能

  • 有关管理门户项目、WebMaps 和 WebScenes,请参阅 arcgis-portal-content。
  • 有关需要身份验证的高级 REST 服务,请参阅 arcgis-rest-services。
  • 有关包含身份验证设置的应用脚手架,请参阅 arcgis-starter-app。

评论

支持 Markdown