User.Identity.IsAuthenticated always false when calling from restSharp - asp.net-mvc

I have a web application in which I was authenticating user like below
$.ajax({
method: 'POST',
data: JSON.stringify(SaveDetails),
url: Utils.getWebApiUrl() + "/api/account/isLoggedIn",
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'bearer ' + access_token);
}
})
code in the controller below
[HttpPost]
[Route("api/account/isLoggedIn")]
public IHttpActionResult IsLoggedIn(Dictionary<string, string> Parameters)
//(string UserLoginLogId)
{
if (User?.Identity?.IsAuthenticated == true)
{
if (Parameters.Count() > 0)
{
string userLoginLogId = Convert.ToString(Parameters["UserLoginLogId"]);
string userRefreshToken = Convert.ToString(Parameters["userRefreshToken"]);
if (!string.IsNullOrWhiteSpace(userLoginLogId))
{
DocPro.DMS.BusinessLayer.IAccess.IUser a = (DocPro.DMS.BusinessLayer.IAccess.IUser)DALFinder.GetInstance(typeof(DocPro.DMS.BusinessLayer.IAccess.IUser));
//int LoginTimeOut = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Login-TimeOut"]);
if (a.IsLoggedInAsPerRefreshToken(Convert.ToInt64(userLoginLogId), userRefreshToken))
return Ok();
else
return NotFound();
}
else
return NotFound();
}
else
return Ok();
}
else
return NotFound();
}
and it was working fine, now I changed the code to the following
Dictionary<string, string> p = new Dictionary<string, string>();
p.Add("UserLoginLogId", Convert.ToString(userId));
p.Add("userRefreshToken", Convert.ToString(RefreshToken));
RestClient client = new RestClient(Convert.ToString(URL));
client.Timeout = -1;
RestRequest request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(p);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + accessToken);
IRestResponse<SPResponse> response = client.Execute<SPResponse>(request);
var result = JsonConvert.DeserializeObject<SPResponse>(response.Content);
but the following key "User?.Identity?.IsAuthenticated" is always showing false and I don't understand the reason.
while I do google I found a solution like below
var isAusorized = (Request.Properties["MS_HttpContext"] as HttpContextWrapper).User.Identity.IsAuthenticated;
but I don't understand how it worked and should I use this or not.

Related

JQuery ajax call blocks RedirectToAction

I have a view with an ajax call:
$.ajax({
url: "CreateChecklistCopies",
type: "POST",
data: JSON.stringify(drivers),
async: false,
contentType: "application/json; charset=utf-8",
});
The controller action performs some tasks and redirects to the index method of the controller:
[HttpPost]
public IActionResult CreateChecklistCopies([FromBody] object i_vm)
{
var tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChecklistCopyModel>>(i_vm.ToString());
int result = _obj.AddChecklistCopies(tmp);
if (result > 0)
return RedirectToAction("Index", new { SuccessMessage = "Checklists were successfully duplicated." });
else
return RedirectToAction("Index", new { ErrorMessage = "An error occurred when duplicating the checklist." });
}
The Index action is successfully executed but there's no forward to the index page happening:
[HttpGet]
public IActionResult Index(string FilterCreator, string salesPersonFilter, string SuccessMessage, string ErrorMessage)
{
if (FilterCreator == null)
{
FilterCreator = User.Identity.Name.Split("\\")[1];
}
else if (FilterCreator.ToLower() == "all")
{
FilterCreator = null;
}
var checklists = _obj.GetChecklists(true, FilterCreator, salesPersonFilter);
var salespersons = _obj.GetSalespersons();
var chlVm = _mapper.Map<List<ChecklistModel>, List<ChecklistListViewModel>>(checklists);
var ivm = new IndexViewModel
{
CheckLists = chlVm,
Salespersons = salespersons,
SuccessMessage = !string.IsNullOrEmpty(SuccessMessage) ? SuccessMessage : "",
ErrorMessage = !string.IsNullOrEmpty(ErrorMessage) ? ErrorMessage : ""
};
return View(ivm);
}
I played around with the async: false tag in the ajax call but that didn't help. Any ideas?
You cannot use RedirectToAction to action in an ajax call to redirect the entire page. Because the ajax response is limited to the ajax request scope only.
What you can do is return a json object instead of RedirectToAction like this:
[HttpPost]
public IActionResult CreateChecklistCopies([FromBody] object i_vm)
{
var tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChecklistCopyModel>>(i_vm.ToString());
int result = _obj.AddChecklistCopies(tmp);
JsonResult result = new JsonResult(new JsonSerializerSettings());
if (result > 0)
result = Json(new { IsRedirect = True, RedirectUrl = '/controller/Index/...', SuccessMessage = "Checklists were successfully duplicated." });
else
result = Json(new { IsRedirect = True, RedirectUrl = '/controller/Index/...', SuccessMessage = "An error occurred when duplicating the checklist." });
return result;
}
Then in the ajax call do this:
$.ajax({
url: "CreateChecklistCopies",
type: "POST",
data: JSON.stringify(drivers),
dataType: 'JSON',
async: false,
}).done(function (response) {
if (response != null) {
window.location = response.RedirectUrl;
//You can also use the IsRedirect and SuccessMessage property as needed
} else {
alert('There was a problem processing the request.');
}
}).fail(function () {
alert('There was a problem processing the request.');
});

"Value cannot be null.\r\nParameter name: input"

I made an ajax call. From ajax the values are passing exactly correct but I am getting that error. I try to find the reason, but failed to locate that.
I try to debug the code but it's showing nothing meaningful.
var obj = {
Mode: mode,
TissueRequestFeeID: mode == 1 ? 0 : data.TissueRequestFeeID,
TissueRequestID: viewBagRequestId,
FeeTypeID: data.FeeTypeID,
OtherFee: data.OtherFee,
Fee: data.Fee,
};
}
var TissueRequestFeeobj = {
TissueRequestFeeData: JSON.stringify(obj)
}
console.log(TissueRequestFeeobj);
var url = rootPath + "api/RequestApi/SaveAndUpdateRequest";
$.ajax({
url: url,
type: 'POST',
data: TissueRequestFeeobj,
success: function (TissueRequestFeeID) {
console.log(TissueRequestFeeID);
}
});
API code:
[System.Web.Http.HttpGet]
[System.Web.Http.ActionName("UpdateTissueRequestFee")]
public HttpResponseMessage UpdateTissueRequestFee(HttpRequestMessage request,int Mode, int TissueRequestFeeID, int TissueRequestID,
int FeeTypeID,string Fee,string OtherFee)
{
try
{
EISDataAccess objDAL = new EISDataAccess();
int i = 0;
SqlParameter[] p = new SqlParameter[7];
p[i] = new SqlParameter("#Mode", SqlDbType.Int);
p[i].Value = Mode;
i++;
p[i] = new SqlParameter("#TissueRequestFeeID", SqlDbType.Int);
p[i].Value = TissueRequestFeeID;
i++;
p[i] = new SqlParameter("#TissueRequestID", SqlDbType.Int);
p[i].Value = TissueRequestID;
i++;
p[i] = new SqlParameter("#OtherFee", SqlDbType.VarChar);
p[i].Value = OtherFee;
i++;
p[i] = new SqlParameter("#Fee", SqlDbType.VarChar);
p[i].Value = Fee;
i++;
p[i] = new SqlParameter("#CreatedBy", SqlDbType.VarChar);
p[i].Value = SessionManager.Current.UserDetails.AppUserId;
i++;
p[i] = new SqlParameter("#ModifiedBy", SqlDbType.VarChar);
p[i].Value = SessionManager.Current.UserDetails.AppUserId;
i++;
var RequestID = objDAL.ExecuteDataset(connectionString, CommandType.StoredProcedure, "Distribution_SaveRequest", p);
return request.CreateResponse(HttpStatusCode.OK, p[1].Value);
}
catch (SqlException ex)
{
return ProcessHttpRequestException(request, ex);
}
catch (Exception ex)
{
return ProcessHttpRequestException(request, ex);
}
}
You are passing TissueRequestFeeobj in your ajax call which contains an object with the key TissueRequestFeeData but in the action method, the attributes of `TissueRequestFeeData' have been mentioned as separate parameters. Hence you are getting null values.
Instead you should try passing JSON.stringify(obj) directly in the ajax call. Something like this:
var obj = {
Mode: mode,
TissueRequestFeeID: mode == 1 ? 0 : data.TissueRequestFeeID,
TissueRequestID: viewBagRequestId,
FeeTypeID: data.FeeTypeID,
OtherFee: data.OtherFee,
Fee: data.Fee,
};
var url = rootPath + "api/RequestApi/SaveAndUpdateRequest";
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify(obj),
success: function (TissueRequestFeeID) {
console.log(TissueRequestFeeID);
}
});

oauth web api call returns 403 forbidden

I implemented OAuth2 in my mvc web api project.I got the token but when I call the web api methods with this token the call will return 403 forbidden.I also called the same web api without the token it's working.Here is my token call:
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
AccountLogin LogCredentials = new AccountLogin();
LogCredentials.UserName = context.UserName;
LogCredentials.Password = context.Password;
LogCredentials.IPAddress = "::1";
string webHost = Convert.ToString(WebConfigurationManager.AppSettings["webHost"]);
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { webHost });
ProviderLoginResponse providerLoginResponse = MembershipService.UserLogin(LogCredentials);
if (providerLoginResponse.LoginStatus != "Y")
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return Task.FromResult<object>(null);
}
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Sid, Convert.ToString(providerLoginResponse.UserID)),
new Claim(ClaimTypes.Name, providerLoginResponse.UserName),
new Claim(ClaimTypes.Email, providerLoginResponse.UserEmail)
};
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(claims,
Startup.OAuthOptions.AuthenticationType);
AuthenticationProperties properties = CreateProperties(providerLoginResponse);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
return Task.FromResult<object>(null);
}
Here is my api method:
[HttpGet]
[Route("GetColumn")]
public HttpResponseMessage GetColumn(HttpRequestMessage request)
{
string tableName = "";
HttpResponseMessage response = null;
try
{
var clientList = _settingsService.GetColumns(tableName);
response = request.CreateResponse(HttpStatusCode.OK, new APIResponse { Status = true, Data = clientList, Message = Messages.Saved_Success });
}
catch (Exception ex)
{
response = request.CreateResponse(HttpStatusCode.OK, new APIResponse { Status = false, Data = null, Message = ex.Message });
}
return response;
}
My api call is :
function GetColumn(data, cb) {
var token = sessionStorage.getItem('accessToken');
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
$.ajax({
type: 'GET',
url: "api/Settings/GetColumn",
headers: headers
}).done(function (data) {
cb(data);
}).fail(function (Res) {
cb(Res);
});
};
I also tried the postman by passing the Authorization token but still got the 403.I searched the web for this problem but nothing will solve my problem .Why it is behaving like this?

Web api 2 - Async Post

I'm develop a web api2 where I post json data.
The code of this api is:
public HttpResponseMessage Post(an_lavanderie an_lavanderie)
{
var response = new HttpResponseMessage();
if (!ModelState.IsValid)
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception("modello non valido"));
}
bool creato = _repoLavanderie.CreaLavanderia(an_lavanderie);
if (creato == true)
{
response = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception("Errore nella creazione"));
}
return response;
}
This code write into db correctly.
My code to POST DATA is this:
var risultato = PostDataAsync();
and the function is
var lav1 = new Lavanderia()
{
rag_soc = "Ragione Sociale",
rag_soc2 = "Ragione sociale2",
indirizzo = "Via Crispi 27",
citta = "Ovada",
provincia = "AL",
isAttiva = "N",
portalkey = "sample string 1",
isPortalVisibile = "S",
cap = "15057"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56040/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/CreaLavanderia", lav1);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
MessageBox.Show("Crezione effettuata correttamente");
}
else
{
MessageBox.Show("Creazione non effettuata");
}
}
return "";
Post operation is ok, but when await don't fire.
Is possible that the return Message from webapi is not correct?
Where is the problem?
Thanks.
Since you are using await and you're saying that it's not firing make sure that your method is marked with the keyword async.

Forms authentication cookie is not persisting or is not getting past through an ajax request?

I am at a loss as to why my authentication cookie disappears. I am using Valums Ajax Upload in conjunction with a couple other ajax requests to build a user's avatar. It is very random as to when the cookie disappears. I can upload 4 files without an issue, then 2 files maybe (after another login). It seems after I call the CreateAvatar method, that is where there might be an issue, but like I said, it doesn't happen all the time. What am I missing?
JavaScript:
$(function () {
//This is the Upload Method
var fileCount = 0;
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/Avatar/AvatarUpload',
debug: true,
params: {
'userId': '#ViewBag.UserId'
},
onSubmit: function (id, fileName) {
fileCount++;
},
onComplete: function (id, fileName, responseJson) {
if (responseJson.success) {
//fileCount--;
if (createAvatar(responseJson.file, responseJson.imageId)) {
fileCount--;
} else {
fileCount--;
//alert('There was an error when trying to save ' + fileName);
}
} else {
$("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
fileCount--;
}
if (fileCount == 0) {
}
},
onCancel: function (id, fileName) {
fileCount--;
if (fileCount == 0) {
parent.$.fn.colorbox.close();
}
}
});
});
//This Creates the Avatar Object
function createAvatar(fileName, imageId) {
var avatarUploadModel = {
UploadFileName: fileName,
UserId: '#ViewBag.UserId',
ImageId: imageId
};
$.ajax({
url: '/Admin/Avatar/CreateAvatar/',
type: 'POST',
cache: false,
timeout: 100000,
data: JSON.stringify(avatarUploadModel),
contentType: 'application/json; charset=utf-8',
dataType: "json",
error: function (xhr, status, error) {
alert(error + " " + status);
},
success: function (data) {
if (data.success) {
loadAvatar(data.avatarModel);
return true;
} else {
return false;
}
}
});
}
//This loads the partial to view the avatar after upload
function loadAvatar(avatarModel) {
$.ajax({
url: '/Admin/Avatar/AvatarEdit',
type: 'GET',
cache: false,
timeout: 100000,
data: avatarModel,
dataType: "html",
error: function (xhr, status, error) {
alert(error + " " + status);
},
success: function (data) {
$("#avatarOriginal").html(data);
}
});
}
Login Method:
var user = _userService.GetByUserName(model.Username);
var authTicket = new
FormsAuthenticationTicket(1, //version
user.Id.ToString(), // user name
DateTime.Now,
DateTime.Now.AddMinutes(40), //Expiration
model.RememberMe, //Persistent,
user.Username);
var encTicket = FormsAuthentication.Encrypt(authTicket);
HttpContext.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return Json(new {success = true, url = model.ReturnUrl}, JsonRequestBehavior.AllowGet);
Upload Method on Controller:
[HttpPost]
public ActionResult AvatarUpload(HttpPostedFileBase fileData)
{
var id = Guid.NewGuid();
string fileName;
var serverPath = Server.MapPath("~/Areas/Admin/TemporaryUploads/");
if (fileData != null)
{
var fileRenamed = System.IO.Path.GetFileName(id + "_" + fileData.FileName);
fileName = Server.MapPath("~/Areas/Admin/TemporaryUploads/" + fileRenamed);
fileData.SaveAs(fileName);
}
else
{
var ajaxUploadFileData = Request["qqfile"];
fileName = Path.Combine(serverPath, id + "_" + Path.GetFileName(ajaxUploadFileData));
using (var output = System.IO.File.Create(fileName))
{
Request.InputStream.CopyTo(output);
}
}
return Json(new {success = true, file = fileName, imageId = id}, JsonRequestBehavior.AllowGet);
}
Create Avatar Method:
[HttpPost]
public ActionResult CreateAvatar(AvatarModel avatarModel)
{
try
{
var image = new WebImage(avatarModel.UploadFileName).Resize(400, 400, true);
var imageFileName = Path.GetFileName(avatarModel.UploadFileName);
var avatar = new Domain.YogaDiVitaContext.Model.Avatar()
{
CreatedById = Guid.Parse(HttpContext.User.Identity.Name),
ModifiedById = Guid.Parse(HttpContext.User.Identity.Name),
UserId = avatarModel.UserId,
Image = new Image()
{
CreatedById = Guid.Parse(HttpContext.User.Identity.Name),
ModifiedById = Guid.Parse(HttpContext.User.Identity.Name),
OriginalImageRelativePath = "original/" + imageFileName
}
};
var user = UserService.FindById(avatarModel.UserId);
if (user.Avatar != null)
RemoveAvatar(user.Avatar);
avatar = _avatarService.Create(avatar);
user.Avatar = avatar;
UserService.Update(user);
var basePath = Server.MapPath("~/" + avatar.ToAvatarBasePath(GlobalVariables.AvatarPath));
Directory.CreateDirectory(basePath);
Directory.CreateDirectory(basePath + "/thumbnail");
Directory.CreateDirectory(basePath + "/fullsize");
Directory.CreateDirectory(basePath + "/original");
image.Save(Server.MapPath("~/" + avatar.ToAvatarOriginalPath(GlobalVariables.AvatarPath)));
avatarModel.Width = image.Width;
avatarModel.Height = image.Height;
avatarModel.Top = image.Height*0.1;
avatarModel.Left = image.Width*0.9;
avatarModel.Right = image.Width*0.9;
avatarModel.Bottom = image.Height*0.9;
avatarModel.OriginalImagePath = "/" + avatar.ToAvatarOriginalPath(GlobalVariables.AvatarPath);
System.IO.File.Delete(avatarModel.UploadFileName);
return Json(new {success = true, avatarModel}, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
return Json(new {message = exception.Message}, JsonRequestBehavior.AllowGet);
}
}
Load Avatar Partial:
public ActionResult AvatarEdit(AvatarModel avatarModel)
{
return PartialView("AvatarCropPartial", avatarModel);
}

Resources