2

I want to find a solution to connect to the Azure SQL database without passcode by utilizing the Azure Managed Identity.

I have done the setup on Azure based on the following document. However there are two issues.

https://learn.microsoft.com/en-us/samples/azure-samples/azure-sql-db-who-am-i/azure-sql-db-passwordless-connections/

  1. I am using ASP.NET MVC on .NET 4.8, so I can't copy the code from the solution.
  2. I also want to find the solution that once the code and setup is done, I do want test out the connection locally.

With some material/code here if you could also give some explanation that would be great.

1 Answer 1

3

I have created an ASP.NET MVC webapp in Visual Studio. I have given connection string in appsetting.json file as:

"ConnectionStrings": {
    "QuotesDatabase": "Server=tcp:<servename>.database.windows.net,1433; Database=<databasename>;" }

Screenshot for reference:

enter image description here

I added below packages to the project.

enter image description here

I added this code to connect to the Azure SQL database:

var connectionString = Configuration.GetConnectionString("<connectionstringname>");
            services.AddTransient(a =>{
                var sqlConnection = new SqlConnection(connectionString);
                var credential = new DefaultAzureCredential();
                var token = credential
                        .GetToken(new Azure.Core.TokenRequestContext(
                            new[] { "https://database.windows.net/.default" }));
                sqlConnection.AccessToken = token.Token;
                return sqlConnection;

Screenshot for reference:

enter image description here

I write this query to retrieve data from the Azure SQL database:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace SqlMSI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class QuotesController : ControllerBase
    {
        private readonly string connectionString;

        public QuotesController(SqlConnection dbconnection)
        {
            DbConnection = dbconnection;
        }

        public SqlConnection DbConnection { get; }
      
        public async Task<IActionResult> Get()
        {
            DbConnection.Open();
            var sqlCommand = new SqlCommand("select * from quote", DbConnection);
            var reader = sqlCommand.ExecuteReader();
            var quotes = new List<Quote>();

            while (reader.Read())
            {
                var quote = new Quote()
                {
                    Id = Guid.Parse(reader["Id"].ToString()),
                    QuoteNumber = int.Parse(reader["QuoteNumber"].ToString())
                };
                quotes.Add(quote);
            }

            return Ok(quotes);
        }
    }

    public class Quote
    {
        public Guid Id { get; set; }
        public int QuoteNumber { get; set; }
    }
}

Screenshot for reference:

enter image description here

I set Azure Service authentication to retrieve the token credentials.

Screenshot for reference:

enter image description here

I set myself as admin to the SQL Server.

Screenshot for reference:

enter image description here

I added client IP address to the sql server Image for reference:

enter image description here

It run successfully and connected to azure sql database and retrieve the data from database.

Image for reference:

enter image description here

I Published the project into Azure app services

Image for reference: enter image description here

enter image description here

enter image description here

Add Ip address of webapp in azure to the sql server.

enter image description here

Set system assigned manage identity in on state of Azure app service.

enter image description here

I open SSMS and login the server using active directory password option.

enter image description here

I created user and added roles to the user using below code

create user [quotes-app] from external provider;
alter role db_datareader add member [quotes-app];
alter role db_datawriter add member [quotes-app];

image for reference:

enter image description here

enter image description here

successfully connected to the app without using userid password.

Image for reference:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I am moved on to store the connection string in Azure key vault secret but I will give your solution a try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.