Not able to access protected Web-api after logging in to the default asp.net core web application template - identity

I have used the default web application template for ASP.NET Core and created an application (http://localhost:xxxx/).
Now I have added a new Web API Controller with path as api/test and default get method that returns a test string array and have decorated the API with Authorize attribute.
Now I have run the application and logged in with registered user.
Opened fiddler and tried to access the web API (http://localhost:xxxx/api/test/).
But it's redirecting me to login page. I have tried using the cookie authentication too but still not able to access Web API. Am I missing something here?
[Route("api/test")]
[Authorize]
public class TestController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}

When you log in from the browser, the browser itself will manage the cookie and use it as part of each subsequent request to the server -- even though you're local this is still the same workflow. You have specified that your entire class is to only accessible to Authorized requested, this means that it will redirect to the login screen if the request doesn't have the correct cookie.
Am I missing something here?
Yes, you're missing that fiddler doesn't know what cookie to use and it's disassociated from the browser. You must instruct fiddler to use the cookie for its request as explained here.

Related

Configure ASP.NET MVC to handle JSON

I´m working on an ASP.NET MVC project, that does the following:
Users collect data using an android app, this data is being sent as json. This app is under development by someone else, not me, but we´re in contact.
I created a JSONController with the following action:
[HttpPost]
public JsonResult PutJSON(JSONModel json){
// do something
}
My JSONModel only contains a public string LastName for testing purposes.
For now, I can only publish the project to IIS on localhost, which can be accessed from other devices in my home network. As far as I know, that should be okay for testing, right? The project is accessible and works when entering the ip of that machine in a browser on another device in network.
Is there anything else I need to do in my ASP.NET MVC project to make it accept AJAX calls from "outside"? Am I missing something?
I tried to test with a simple AJAX call from another device, but that´s just giving me internal server errors, because of cross domain call. Accepting those cross domain calls didn´t work though (do I need this when the project is finally being published?)
I´d be very thankful if someone could help, maybe by providing a link to a tutorial explaining how to configure ASP.NET project to accept AJAX calls from the internet.
Please take a look in the following question:
How to pass JSON POST data to Web API method as object
How to receive JSON data on WebAPI backend C#?
How to receive JSON as an MVC 5 action method parameter
How to receive JSON in asp.net web API?
Hope these will help you.

Liferay: Issue when Using JSON WebService and https

I have created a Liferay Web Service and made it accessible via JSON.
I call successfully call and use the JSON WebService using this URL:
https://localhost:8080/api/jsonws/my-portlet-name/my-method/time-unit/HOUR/class-name/TEST
I have annotated my Web Services like this:
#com.liferay.portal.security.ac.AccessControlled(guestAccessEnabled = true, hostAllowedValidationEnabled = false)
When I am using this call locally (http) I have no problems.
As soon as I deploy it to our test server (https) I do get "Forbidden - no permissions to access this resource".
What can I do to access my JSON Web Service calls ?
Ok, honestly : I don´t know if there is an answer for that ;)
I have used the Liferay.Service js call to do the same and it works.
So no more URL calling from jQuery ...

Dynamic Json result from RestAPI not being returned to Angular controller

I have Json data being pulled from a REST API. On success I have created a simple alert that will display the Json results inside of an $http.get. I found a sample URL that points to Json data online for testing and I get the alert with the results just fine. But when I try to do this with my URL pointing back to the api, I get no results (not even an alert). However, when I take that same URL and put it into the browser, all of my Json data is there. Any ideas or thoughts on what might be causing this issue? Thanks.
JavaScript (with test Json data)
var myApp = angular.module('paladinMonitor', ["highcharts-ng"]);
myApp.controller('SizeCtrl', function ($scope, $http, $timeout) {
$http.get('http://ip.jsontest.com/?callback=showMyIP').success(function (data, status) {
alert(data)
});
I had something similar happen to me. Restful web services must use the Access-Control-Allow-Origin header to specify what origins are allowed to access the service. Without it, you can hit the web service successfully by putting the address directly in your browser but it won't work from your app. If your REST service is written in Java, you can see this question for details on how to add the appropriate headers. Other languages will use a similar mechanism.
My other guess is that the web service requires authorization to access. It works fine from your browser because at one time you provided the proper credentials and
your browser cached them. If your service does require authorization, see the "Setting HTTP Headers" section on this page for information on how to add the appropriate headers.
As Alvin Thompson mentioned, you have to set your access-control-allow origin and should also set your access-control-allow-headers, access-control-allow-credentials on the server side. In my case I had to do this in my WebAPIcontroller. This is because in order for CORS to work (cross-domain) you have to have the service 1 (RESTApi in my case) allow permissions for service 2(client) to receive call it. In order, to allow this I had to add the following NuGet packages
NuGet
- Microsoft.AspNet.Cors NuGet package
- Microsoft.Owin.Cors NuGet package
Once these were installed I went to my config file on the API project and added
API App_Start/WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.EnableCors();
}
Then in my controller that inherits the API controller I referenced the NuGet package I installed and enabled CORS on the client side and this is where you set you origin, headers and methods
YourController : ApiController
namespace YourNamespace.Controllers
{
[EnableCors(origins: "https://localhost:.....", headers: "*", methods: "*")]
public class YourController : ApiController
{
//The rest of your controller functionality
}
}
The rest of the issue I was having was how the Json Web Token variable is being passed into my javascript file. I am still working on this, I will post the answer to this as well when I figure it out.
To read more about the CORS issue, this was the best reference for me: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

call json web api nopcommerce

Hi I am new for nopcommerce 3.5. I need to write a restful web service api to third party(for eg mobile) access the service. I know that we can access through Nop.Plugin.Misc.WebServices . I had enable the service from administrator site.
But now is my question. How can i call the web service for eg GetPaymentMethod , product list and etc
And if I want to write my custom web service by using web api. what is step to create? I cant find any documentation about the web service. Please guide me some example
Thanks
If you want a really quick start in writing a web service in NopCommerce, you can follow the MVC architecture and:
Create an Action method inside a Controller that you find appropriate for your purpose. For example, if you want access to a product list, you might create an Action inside CatalogController that follows the logic of the existing ProductList action.
Set up a Route in RouteProvider.cs to point to the Action you created. Based on this route you can deduce the URL of your service.
Do the processing that you need inside the Action. If this Action/service is to be called with parameters (in query string format: param=value&param2=value2), you can just put these parameters in the Action's header:
public ActionResult QuickService(int param, string param2) { ... and .NET will take care of having them initialized.
Store results in an object (can also be an anonymous object) and at the end of your action, return it as Json: return Json(resultsObject); Again, ASP.NET takes care of the JSON serialization and automatically sets the Content-Type HTTP response header to "application/json".
You can consume the service calling the URL that corresponds to the route of your Action.
If you want users to be able to log in, by using the above method, it gets a little bit trickier. You need the webservice client to be able to accept and send cookies, as well as make appropriate services for Login, Logout, Register,...
However, in this case, you might be better off with a mobile version of the site.
Final note: If you don't want to alter base NopCommerce code, you can apply the steps above to a plugin. The majority of NopCommerce plugins follow the MVC architecture, so you can apply the steps above.

Play Framework Secure Module: Login for JSON response interface

I'm using the secure module that is provided by the play framework. Now im trying to access a controller method that is protected by the secure module to get a JSON response. Is there a way to access this method without using the provided login form? e.g. with username and password as url parameter
Thanks, joe
Not directly, no. The Secure module is designed for UI based authentication. That said, building security around a controller using HTTP Authentication is pretty trivial.
There are a number of options, which depend on your use case on how to make this work. If you are building RESTful web services, then using HTTP Auth may be the way to go, but if you are using AJAX, that has already used the login page, then checking the cookie may be you answer.
If you look at the Http.Request object, you will see that it contains both a username and password fields. These are specifically used for HTTP authentication. So, you could have an action that does the following
public static void myJSONAction() {
if ("secretuser".equals(request.user) && "secret".equals(request.password)) {
// do some JSON
}
else {
// tell them they are not authorised to this content
unauthorized( "Secret Realm" );
}
}
Alternatively, if your JSON is used as AJAX on a website, I would be tempted to just check the secure module's cookie (take a look at the source to find the name of the cookie) to determine who the logged in user is.