Forms Authentication - token send to controller - c#

When I send this token to Controller in WebApi I get information 401 (Unauthorized) Why? I take this token form login and it`s correct.
$scope.expiresCookie = $cookies.get('expires');
$scope.issuedCookie = $cookies.get('issued');
$scope.access_tokenCookie = $cookies.get('access_token');
$scope.expires_inCookie = $cookies.get('expires_in');
$scope.token_typeCookie = $cookies.get('token_type');
$scope.user_nameCookie = $cookies.get('user_name');
$scope.addLink = "http://localhost:56305/api/ProductInsuranceCar";
$http({
method: "GET",
url: $scope.addLink,
headers: { 'Authorization': '' + $scope.token_typeCookie + ' ' + $scope.access_tokenCookie + '' },
headers: { 'Content-Type': 'application/json; charset=utf-8' }
}).then(function mySucces(response) {
$scope.test = response;
}, function myError(response) {
});
Picture 1
Picture 2
Example correct request
When I use Advanced Rest Client I get information but in my method :/ not working...

Correct answer. Position of header is important :/
headers: { 'Content-Type': 'application/json; charset=utf-8' },
headers: { 'Authorization': $scope.Authorization2 }

The problem could be when calling web api from a different UI domain.
Cookies are not sent if domains are different. So, If you call from localhost:64757 to localhost:56305 cookies are not sent, that's why you are receiving Unathorized 401 error.

Related

"Unsupported Media Type", 415 eror when post request in react-native

I'm trying to fetch my asp .net core api in react-native app. When i am testing wiht postman this api is working fine. But in react-native i have this eror.
["https://tools.ietf.org/html/rfc7231#section-6.5.13", "Unsupported Media Type", 415, "00-2608a636e0aeaf4bb2b29a2e1b54370a-2145e9063626d940-00"]
This is my api. I have tried public JsonResult but nothing change.
[HttpPost("register")]
public IActionResult Register([FromBody] TbPersonel model)
{
try
{
// SOME CASES
if (dt.Rows.Count > 0)
{
model.login = true;
return new JsonResult(model.login);
}
else
{
model.login = false;
return new JsonResult(model.login);
}
}
catch (Exception e)
{
Logla.Log(MethodBase.GetCurrentMethod().Name, ControllerContext.ActionDescriptor.ControllerName, e);
return new JsonResult(e);
}
}
React-Native
fetch('http:/.../api/login/register/',{
method:'post',
header:{
'Accept': 'application/json',
// 'Content-type': 'application/json'
'Content-Type': 'application/json; charset=utf-8'
},
body:JSON.stringify({
'kullaniciAdi': userName,
'sifre': userPassword
})
})
.then((response) => response.json())
.then((responseJson)=>{
console.log(Object.values(responseJson));
Postman Post request
Postman headers
The problem is in the parameters of fetch. fetch doesn't have any parameter named header but it's headers with an s. So, your code wasn't asking for the correct Content-type and Accept Headers. To fix this just add an s to the header key :
fetch('http:/.../api/login/register/',{
method:'post',
headers:{
'Accept': 'application/json',
// 'Content-type': 'application/json'
'Content-Type': 'application/json; charset=utf-8'
},
body:JSON.stringify({
'kullaniciAdi': userName,
'sifre': userPassword
})
})
.then((response) => response.json())
.then((responseJson)=>{
console.log(Object.values(responseJson));
Unfortunately, Javascript doesn't highlight this error.

Display website in I-frame via post method and pass header and body

I am trying to load a website in an I-frame. this is the first time I have to call the post method and pass a header and body.
This is my attempt with ajax.
$.ajax({
url: 'example.com',
type: 'post',
data: {
FirstName: "john doe"
},
headers: {
Token: "token"
},
dataType: 'json',
success: function (data) {
//console.info(data);
$("#output_iframe_id").attr('src', "/")
$("#output_iframe_id").contents().find('html').html(data);
}
});
I get a CORS error.
Access to XMLHttpRequest at 'https://localhost:44349/archive/statements' from origin 'https://localhost:44346' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
Update:
I used HttpClient and was able to pass the needed header and body. the site loads in the i-frame. However, the site does not behave correctly. I loose session data on additional calls to the server.
string jsonString = GetJsonString(req);
string url = example.com;
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Token", "token");
var clientRequest = new HttpRequestMessage()
{
Method = HttpMethod.Post,
Content = new StringContent(jsonString, Encoding.UTF8, "application/json")
};
var Res = await client.PostAsync(url, clientRequest.Content);
ViewBag.Statements = await Res.Content.ReadAsStringAsync();
}
Usage:
<div>
<iframe srcdoc="#ViewBag.Statements"></iframe>
</div>
I was finally able to get the ajax call working. I ended up adding a test page within the application itself and below is the working ajax call.
$.ajax({
url: 'example.com',
type: 'post',
data: {
FirstName: "john doe"
},
headers: {
Token: "token"
},
dataType: 'html',
success: function (data) {
$("#output_iframe_id").contents().find('html').html(data);
}
});
AS for the HTTPClient call. I found a few articles stating that HTTPClient doesn't return all HTML so I ended up focusing on the ajax call.

How to recieve and process AngularJS HTTP POST to C#?

I'm developing a web site associated to a SQL database and Azure web app. The app support authentication. For now, I'm able to login a user using Owin OAuthAuthorizationServerProvider class.
Here is the code I'm using to POST login data from my Angularjs file :
fac.login = function (user) {
var obj = {
'username': user.username, 'password': user.password,
'grant_type': 'password'
};
Object.toparams = function ObjectsToParams(obj)
{
var p = [];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
}
var defer = $q.defer();
$http({
method: 'post',
url: serviceBasePath + "/token",
data: Object.toparams(obj),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
userService.SetCurrentUser(response.data);
defer.resolve(response.data);
}, function (error) {
defer.reject(error.data);
})
return defer.promise;
}
And I deal with the data and identity by overriding : Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context).
This works perfectly. I'm now trying to create a "Sign In" page based on the same structure.
I think I know how to post the data with AngularJS like this :
fac.suscribe = function (newUser) {
var obj = {
'username': newUser.username, 'surname': newUser.surname, 'firstname': newUser.firstname,
'password1': newUser.password1, 'password2': newUser.password2, 'email': newUser.email, 'guid': newUser.guid
};
Object.toparams = function ObjectsToParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
}
var defer = $q.defer();
$http({
method: 'post',
url: serviceBasePath + "/register",
data: Object.toparams(obj),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response){
userService.SetCurrentUser(response.data);
defer.resolve(response.data);
}, function (error) {
defer.reject(error.data);
})
return defer.promise;
}
But I wonder how I can get the data to generate the post answer. Any idea on C#, preferably ?
First, You should have Model same with same property name on the server side. So that the property that you are sending in the object from angularjs will get binded to the Model Properties. Instead of having headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, change it to headers: { 'Content-Type': 'application/json' } for the Web API.
For your reference i am sharing this link
CRUD WITH ANGULARJS and ASP.NET WEB API

Web Api, ajax and Content Type

I would like to understand a little better about WebApi in Net and how is the correct way to called it with ajax. Little of info about my development environment: I am using .net 4.0 and visual studio 2010 and Jquery.
Model:
public class TestForm
{
public string FirstName { get; set; }
}
WebApi:
public class TestpController : ApiController
{
[HttpPost]
public HttpResponseMessage Post(TestForm form)
{
string jose = "jose";
return Request.CreateResponse(HttpStatusCode.OK, "yay");
}
}
Client side:
V1 (doesnt work, return error 405 ):
$.ajax({
url: "http://xxx/api/Testp",
type: "POST",
data: JSON.stringify({ FirstName: "Jose" }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log("success");
},
error: function (xhr, errorType, exception) {
console.log("error");
}
});
V2 (works):
$.ajax({
url: "http://xxx/api/Testp",
type: "POST",
data: { FirstName: "Jose" },
dataType: 'json',
success: function(data) {
console.log("success");
},
error: function (xhr, errorType, exception) {
console.log("error");
}
});
Why do I get an error when I add contentType: "application/json; charset=utf-8" and change the data to JSON.stringify({ FirstName: "Jose" }), but it works when I removed the content type and send a object in data option.
Short answer lies in the output of these alerts:
alert(JSON.stringify({FirstName :"Jose"}));
alert({FirstName :"Jose"});
The first one gives you a string, the second one gives you an object.
Your method:
public HttpResponseMessage Post(TestForm form)
Accepts an object and not a string. So when you post a string, .NET Framework is not able to find a method which can process a string, hence returns 405.
The Problem you are encountering seems to be jQuery preflight.
If you take a look at the Headers of your request you'll see that in V1 the Http Method used is actually OPTIONS. That is because jQuery does only allow certain values for the Content-Type Header.
#McBoman gave a good overview on this, at the linked source. You may also want to read up on Cross Origin Resource Sharing (Cors) for example this.
You need to add a Function that answers to [HttpOptions] and explicitly tells the preflight-request that a certain "custom"-Header is allowed or in the case of cross-origin request allowing the originating domain.
You would need to adapt the below Function to your needs, taking the info preflight provides you with.
[HttpOptions]
public HttpResponseMessage Options() {
var response = request.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("access-control-allow-origin", "*");
response.Headers.Add("access-control-allow-headers", "content-type");
return response;
}
Hope that helps you.

How to use AJAX to get the DB data in ASP.NET WebAPI Server with a Token Key

I've got a serious problems with WebAPI and Token Key in ASP.NET IIS Server, I can acquire data very easy without security issue.
However I cannot obtain anymore from sever when I set up the [Authorize] in the any Controllers , because I didn't put the Authorization messages in the HTTP head, so how to put it in that ???
There had dealt with my question about how to use Ajax to get a Token key from Asp.net WebAPI. Hopefully this example can help someone who has the same question like me.
The client code will like as following ,it can get Token key from server ,however you have to add the user profile data in DB table first and then using client code to send user/pwd to server ,if user/pwd is correct it will be sent token key back by server
<script>
var token;
$("#getToken1").click(function () {
var user = {
grant_type: 'password',
username: '***#gmail.com',
password: '!aA1234'
};
$.ajax({
type: 'POST',
url: 'http://localhost:65370/Token',
data: user,
success: function (data) {
var parsedResponseBody = JSON.parse(JSON.stringify(data));
token = parsedResponseBody.access_token;
}
});
});
</script>
when you get token key,you will be passing Authorization checking and then you can get data from server site, like as following code
<script>
$("#read1").click(function () {
$.support.cors = true;
$.ajax({
crossDomain: true,
url: 'http://localhost:65370/api/travels',
headers: {
'Authorization': 'Bearer ' + token
},
type: 'GET',
success: function (data) {
alert(JSON.stringify(data));
}
});
});
</script>
Reference from https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi

Categories

Resources