Skip to content

Instantly share code, notes, and snippets.

@nlivaic
Last active November 26, 2018 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nlivaic/706ab05db84d201b5735d05815facb6b to your computer and use it in GitHub Desktop.
Save nlivaic/706ab05db84d201b5735d05815facb6b to your computer and use it in GitHub Desktop.
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment