0

I have an ASP.NET application which has been working by creating a context to connect to a SQL Server 2016 database. So far it's been working great, but I've been tasked with adding javascript into the code to retrieve data from the database and display it to the user. I've heard connecting directly to the database through Javascript has security risks due to users being able to see the username and password, so I wanted to know if there's a safe alternative to direct connection that would have the Javascript code call server-side code and retrieve the data (stored in the database as JSON). I know AJAX is how to retrieve the code and have learned a decent amount about it, but I don't know how to get the connection string that AJAX needs to function. I've heard Node.js could work, but we already have a server stood up so I'm pretty confused. Any advice would be much appreciated!

Side note: I know there's already a good explanation of why a direct connection is bad here, but while the top answer says "A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others." they didn't explain how to connect through the server side with .NET

mightynifty
  • 149
  • 1
  • 13
  • 1
    https://learn.microsoft.com/en-us/sql/connect/ado-net/microsoft-ado-net-sql-server?view=sql-server-ver15 – Július Ľuptovec Jan 13 '21 at 14:39
  • 2
    "I've heard connecting directly to the database through Javascript has security risks due to users being able to see the username and password" - a better reason is because you physically can't. JavaScript running in a web-page **cannot connect to database servers** because JavaScript cannot create TCP Socket connections. – Dai Jan 13 '21 at 14:44
  • Nor would you publicly expose your database for random people to see - your database should be sitting behind a firewall, and only other connections from inside the firewall should be able to hit it. Plus - if JavaScript could do whatever it wanted to the database....don't you think that attackers might take advantage of that and just issue whatever SQL commands they wanted? `UPDATE USERS SET PASSWORD = 'haha'` or `UPDATE PRODUCTS SET PRICE = 1` come to mind. – mason Jan 13 '21 at 14:52
  • In general, when you have code that needs to interact with your server side, you write an HTTP API (or REST API). That could be in Node, but you mentioned this is already an ASP.NET site. Microsoft has ASP.NET Web API. That exposes HTTP endpoints for your client side code to call, and it's able to interact with the database since it would sit inside your firewall. The Web API would handle authentication and authorization to make sure clients can't just do whatever they want, but instead can only do what your authorize them to do.. – mason Jan 13 '21 at 14:54
  • You mentioned ASP.NET but didn't mention if you are using WebForms or MVC? – JuanR Jan 13 '21 at 14:58
  • @JuanR I'm using WebForms (legacy site and the older devs don't like change). – mightynifty Jan 13 '21 at 15:06
  • @JúliusĽuptovec Thanks, I'll check that out and see if it's what I'm looking for! – mightynifty Jan 13 '21 at 15:07
  • @mightynifty I posted an answer. I should have everything you need to get going. – JuanR Jan 13 '21 at 15:16

2 Answers2

1

When tasked with this sort of thing, the general idea is to defer loading of the data so that the page can load faster. You do this by loading the UI first, then fetching the data (via an AJAX call done with JavaScript).

With this in mind and generally speaking, you would do something like this:

  1. Code a method in your web form or controller, depending on the technology you are using, that loads the page without making a call to load the data. It simply loads the UI with placeholders.
  2. On the UI side, have a JavaScript function fire once the DOM has loaded. This function will make a call to another method on the backend that will provide the data (or even the HTML if you so desire) needed to populate the UI. this call will use a callback function that will be triggered when the data is received back from the server. This function will then populate the UI with the data.
  3. Back on your web form, controller, web service, web api or wherever you decide to host your data retrieving logic, you will code a method that will service the JS AJAX call. This backend method will then make the call (server side) to the database using the connection string safely stored in your web application and retrieve the data, then pass it back to the calling JS function, which will then fire the callback mentioned before and populate the UI.

There are plenty of examples out there as this is a common design pattern nowadays. You can find one here.

JuanR
  • 7,405
  • 1
  • 19
  • 30
-1

I actually found the solution I was looking for here (suggested by a coworker):

https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/

In case the link becomes invalid, the solution is to use Microsoft's Web API 2 with ASP.NET and EntityFramework. By creating Models and controllers in Visual Studio, you can create a context that can be reached with AJAX using routes defined in the RouteConfig access in the JavaScript like so:

var ViewModel = function () {
var self = this;
self.books = ko.observableArray();
self.error = ko.observable();

var booksUri = '/api/books/';

function ajaxHelper(uri, method, data) {
    self.error(''); // Clear error message
    return $.ajax({
        type: method,
        url: uri,
        dataType: 'json',
        contentType: 'application/json',
        data: data ? JSON.stringify(data) : null
    }).fail(function (jqXHR, textStatus, errorThrown) {
        self.error(errorThrown);
    });
}

function getAllBooks() {
    ajaxHelper(booksUri, 'GET').done(function (data) {
        self.books(data);
    });
}

// Fetch the initial data.
getAllBooks();

};

mightynifty
  • 149
  • 1
  • 13
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/28072661) – buzatto Jan 13 '21 at 19:51
  • Good point. It's way too much to add everything in one answer, but I did add enough to give others the opportunity to solve the problem (or at least know what to look for) in case the link dies. – mightynifty Jan 14 '21 at 16:40