Home > Software design >  How to MVC.Net project in Visual Studio to Connect to Azure SQL Database with Password less connecti
How to MVC.Net project in Visual Studio to Connect to Azure SQL Database with Password less connecti

Time:10-28

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 MVC.NET 4.8 version 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.

CodePudding user response:

I have created MVC .Net 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>;" }

Image for reference:

enter image description here

I added below packages to the project.

enter image description here

I added below code to connect 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;

Image for reference:

enter image description here

I write below query to retrieve data from 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; }
    }
}

Image for reference:

enter image description here

I set azure service authentication to retrieve the token credentials.

Image for reference:

enter image description here

I set myself as admin to the sql server.

Image 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

  • Related