ASP.Net WebAPI Owin authentication token in Knockout - c#

I am trying to create a demo project which uses .Net ASP.Net WebAPI and KnockoutJs as the front end. I have created the controller methods that listen for the /token post, and validates a user, and returns a token. This is done from an Ajax Post from the Knockout View Model.
This code works. However, when I get 200 back (Success) from the webApi, I then redirect to a controller method, decorated with a [Authorize]. And that's where I hit a 401 - not authorised.
Login()
{
var data = {
username : this.login.emailAddress(),
password : this.login.password(),
RememberMe: this.login.rememberMe(),
grant_type: "password"
}
return $.ajax({
type: "POST",
data: data,
dataType: "json",
url: "/token",
contentType: "application/json"
}).done((reply) => {
window.location.href = "/Home/AnotherThing";
});
}
I think the issue is - I get a response back from my /token (login) call, but do nothing with it. I'm not sure what to do with the token. I stupidly thought that OAuth would somehow put the token into my headers, and they would be there magically. I was wrong.
So, I've been looking for an example, and then best I can find is Here
But this means I am going to have a LOT of repeated code, on each view model
Extract:
function ViewModel() {
var self = this;
var tokenKey = 'accessToken';
var RefTokenKey = 'refreshToken';
self.result = ko.observable();
self.user = ko.observable();
self.token = ko.observable();
self.refreshToken = ko.observable();
function showError(jqXHR) {
self.result(jqXHR.status + ': ' + jqXHR.statusText);
}
self.callApi = function () {
self.result('');
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
$.ajax({
type: 'GET',
url: '/api/values',
headers: headers
}).done(function (data) {
self.result(data);
}).fail(showError);
}
self.callToken = function () {
self.result('');
var loginData = {
grant_type: 'password',
username: self.loginEmail(),
password: self.loginPassword()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).done(function (data) {
self.user(data.userName);
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
var tkn = sessionStorage.getItem(tokenKey);
$("#tknKey").val(tkn);
}).fail(showError);
}
}
var app = new ViewModel();
ko.applyBindings(app);
This seems to be part of what I am missing:
sessionStorage.setItem(tokenKey, data.access_token);
var tkn = sessionStorage.getItem(tokenKey);
$("#tknKey").val(tkn);
Would I need every view model to have the code that then goes to the sessionStorage, and get the token?
So, this:
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
$.ajax({
type: 'GET',
url: '/api/values',
headers: headers
}).done(function (data) {
self.result(data);
}).fail(showError);
}
It seems like a lot of code.. Is this the right way to go?

Ok, so what you could do is attach the bearer token to each of your HTTP requests. I assume you're using jQuery there? If that's the case you could leverage the beforeSend config param.
Extract a reusable method such as this:
function onBeforeSend(xhr, settings) {
var token = sessionStorage.getItem(tokenKey);
if (token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token );
}
}
And then simply attach that method to each of your $.ajax calls that require the token, like this:
$.ajax({
type: 'GET',
url: '/api/values',
headers: headers,
beforeSend: onBeforeSend
}).done(function (data) {
self.result(data);
}).fail(showError);
The onBeforeSend function obviously needs to be accessible by your ajax call (I'm not a knockout guy so I don't know if it has any constructs such as services, but if not, you could namespace it for example to avoid making it a global function, but your code organization is up to you).
This way you'll only have to add the beforeSend: onBeforeSend bit to each request that requires auth and it will avoid unnecessary code duplication.

Related

How to pass bearer token into request header

It's my first time building a web api. I've successfully set up the model view controller and enabled token generation. However, I am stuck on how to pass the access token through the request header. After I have logged in and attempt to view another page, there is nothing in the header in regards to the authorization therefore I receive a 401 error. I've looked at several blogs, forums and articles over the past couple days and cannot come to a conclusion on how this is done. I have my jquery storing the header in a variable, but I am unsure on where that is stored and how to reference it or where to put the reference. I've messed around with setting it in global.asax and some of the config files, also at the top of the controller class. My next thought is to create a web page for each controller and storing the authorization there, even still I don't know how to dynamically place a token that would vary for other users. I feel like there is something very simple that I'm missing. I suppose my question is how do I store my javascript variable in each request header? Here is my javascript for reference:
$("#btnLogin").on('click', function () {
//var data = { Email: $("#loginEmail").val().trim(), Password: $("#textPwd").val().trim(), ConfirmPassword: $("#loginPwd").val().trim() };
$.ajax(
{
url: "/TOKEN",
type: "POST",
data: $.param({ grant_type: 'password', username: $("#loginEmail").val(), password: $("#loginPwd").val() }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
success: function (resp) {
sessionStorage.setItem('userName', resp.userName);
sessionStorage.setItem('accessToken', resp.access_token);
var authHeaders = {};
authHeaders.Authorization = 'Bearer ' + resp.access_token;
$.ajax({
url: "https://localhost:44327/api/values",
type: "GET",
headers: authHeaders,
success: function (response) {
$("#loginEmail").val(),
$("#loginPwd").val(),
$("#msg").text(response)
}
});
},
error: function () {
$("#msg").text("Authentication failed");
}
})
});

MVC RedirectToAction Doesn't Work After JSON Post Return

I am trying to change the page after post process of the AJAX process which executes by MVC. I have used it different way maybe my usage might be wrong.
C# MVC code part. I am sending int list which is user list and process and do something.
[HttpPost]
public ActionResult SelectUserPost(int[] usersListArray)
{
// lots of code but omitted
return JavaScript("window.location = '" + Url.Action("Index", "Courses") + "'"); // this does not work
return RedirectToAction("Index"); // this also does not
return RedirectToAction("Index","Courses"); // this also does not
}
My problem is redirect part do not work after the MVC process ends. Process works, only redirect doesn't.
JavaScript code here
// Handle form submission event
$('#mySubmit').on('click',
function(e) {
var array = [];
var rows = table.rows('.selected').data();
for (var i = 0; i < rows.length; i++) {
array.push(rows[i].DT_RowId);
}
// if array is empty, error pop box warns user
if (array.length === 0) {
alert("Please select some student first.");
} else {
var courseId = $('#userTable').find('tbody').attr('id');
// push the id of course inside the array and use it
array.push(courseId);
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
}
});
Added this to AJAX and it is not working too
success: function() {
window.location.href = "#Url.Content("~/Courses/Index")";
}
Once you are using AJAX the browser is unaware of the response.
The AJAX success in its current form failed because redirect response code is not in the 2xx status but 3xx
You would need to check the actual response and perform the redirect manually based on the location sent in the redirect response.
//...
success: function(response) {
if (response.redirect) {
window.location.href = response.redirect;
} else {
//...
}
}
//...
Update
Working part for anyone who need asap:
Controller Part:
return RedirectToAction("Index","Courses");
Html part:
$.ajax({
url: "/Courses/SelectUserPost",
type: "POST",
data: JSON.stringify(array),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Successful!");
window.location.href = "#Url.Content("~/Courses/Index")";
}
});
Just deleted
dataType: 'json'
Part because I am using my own data type instead of JSON.

ajax request to razor page using handler

I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});

$http post passing value as null to Asp.Net Web API

I have a ASP.Net web API with one post method. I'm calling the post method from angular js. It is not passing me the data to API POST method, All my properties of my requestData object is null. I'm not sure what is the mistake am doing here. Can anyone help me plz.
API Code
public void Post(RequestData data)
{
.....
}
public class RequestData
{
PropertyDetail propertyDetails;
ICollection<Model1> model1s;
ICollection<Model2> model2s;
ICollection<Model3> model3;
ICollection<Model4> model4;
}
Client Code
var requesData = new RequestData();
requesData.model0= $scope.model0;
requesData.model1s= $scope.models;
requesData.model2s= $scope.model2s;
requesData.model3s= $scope.model3s;
requesData.model4s= $scope.model4s;
$http({
method: 'POST',
url: window.apiUrl,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: requesData,
}).then(function (res) {
console.log('succes !', res.data);
window.alert("Successfully created");
}).catch(function (err) {
debugger;
console.log('error...', err);
});
Probably, your server side couldn't map your parameters correctly. Data type matching is important while post some parameters. You can change your client code like this:
...
contentType: "application/json; charset=utf-8",
data: JSON.stringify(requestData),
dataType:'json',
...
After doing as #Jaky71 says, you can learn how .net expects those objects by calling dummy methods with nulls or whatever you nees to mimic.
.net has a strict parser
You can use angular.toJson:
$http({
method: 'POST',
url: window.apiUrl,
headers: { 'Content-Type': 'application/json' },
data: angular.toJson(requesData),
}).then(function (res) {
console.log('succes !', res.data);
window.alert("Successfully created");
}).catch(function (err) {
debugger;
console.log('error...', err);
});
Also make sure that your properties match.

AJAX Call not hitting Controller Method - ASP.NET MVC

I've tries setting breakpoints at the Controller method. But it does not stop there. The alerts "clicked" and the next one work perfectly fine. But the controller method is not called. Any help is appreciated. Here's my ajax call and my controller method.
var Url = "#Url.Action("~/Home/Get_Location")";
$("#gotoloc").click(function() {
alert("clicked");
alert(lat +" "+ lon);
$.ajax({
type: "POST",
url: Url,
data: {
latitude: lat,
longitude: lon
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Hello:" + response)
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
alert("ignored");
});
public JsonResult Get_Location(double latitude,double longitude)
{
string loc = latitude + "/" + longitude;
return Json(loc, JsonRequestBehavior.AllowGet);
}
You are using the Url.Action method incorrectly.
Try this
var Url = "#Url.Action("Get_Location","Home")";
The above overload takes the action method name as first parameter and controller names as second parameter
Also, i see you are passing incorrect contentType request header. contentType headers tells the server what is the type of data the client is sending. Your current code says you are sending json data. But you have 2 parameters in your action method and the json serializer will fail to properly map the posted data to it, hence you will be getting a 500 response from the server.
This should work, assuming there are no other js errors in your page
var url = "#Url.Action("Get_Location","Home")";
$.ajax({
type: "POST",
url: url,
data: { latitude: 44, longitude: 55 },
success: function (response) {
console.log("Hello:" + response);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});

Categories