Authenticated Web API
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<h3>Auth Request</h3>
<form id="userData">
<input type="text" name="email" placeholder="Name" />
<input type="password" name="password" placeholder="Password" />
<input type="password" name="confirmPassword" placeholder="Confirm Password" />
<input type="submit" id="register" value="Register" />
<input type="submit" id="login" value="Login" />
</form>
<button id="getPatients">Get Patients</button>
<pre id="output">
</pre>
<script>
$(function () {
var accessToken = '';
var login = function () {
var url = 'token';
var username = $('[name=email]').val();
var data = $('#userData').serialize();
data += '&username=' + username;
data += '&grant_type=password';
$.ajax(url, {
method: 'POST',
dataType: 'json',
data: data
}).then(saveAccessToken)
.always(writeResponse)
;
return false;
};
var saveAccessToken = function (data) {
accessToken = data.access_token;
};
var getPatients = function () {
var url = 'api/patients';
$.ajax(url, {
method: 'GET',
dataType: 'json',
headers: getHeaders()
}).then(writeResponse);
return false;
};
var getHeaders = function () {
if (accessToken) {
return {
Authorization: 'Bearer ' + accessToken
};
}
return {};
};
var writeResponse = function (data) {
var printout = JSON.stringify(data, null, 4);
$('#output').text(printout);
};
$('#login').click(login);
$('#getPatients').click(getPatients);
});
</script>
</body>
</html>