Testing Web API functionality with Fiddler - c#

I am developing a c# web api application. I am trying to test the /Token (login) and the ChangePassword action. I was able to simulate the /Token request and get the access_token from the response. However, I am unsure of how to use fiddler to test the ChangePassword action. If I just pass the OldPassword, NewPassword and ConfirmPassword, I get an unauthorized error, which makes sense as I have AuthorizeAttribute set as a GlobalFilter. It seems like I have to somehow pass the access_token as well. My question is how do I pass the access_token with the other fields?

I've never used Fiddler for that, but if it's a restful service I would just use Postman (free Chrome extension) or a similar restful client. In Postman you just fill out the URL, click the Headers button and fill out 2 form fields (header/value) to add the access_token to the request.
Good luck

Related

Redirect to a page with api response in ASP.NET Core MVC

I have an api controller with a http GET method. This method is invoked from a frontend. In response to this, I want to redirect user to dashboard page and also provide some login response object. When a request comes into this method, it comes from a different page.
The request comes to this method with a path api/accounts/loginobject when a third party identity servers sends oauth2 authentication. This is a redirect url method.
[HttpGet]
[Route("LoginObject")]
public async Task<IActionResult> getLoginObject()
{
var externalLoginInfo = await this.signInManager.GetExternalLoginInfoAsync().ConfigureAwait(false);
// parse token here
}
I tried below code and it works. But I don't know if we can send response object in the below response. I want to attach token in the headers and some info in the response body.
// dashboard is a ui page not another controller action
return Redirect("/dashboard");
The front end app is an angular app part of ASP.NET Core MVC project. I have a third party identity server which sends oauth2 result back to this controller.
The following will set header but it will be lost when the redirection to html page /dashboard happens. Still I am not able to respond to ui with access token
this.Response.Headers.Add("Authorization", $"Bearer {accessToken}");
Update:
I solved this temporarily by passing token in query string. It looks more like a hack for now. Once received it in ui, i will set it in web app local storage for subsequent api calls.
https://mywebsite/accesstokencallback?access_token=eybcsdfk23klsd-3dsfjs

400 Bad Request error when simulating login with Postman on ASP.NET Core Web Application with individual user accounts stored in-app

Postman returns a 400 Bad Request error when trying to simulate a login request to an ASP.NET Core Web Application that has an authentication of individual user accounts stored in-app.
However, I am able to log in when using the default application template generated by Visual Studio. Using Chrome DevTools, it seems like the request is as follows:
Request URL: application/Identity/Account/Login
Request Method: POST
Content-Type: application/x-www-form-urlencoded
Form Data:
Input.Email: user's email address
Input.Password: user's password
__RequestVerificationToken: token
Input.RememberMe: user's selection of either true or false
I have unsuccessfully tried to simulate this using Postman as follows: Postman request headers and Postman request body
Postman returns a 400 Bad Request error without any additional information: Postman response with 400 error code
Please could you help me determine what is wrong in my request when attempting to simulate the login with Postman?
Edit: I did not write any custom code for this. It is the default template generated in Visual Studio. I tried looking for the function that gets called when I use the built-in login page
When I add a scaffold "Identity" to the project using Visual Studio, the login page is named Login.cshtml and it uses the default LoginModel. When I tried to debug with a breakpoint, I see that it calls a function named OnPostAsync in the LoginModel class.
However, when I use Postman, the breakpoint is not reached. Therefore, I think this may be because my current request structure is incorrect
Sometime this may help. Decorate your PageModel class with [IgnoreAntiforgeryToken(Order = 1001)]. The key is the Order parameter. The built-in [ValidateAntiforgeryToken] has an order of 1000, and therefore explicitly setting [IgnoreAntiforgeryToken] to anything greater than 1000 should resolve the issue.
refer - Disabling antiforgery token verification

How to send Bearer Token to different Website without Query String in C#/ASP.NET?

SSO/Oauth issue that I'm hoping is either simple, inexperience (probably) or just impossible.
I have Website A and Website B. Website A is under my control, and we currently use OAuth/OWin for SSO. Things work as intended, I can successfully make authentication/bearer tokens, all that jazz. Initially, to allow Website A credentials to be used for Website B, I'd pass the bearer token as a QueryString in the URL. The website would create and get the nessicary bits and bobs to get the Bearer token and stick it in a . User clicks the link, token is there in the URL.
What I'd like to do is take that information out of the QueryString/URL.
I've been looking at Request and Responses, using combinations of HttpWebRequest, Headers.TryAddWithoutValidation(), using Ajax calls to try and call Website B, and I still can't seem to get the token information over, even when I try to just use a dummy Website.
From my research, it seems like the answer is "Encrypt and pass it in a query string" or put it in the Authorization Header. But every example I see, shows that going to a API for validation and not passing it to another website login page. Anyone know any examples? Is this even possible without some weird inbetween?
If you want to remove it from the URL, you'll need to POST the token to Website B from Website A. The location you post to will need to be a server side endpoint that is prepared to look for the token and do something with it. You cannot POST to to a client side HTML page without it being in the URL.

Web API how to secure token when using IFrame on clientside

I have a ASP.NET Web API server application and Javascript frontend.
The way Im implementing authentication is by using a Token that is sent and received in the HTTP Response Headers.
When the users log into the application, my server will send back to the client a JSON object with a session Token. The javascript client then stores that in a browser cookie.
Every call that the javascript client makes to the server, the token is sent in to a custom header so the server can decrypt that and validate it in the database so it know if its a valid session.
Everything works great here, If I need to secure that part then adding a SSL will help.
Now, there are calls in the app that I need to use an IFrame so I set the src property to the web api method I need to call.
It's not possible to add a custom HTTP Header when using IFrame, just a simple URL into src property
Of course using this there is no way to send a custom header so what I did was to append a parameter into the scr url like this:
<iframe scr="/api/report/GenerateReport?sessionUid=" + getCookie('sessionuid') ></iframe>
This is my web api method that receives the sessionUid as a parameter.
[HttpGet]
public HttpResponseMessage GenerateReport(string sessionUid) {
// validates session
bool validSession = common.ValidateSession(sessionUid);
if (validSession) {
// do some stuff here
}
}
My question is... how can I secure my token, because if someone steals the sessionuid he then can call all the HttpGet methods that receives sessionUid as a parameter?
Any clue?
If your website is not using SSL, then you cannot 100% secure the communication between your website and user's browser.
Attackers usually hijack you whole HTTP package, including HTTP headers, put session in HTTP header is not enough for security.
The answer to your specific question is to encrypt the querystring parameters.

How to use external authentication services on a ASP.NET MVC Web Api

I'm developing an ASP.NET MVC Web Api with Visual Studio 2013, C# and .NET Framework 4.5.1.
I was reading this article and it is very interesting. It only talks about ASP.NET MVC applications and it doesn't say anything about how to implemented it with Web Api.
I think I can use it with Web Api but I don't know how because, as I read on the article, I will need a login page and a web api doesn't have one.
If I will consume that web api from mobile phones (iOS, Android, Windows Phone, etc.); what do I have to do?
Maybe I will need a login form on the mobile app, or maybe I will need a login page on my web api to allow login on Google, Facebook, etc.
Any advice?
#VansFannel, this is an old question and I'm guessing you have moved on, but I'm leaving this here for future seekers.
You are correct, it does not offer a login page, but it does offer what the login page itself would use.
Before I begin, go download a Chrome plugin called PostMan. I'll show a few screenshots as I go along using it. I've setup a basic WebAPI with the sample Values controller still in it, but protected with [Authorize]. I'm running my sample WebAPI at http://localhost:54211 for this example.
Here is a high level process:
Creating a User
I'm guessing your don't have any users in this new DB yet, but if you do just skip this. Otherwise, this is how you create them without a UI.
POST to http://localhost:54211/api/Account/Register
The post should be x-www-form-urlencoded, and should include the following fields:
email --- For example "test#somedomain.com"
password --- For example "Test123!"
confirmpassword --- For example "Test123!"
If the body is empty and the header status was 200, then it was successful:
If it failed, you'll get back a header status error of 400 and some kind of error in the body like:
Authenticating
Ok, we have a user in the database, lets authenticate with the WebAPI.
POST to http://localhost:54211/token
The post should be x-www-form-urlencoded, and should include the following fields:
grant_type --- Set it to "password"
username --- For example "test#somedomain.com"
password --- For example "Test123!"
In the results from the server, if successful (status 200), you will get back what is called a "Bearer Token" - its located in the "access_token" field like this:
For your test, copy that token value to the clipboard (in your app you could store this away in a variable).
Calling a WebAPI method with a Bearer Token
If you try to call an [Authorize] protected method without being authenticated, you will see something like this returned:
But you already authenticated, right? So why doesn't it know you anymore? Because it's REST based and it's stateless - it doesn't know you anymore after the call is complete. So, you have to "remind" it of who you are each time a call is made. You do this by passing the token you received earlier with every request.
Call the URL (http://localhost:54211/api/Values/) using whatever verb you need (GET,POST,etc). I'm using GET below, because in the ValuesController that is what is required.
In the Header of the request, I add the following field: "Authorization" and it's value as "Bearer [token]" where [token] is the token you stored away earlier.
If you get back a success (200) you can check it's body data and it will have your response:
And that is how it's done! I hope that helps you or others down the road.
Web api providees support for integrating with social networks like facebook, twitter, microsoft, google via the owin pipeline.
Find a sample here which provides facebook login support for a web api.

Categories

Resources