#author("2020-08-13T04:38:34+00:00","","")
#author("2020-08-13T07:59:34+00:00","","")
#mynavi(Azureメモ)
#setlinebreak(on);

* 概要 [#dadf4db4]
#html(<div class="pl10">)
#TODO
#html(</div>)

* 目次 [#g9c9f576]
#contents
- 関連
-- [[Azureメモ]]
- 参考
-- https://grafana.com/docs/grafana/latest/auth/ldap/
-- https://grafana.com/docs/grafana/latest/auth/ldap/#active-directory
-- https://grafana.com/docs/grafana/latest/auth/azuread/
-- https://techexpert.tips/ja/grafana-ja/active-directory%E3%81%A7%E3%81%AEgrafana-ldap%E8%AA%8D%E8%A8%BC/
-- [[Microsoft ID プラットフォーム を使用したアプリのサインイン フロー>https://docs.microsoft.com/ja-jp/azure/active-directory/develop/app-sign-in-flow]]
-- [[Microsoft ID プラットフォームを使用した認証と承認>https://docs.microsoft.com/ja-jp/azure/active-directory/develop/authentication-vs-authorization#authentication-and-authorization-using-microsoft-identity-platform]]
-- [[Microsoft ID プラットフォームと OAuth 2.0 認証コード フロー>https://docs.microsoft.com/ja-jp/azure/active-directory/develop/v2-oauth2-auth-code-flow]]
-- [[認証コード フローと暗黙的なフロー(Web Apps)>https://docs.microsoft.com/ja-jp/azure/active-directory/develop/v2-app-types#web-apps]]
-- [[Azure AD OAuth2 authentication>https://grafana.com/docs/grafana/latest/auth/azuread/]]
-- [[Microsoft ID プラットフォームと暗黙的な許可のフロー (暗黙的な許可フローの有効有効化)>https://docs.microsoft.com/ja-jp/azure/active-directory/develop/v2-oauth2-implicit-grant-flow#send-the-sign-in-request]]
-- [[Azure Active Directory を使ってアプリケーションに対するグループ要求を構成する>https://docs.microsoft.com/ja-jp/azure/active-directory/hybrid/how-to-connect-fed-group-claims#configure-the-azure-ad-application-registration-for-group-attributes]]
-- [[アプリケーションにアプリ ロールを追加してトークンで受け取る>https://docs.microsoft.com/ja-jp/azure/active-directory/develop/howto-add-app-roles-in-azure-ad-apps]]


* ADアプリ 及び シークレットの作成 [#m5cf0c30]
#html(<div class="pl10">)

App Service のアプリ(Grafana)を作成後でもシークレットの作成は可能だが、
結局は grafana.ini を変更して再デプロイが必要になるので、先に ADアプリ 及び シークレットは別アプリとして作成しておく。

#html(){{
<style>
.images div { vertical-align: top; margin-right: 20px; }
.images img { border: 1px solid #333; }
</style>
}}
#html(<div class="images">)
#html(<div class="ib">)
[Active Directory] を選択
&ref(create_secret1-1.png,nolink);
#html(</div><div class="ib">)
[アプリの登録] を選択
&ref(create_secret1-2.png,nolink);
#html(</div><div class="ib">)
[新規登録] を選択
&ref(create_secret1-3.png,nolink);
#html(</div><div class="ib">)
アプリケーション名を入力して登録
&ref(create_secret1-4.png,nolink);
#html(</div><div class="ib">)
クライアントID(アプリケーションID)を確認しておく
クライアントID 及び テナントID を確認しておく
&ref(create_secret1-5.png,nolink);
#html(</div><div class="ib">)
[証明書とシークレット] → [新しいクライアントシークレット] を選択
&ref(create_secret1-6.png,nolink);
#html(</div><div class="ib">)
説明を入力して [追加]
&ref(create_secret1-7.png,nolink);
#html(</div><div class="ib">)
登録したクライアントシークレットを確認しておく。(追加直後しか確認できないので注意)
&ref(create_secret1-8.png,nolink);
#html(</div><div class="ib">)
[認証] → [プラットフォームの追加]
&ref(create_secret1-9.png,nolink);
#html(</div><div class="">)
#html(<div class="ib">)
リダイレクトURI 等を登録する。
&ref(create_secret1-10.png,nolink);
#html(</div><div class="ib">)
 
 
| 項目 | 設定値 |h
| リダイレクトURI | https&#58;//Grafanaアプリケーション名.azurewebsites.net/login/azuread |
| ログアウトURL|  https&#58;//Grafanaアプリケーション名.azurewebsites.net/logout |
| 暗黙的な許可フロー |  シークレットを 他の Service App と共用する場合は2つともチェックを入れておく |

※ Grafanaアプリケーション名は 後述の 0_env.sh の $webappName と同じもの。

#html(</div>)


#html(</div>)


#html(</div>)

** アプリケーションロールの作成 [#qfb72dfa]
#html(<div class="pl10">)

登録したアプリケーションのマニフェストを以下の通り更新する(appRolesの追加)
左側メニューの [マニフェスト] から、登録したアプリケーションのマニフェストを以下の通り更新する(アプリケーションロールの追加)
※ユニークIDは uuidgen 等を使用して3つ生成しておく。
※ https://grafana.com/docs/grafana/latest/auth/azuread/

#mycode2(){{
        :
	"appRoles": [
		{
			"allowedMemberTypes": [
				"User"
			],
			"description": "Grafana Editor Users",
			"displayName": "Grafana Editor",
			"id": "ユニークなID",
			"isEnabled": true,
			"lang": null,
			"origin": "Application",
			"value": "Editor"
		},
		{
			"allowedMemberTypes": [
				"User"
			],
			"description": "Grafana read only Users",
			"displayName": "Grafana Viewer",
			"id": "ユニークなID",
			"isEnabled": true,
			"lang": null,
			"origin": "Application",
			"value": "Viewer"
		},
		{
			"allowedMemberTypes": [
				"User"
			],
			"description": "Grafana admin Users",
			"displayName": "Grafana Admin",
			"id": "ユニークなID",
			"isEnabled": true,
			"lang": null,
			"origin": "Application",
			"value": "Admin"
		}
	],
        :
        "groupMembershipClaims": "ApplicationGroup",
        :
}}

#html(</div>)


#html(</div>)
// ADアプリ 及び シークレットの作成

* ユーザ作成 及び ロールの割当 [#f573268d]
#html(<div class="pl10">)

** ユーザの作成 [#d6279ac1]
#html(<div class="pl10">)
#TODO

[Azure Active Directory] → [ユーザ] から下図の通りユーザを登録。
#html(<div class="ib border">)
&ref(create-users.png,nolink);
#html(</div>)

#html(</div>)

** ロールの割り当て [#jdcb9361]
#html(<div class="pl10">)
#TODO

[Azure Active Directory] → [エンタープライズ アプリケーション] から対象のアプリを選択後に [ユーザーとグループ] を選択して、ユーザにアプリケーションロールを割り当てる。
※デフォルトで Viewer権限 になるので、割り当てるのは Admin と Editor に該当するユーザだけでOK。
#html(<div class="ib border">)
&ref(attach_role.png,nolink);
#html(</div>)

#html(</div>)

#html(</div>)


* リソースの作成 [#p10153b6]
#html(<div class="pl10">)

** シェル作成 [#r711498e]
** ファイル作成 [#r711498e]
#html(<div class="pl10">)

#html(){{
<div id="tabs1">
  <ul>
    <li><a href="#tabs1-0">0_env.sh</a></li>
    <li><a href="#tabs1-1">1_resources.sh</a></li>
    <li><a href="#tabs1-2">2_vm_setup.tmpl</a></li>
    <li><a href="#tabs1-1">0_env.sh</a></li>
    <li><a href="#tabs1-2">1_resources.sh</a></li>
    <li><a href="#tabs1-3">Dockerfile</a></li>
    <li><a href="#tabs1-0">grafana.ini</a></li>
  </ul>
}}

// START tabs1-0
#html(<div id="tabs1-0">)
// START tabs1-1
#html(<div id="tabs1-1">)

0_env.sh
#mycode2(){{
#!/bin/bash

PREFIX="各リソース名に付ける接頭文字"
subscriptionId="サブスクリプションID"
region=japanwest

resourceGroup=${PREFIX}ResourceGroup
# リソースグループ
resourceGroup=${PREFIX}Resources

vnetName=${PREFIX}VNet
vnetPrefix=10.1.0.0/16
# リージョン
region=japanwest

nsgName=${vnetName}SecGrp
nsgPubRuleName=${nsgName}PubRule
nsgPubInboundPort="3000"
# レジストリ名
registryName=${PREFIX}registry

vmSubnetName=${PREFIX}VmSubnet
vmSubnetPrefix=10.1.1.0/24
# Dockerイメージ名
imageName=${PREFIX}-grafana

vmName=${PREFIX}Vm
vmImage=UbuntuLTS
vmIpAddress=10.1.1.5
vmUser=sample
# ADアプリ名(認証用)
adAppName=${PREFIX}-apps

# 登録したアプリケーションのクライアントID、シークレット
clientId="確認したクライアントID"
clientSecret="確認したクライアントシークレット"

# テナントIDの取得
tenantId=`az account show -s $subscriptionId -o table | tail -1 | awk '{print $NF}'`
# Grafanaアプリ名
webappName=${PREFIX}-grafana
}}

#html(</div>)
// END tabs1-0
// END tabs1-1

// START tabs1-1
#html(<div id="tabs1-1">)
// START tabs1-2
#html(<div id="tabs1-2">)

#mycode2(){{
#!/bin/bash

# 設定の読み込み
# リソース名の読み込み
source 0_env.sh

# リソース作成
if [ "$1" == "--create" ]; then

  # リソースグループの作成
  echo az group create
  echo group create
  az group create --name $resourceGroup --location $region

  # NSG(ネットワークセキュリティグループの)作成
  echo az network nsg create
  az network nsg create --resource-group $resourceGroup --name $nsgName
  # コンテナレジストリ作成
  echo "acr create"
  az acr create -n $registryName -g $resourceGroup --sku standard --admin-enabled true

  # NSGルール(Public)
  echo az network nsg rule create
  az network nsg rule create \
    --resource-group $resourceGroup --nsg-name $nsgName --name ${nsgPubRuleName}1\
    --access Allow --protocol Tcp --direction Inbound --priority 100 \
    --source-address-prefix Internet --source-port-range "*" --destination-port-range $nsgPubInboundPort
  # レジストリユーザ名/パスワード取得
  acr_credential="`az acr credential show --name $registryName -o table | tail -1`"
  registryUser="`echo "$acr_credential" | awk '{print $1}'`"
  registryPwd="`echo "$acr_credential" | awk '{print $2}'`"

  # NSGルール(Public) SSH
  echo "az network nsg rule create(ssh)"
  az network nsg rule create \
    --resource-group $resourceGroup --nsg-name $nsgName --name ${nsgPubRuleName}2 \
    --access Allow --protocol Tcp --direction Inbound --priority 101 \
    --source-address-prefix Internet --source-port-range "*" --destination-port-range "22"
  # イメージのプッシュ
  echo "acr build"
  az acr build --registry $registryName --image $imageName .

  # 仮想ネットワーク 及び サブネット作成
  echo az network vnet create
  az network vnet create \
      --name $vnetName --resource-group $resourceGroup \
      --address-prefixes $vnetPrefix --network-security-group $nsgName \
      --subnet-name $vmSubnetName --subnet-prefixes $vmSubnetPrefix
  # App Service アプリ作成(Grafana)
  echo "create appservice plan and webapp"
  az appservice plan create -n ${webappName}-plan -g $resourceGroup --is-linux --sku B1
  az webapp create -g $resourceGroup -p ${webappName}-plan -n $webappName \
      --deployment-container-image-name ${registryName}.azurecr.io/${imageName}:latest

  # VM用の初期化シェルに含まれているシークレットID等を置換する
  cat 2_vm_setup.tmpl | sed "s/\$clientId/$clientId/g" \
      | sed "s/\$clientSecret/$clientSecret/g" \
      | sed "s/\$tenantId/$tenantId/g">2_vm_setup.sh
  # コンテナの構成/デプロイ(Grafana)
  echo "configure web app from Azure Container Registry"
  az webapp config container set \
      --resource-group $resourceGroup --name $webappName \
      --docker-registry-server-url http://${registryName}.azurecr.io \
      --docker-registry-server-user ${registryUser} \
      --docker-registry-server-password ${registryPwd} \
      --docker-custom-image-name ${registryName}.azurecr.io/${imageName}:latest

  # 仮想マシンの作成
  rm -rf  ~/.ssh/id_rsa
  rm -rf  ~/.ssh/id_rsa.pub
  echo az vm create
  az vm create \
    --resource-group $resourceGroup --name $vmName --image $vmImage --generate-ssh-keys \
    --vnet-name $vnetName --subnet $vmSubnetName \
    --private-ip-address $vmIpAddress --admin-username $vmUser \
    --public-ip-address-dns-name `echo $vmName | tr '[A-Z]' '[a-z]'` \
    --custom-data 2_vm_setup.sh

  # Grafana用のポート開放
  az vm open-port --resource-group $resourceGroup --name $vmName --port 3000

  # 生成されたSSH鍵を移動( --ssh-dest-key-path が効かない為 )
  mkdir -p pem
  if [ -e ~/.ssh/id_rsa ]; then
    mv ~/.ssh/id_rsa     ./pem/id_rsa_${vmName}
    mv ~/.ssh/id_rsa.pub ./pem/id_rsa_${vmName}.pub
  fi

  echo "Application URL: https://${webappName}.azurewebsites.net"
fi


# リソース削除
if [ "$1" == "--delete" ]; then
  echo az group delete
  echo group delete
  az group delete --name $resourceGroup
fi
}}

#html(</div>)
// END tabs1-1
// END tabs1-2

// START tabs1-2
#html(<div id="tabs1-2">)
// START tabs1-3
#html(<div id="tabs1-3">)

#mycode2(){{
#!/bin/bash
FROM grafana/grafana:7.1.1
COPY grafana.ini /etc/grafana/grafana.ini
}}

apt-get update
apt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common
#html(</div>)
// END tabs1-3

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
// START tabs1-0
#html(<div id="tabs1-0">)

apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io
grafana.ini を以下の通り編集する。
※テンプレートは https://github.com/grafana/grafana/blob/master/conf/sample.ini 等から取得。
#mycode2(){{

curl -L "https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
[server]
:
root_url = https://Grafanaアプリケーション名.azurewebsites.net
:

mkdir /tmp/grafana_docker && cd /tmp/grafana_docker
mkdir -p data/grafana && chmod 777 data/grafana
[auth.azuread]
name = Azure AD
enabled = true
client_id = クライアントID
client_secret = クライアントシークレット
auth_url = https://login.microsoftonline.com/テナントID/oauth2/v2.0/authorize
token_url = https://login.microsoftonline.com/テナントID/oauth2/v2.0/token
}}

cat <<_EOYML_>docker-compose.yml
version: "3"
※Grafanaアプリケーション名 は 0_env.sh で設定している $webappName。

services:
  grafana:
    image: grafana/grafana:7.1.1
    hostname: grafana_sample
    container_name: grafana_sample
    ports:
      - "3000:3000"
    volumes:
      - ./grafana.ini:/etc/grafana/grafana.ini
    environment:
      - GF_SERVER_ROOT_URL=http://localhost:3000
      - GF_SECURITY_ADMIN_PASSWORD=admin
_EOYML_
#html(</div>)
// END tabs1-0

# get grafana.ini template
docker run -d --name grafana_tmp --rm grafana/grafana:7.1.1
while [ true ]; do
  docker cp grafana_tmp:/etc/grafana/grafana.ini grafana.ini.tmpl
  if [ "$?" == "0" ]; then
    docker stop grafana_tmp
    break
  fi  
  sleep 2
done

# replace [auth.azuread] config
cat grafana.ini.tmpl | awk -v client_id="$clientId" -v client_secret="$clientSecret" -v tenant_id="$tenantId" '
BEGIN{
  target=0
}
{
  if ($1=="[auth.azuread]") {
    target=1
    print $1
  }
  if (target>1){
    target=target+1
    if (substr($1, 1, 1) == "[") {
      target=0
    } else {
      print
    }   
  }
  if (target==1){
    print "name = Azure AD" 
    print "enabled = true"
    print "client_id = "client_id
    print "client_secret = "client_secret
    print "auth_url = https://login.microsoftonline.com/"tenant_id"/oauth2/v2.0/authorize"
    print "token_url = https://login.microsoftonline.com/"tenant_id"/oauth2/v2.0/token"
    print "role_attribute_path = contains(groups[*], 'admin') && 'Admin' || contains(groups[*], 'editor') && 'Editor' || 'Viewer'"
    print ""
    target=target+1
  }
  if (target==0) {
    print
  }
}' > grafana.ini

# start grafana
docker-compose up -d
}}

#html(</div>)
// END tabs1-2

#html(</div>)
// END tabs1

#html(<script>$(function() { $("#tabs1").tabs(); });</script>)
#html(</div>)

** リソース作成 [#w558c42c]
#html(<div class="pl10">)
#myterm2(){{
./1_resources.sh --create
}}
#html(</div>)

#html(</div>)


* XXXXXXXXXX [#v8d82db4]
* 動作確認 [#ka88153d]
#html(<div class="pl10">)

grafana.ini (抜粋)
#mycode2(){{
[auth.azuread]
name = Azure AD
enabled = true
client_id = クライアントID
client_secret = クライアントシークレット
;scopes = openid email profile
auth_url = https://login.microsoftonline.com/テナントID/oauth2/v2.0/authorize
token_url = https://login.microsoftonline.com/テナントID/oauth2/v2.0/token
;allowed_domains =
;allowed_groups =
; 正常に動作しない (常に Viewer になってしまう )
;role_attribute_path = contains(info.groups[*], 'admin') && 'Admin' || contains(info.groups[*], 'editor') && 'Editor' || 'Viewer'
role_attribute_path = contains(groups[*], 'admin') && 'Admin' || contains(groups[*], 'editor') && 'Editor' || 'Viewer'
}}
ブラウザから https&#58;//Grafanaアプリケーション名.azurewebsites.net にアクセスして動作確認を行う。

#html(<div class="images">)
#html(<div class="ib">)
試しに Adminロールを割り当てたユーザでログインしてみる。
&ref(grafana-login1.png,nolink);
#html(</div><div class="ib">)
 
&ref(grafana-login2.png,nolink);
#html(</div><div class="ib">)
 
&ref(grafana-login3.png,nolink);
#html(</div><div class="ib">)
 
&ref(grafana-login4.png,nolink);
#html(</div><div class="ib">)
Admin 権限でログインされている事を確認。
&ref(grafana-login5.png,nolink);
#html(</div>)
#html(</div>)

* Azure AD認証を設定する [#n828409e]
#html(<div class="pl10">)
#html(</div>)

Azure AD OAuth2 authentication
https://grafana.com/docs/grafana/latest/auth/azuread/

* 補足 [#t61a4455]
#html(<div class="pl10">)
いちいち [Sign in with Microsoft] を押すのが面倒なのでプロキシを噛ませてHTTPヘッダで認証できないかやってみたが、 
Grafana の Auth Proxy は ロールマッピングには対応していない模様。
https://grafana.com/docs/grafana/latest/auth/overview/
#html(</div>)

Microsoft ID プラットフォームと暗黙的な許可のフロー (暗黙的な許可フローの有効有効化)
https://docs.microsoft.com/ja-jp/azure/active-directory/develop/v2-oauth2-implicit-grant-flow#send-the-sign-in-request

#mycode3(){{
ID トークンおよびアクセス トークンを正しく要求するには、Azure portal の [アプリの登録] ページのアプリ登録で、
 [暗黙の付与] セクションの [ID トークン] および [アクセス トークン] を選択して、対応する暗黙的な許可フローを有効にする必要があります。
それが有効でない場合は、unsupported_response エラーが返されます
}}


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS