{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Copyright (c) Microsoft Corporation. All rights reserved.\n",
        "\n",
        "Licensed under the MIT License.\n",
        "\n",
        "## Authentication in Azure Machine Learning\n",
        "\n",
        "This notebook shows you how to authenticate to your Azure ML Workspace using\n",
        "\n",
        " 1. Interactive Login Authentication\n",
        " 2. Azure CLI Authentication\n",
        " 3. Service Principal Authentication\n",
        " \n",
        "The interactive authentication is suitable for local experimentation on your own computer. Azure CLI authentication is suitable if you are already using Azure CLI for managing Azure resources, and want to sign in only once. The Service Principal authentication is suitable for automated workflows, for example as part of Azure Devops build."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/manage-azureml-service/authentication-in-azureml/authentication-in-azureml.png)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from azureml.core import Workspace"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Interactive Authentication\n",
        "\n",
        "Interactive authentication is the default mode when using Azure ML SDK.\n",
        "\n",
        "When you connect to your workspace using workspace.from_config, you will get an interactive login dialog."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "ws = Workspace.from_config()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Also, if you explicitly specify the subscription ID, resource group and resource group, you will get the dialog."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "ws = Workspace(subscription_id=\"my-subscription-id\",\n",
        "               resource_group=\"my-ml-rg\",\n",
        "               workspace_name=\"my-ml-workspace\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Note the user you're authenticated as must have access to the subscription and resource group. If you receive an error\n",
        "\n",
        "```\n",
        "AuthenticationException: You don't have access to xxxxxx-xxxx-xxx-xxx-xxxxxxxxxx subscription. All the subscriptions that you have access to = ...\n",
        "```\n",
        "\n",
        "check that the you used correct login and entered the correct subscription ID."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "In some cases, you may see a version of the error message containing text: ```All the subscriptions that you have access to = []```\n",
        "\n",
        "In such a case, you may have to specify the tenant ID of the Azure Active Directory you're using. An example would be accessing a subscription as a guest to a tenant that is not your default. You specify the tenant by explicitly instantiating _InteractiveLoginAuthentication_ with tenant ID as argument ([see instructions how to obtain tenant Id](#get-tenant-id))."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from azureml.core.authentication import InteractiveLoginAuthentication\n",
        "\n",
        "interactive_auth = InteractiveLoginAuthentication(tenant_id=\"my-tenant-id\")\n",
        "\n",
        "ws = Workspace(subscription_id=\"my-subscription-id\",\n",
        "               resource_group=\"my-ml-rg\",\n",
        "               workspace_name=\"my-ml-workspace\",\n",
        "               auth=interactive_auth)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Azure CLI Authentication\n",
        "\n",
        "If you have installed azure-cli package, and used ```az login``` command to log in to your Azure Subscription, you can use _AzureCliAuthentication_ class.\n",
        "\n",
        "Note that interactive authentication described above won't use existing Azure CLI auth tokens. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from azureml.core.authentication import AzureCliAuthentication\n",
        "\n",
        "cli_auth = AzureCliAuthentication()\n",
        "\n",
        "ws = Workspace(subscription_id=\"my-subscription-id\",\n",
        "               resource_group=\"my-ml-rg\",\n",
        "               workspace_name=\"my-ml-workspace\",\n",
        "               auth=cli_auth)\n",
        "\n",
        "print(\"Found workspace {} at location {}\".format(ws.name, ws.location))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Service Principal Authentication\n",
        "\n",
        "When setting up a machine learning workflow as an automated process, we recommend using Service Principal Authentication. This approach decouples the authentication from any specific user login, and allows managed access control.\n",
        "\n",
        "Note that you must have administrator privileges over the Azure subscription to complete these steps.\n",
        "\n",
        "The first step is to create a service principal. First, go to [Azure Portal](https://portal.azure.com), select **Azure Active Directory** and **App Registrations**. Then select **+New application registration**, give your service principal a name, for example _my-svc-principal_. You can leave application type as is, and specify a dummy value for Sign-on URL, such as _https://invalid_.\n",
        "\n",
        "Then click **Create**.\n",
        "\n",
        "![service principal creation]<img src=\"images/svc-pr-1.PNG\">"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The next step is to obtain the _Application ID_ (also called username) and create _password_ for the service principal.\n",
        "\n",
        "From the page for your newly created service principal, copy the _Application ID_. Then select **Settings** and **Keys**, write a description for your key, and select duration. Then click **Save**, and copy the _password_ to a secure location.\n",
        "\n",
        "![application id and password](images/svc-pr-2.PNG)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<a id =\"get-tenant-id\"></a>\n",
        "\n",
        "Also, you need to obtain the tenant ID of your Azure subscription. Go back to **Azure Active Directory**, select **Properties** and copy _Directory ID_.\n",
        "\n",
        "![tenant id](images/svc-pr-3.PNG)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, you need to give the service principal permissions to access your workspace. Navigate to **Resource Groups**, to the resource group for your Machine Learning Workspace. \n",
        "\n",
        "Then select **Access Control (IAM)** and **Add a role assignment**. For _Role_, specify which level of access you need to grant, for example _Contributor_. Start entering your service principal name and once it is found, select it, and click **Save**.\n",
        "\n",
        "![add role](images/svc-pr-4.PNG)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Now you are ready to use the service principal authentication. For example, to connect to your Workspace, see code below and enter your own values for tenant ID, application ID, subscription ID, resource group and workspace.\n",
        "\n",
        "**We strongly recommended that you do not insert the secret password to code**. Instead, you can use environment variables to pass it to your code, for example through Azure Key Vault, or through secret build variables in Azure DevOps. For local testing, you can for example use following PowerShell command to set the environment variable.\n",
        "\n",
        "```\n",
        "$env:AZUREML_PASSWORD = \"my-password\"\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import os\n",
        "from azureml.core.authentication import ServicePrincipalAuthentication\n",
        "\n",
        "svc_pr_password = os.environ.get(\"AZUREML_PASSWORD\")\n",
        "\n",
        "svc_pr = ServicePrincipalAuthentication(\n",
        "    tenant_id=\"my-tenant-id\",\n",
        "    service_principal_id=\"my-application-id\",\n",
        "    service_principal_password=svc_pr_password)\n",
        "\n",
        "\n",
        "ws = Workspace(\n",
        "    subscription_id=\"my-subscription-id\",\n",
        "    resource_group=\"my-ml-rg\",\n",
        "    workspace_name=\"my-ml-workspace\",\n",
        "    auth=svc_pr\n",
        "    )\n",
        "\n",
        "print(\"Found workspace {} at location {}\".format(ws.name, ws.location))"
      ]
    }
  ],
  "metadata": {
    "authors": [
      {
        "name": "roastala"
      }
    ],
    "kernelspec": {
      "display_name": "Python 3.6",
      "language": "python",
      "name": "python36"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}