Last active
November 26, 2018 16:44
-
-
Save nlivaic/706ab05db84d201b5735d05815facb6b to your computer and use it in GitHub Desktop.
Authenticated Web API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment