I have an asp.net application that I'm attempting convert the front end to Angular. Getting header information is important to the view. I'm used to getting the header information like so in C#:
httpContext.Request.Headers["USERID"]
How can I do the same thing in an angular controller?
In asp.net each request runs in its own independent context and hence the header access as you have shown in your code make sense.
This does not hold good for angular or in fact any client side framework. You can always get the headers for any request or response made using angular $http but the question is which request? During the lifetime of the app you would make many such requests.
Let's say you want to get the current userid, you can create a service that returns the logged in user. There are two ways to implement such a sevice
create a method on server to return this data. Invoke this method from service and cache results
on the client side assuming there is a login request made through angular, implement a success callback method which can update the service with the logged user id.
You can look at $http documentation here to understand how to access headers.
Related
I tried to find a good solution, but have not found so far, so asking for advice.
I have MVC Core 'website' project + MVC Core 'API' project.
Website speaks to API and uses bearer token. When user authenticates at Website - it sends authentication request to API as well. Api sends bearer token back that is valid for some time. Website encapsulates bearer token to cookie and sends it to end user. When end user works with website, the website checks if user is authenticated basing on cookie.
Website cannot work without API and sends all requests that way. At some point API can return exception that indicates that bearer token is expired. So when website receives it - it needs to redirect user to login page again, so we get a new bearer token and a new cookie.
The question is how this could be done in a generic way. We do not know that bearer token is expired until we send request to API. So this situation could happen at any controller and any action.
What I currently have is a code like:
var apiResponse = await apiCommunicator.GetResponse(endpoint, content);
GetResponse returns entity like <Response<T>> - where Response is a generic class that contains all basic information about response (contains error, valid, etc.) and T - class that encapsulates data that we need from this API call.
I can easily extend Response class to include something like IsAuthenticationRequired flag. But the question is how could I finally make redirect in a flexible way.
Solution 1
Simple checking for this flag above and make RedirectToAction. But that does not look good as I need always to check it and duplicate code on each request. Easy to make mistake.
Solution 2
Implement exception that could be caught by a middleware. If middleware detects that exception is of type X - make redirect.
In this way middleware would look like
try
{
await _next.Invoke(context);
}
catch(MyAuthenticationException ex)
{ ... }
But that does not look too good as well - what if inside one of controllers the call to apiCommunicator would be surrounded by try-catch as well? In this case middleware would not catch anything.
Solution 3 - best choice so far
Issue website cookie to the period that is less than bearer token validity period. So far it looks like a best choice. But is this really the best way?
Any ideas about how this could be flexibly accomplished would be highly appreciated!
I wanted to put a situation to you to get your thoughts on the use of Flurl; if I have developed a restful api which is designed to support authentication and sessions from multiple users and you part of the operation of the restful service is that it needs to make authenticated calls to another outside service. If I used the standard flurl implementation of call asyn from a string URL and if I need to set different headers depending on the user that authenticated to my service, would this cause unpredictable behaviour due to it using a single httpclient (as they are all calling the same host).
Doing it the way you describe is completely safe. Setting headers fluently off a URL string or Url object will apply them to the request, not the client. Example:
await url.WithHeader(name, value).PostAsync(body);
This call can be made a zillion times from different threads with different header values and a single shared HttpClient instance with no conflicts. This works because under the hood it sets the header on the HttpRequestMessage, not the default headers on the HttpClient.
I'm working on a legacy ASP classic application. This application also supports an API, written in C# using Web API 2.
I'd like to add functionality to this API that will consume a request (as a resource - which will contain data need to satisfy a workflow), validate that request, and inside the API controller, generate a new request to an ASP page (the workflow is quiet complicated, so rather than re-write that logic, re-using the ASP page provides better business value).
Ideally I'd like to wait for the response inside the controller, and then pass back an Action Result (like a 204) to the consumer of the API.
The idea here is to hide the response of the ASP page, and return something simple to the consumer.
I know how to structure the URL somepage.asp?p1=help&p2=me, however I'm not sure how to create it as a request, execute it, and then consume the response within the API controller.
Is it even possible?
I want to submit a form using AJAX to a MVC 3 Controller.
The form and the controller are on two different domains, which is why i want to use CORS.
I have read that the following code should do the trick in ASP.NET:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
from http://enable-cors.org/#how-asp.net
Should this code go directly in the controller that takes the form data?
As far as i know, there has to be some exchange of data between the client posting data and the server, to determine wether CORS is enabled/supported or not, so i figure that the one line of code has to go somewhere else?
Thanks
This could go in the controller. Actually I would probably externalize it in a custom action filter to avoid repeating it in every controller action that needs to be invoked from a cross domain AJAX call. There are no additional steps necessary. Just make sure that your browser supports CORS because if it doesn't adding this line will have strictly no effect whatsoever.
My back-end server is built using the Microsoft WCF REST Starter Kit Preview 2. I want to add some request processing to all requests, except for those methods I explicitly disable by marking them with an attribute. I have over a hundred service methods and there are only a few I want to exclude from this extra processing. I'll tag them all if I have to, but I'm trying to avoid disrupting what's already written.
I haven't seen anything I can add to WebInvoke, and adding an interceptor won't let me examine the method that the request is routed to.
I am asking for an explanation of how to register HttpOperationHandler object(s) so I can do my extra request processing (i.e. authorization based on information in the request headers) before it is handed off to the method it was routed to. Can someone please explain how to do this, without rewriting my existing codebase to use Web API?
You can't use an HttpOperationHandler with WCF REST Starter Kit. However the Web API is very compatible with ServiceContracts that were created for WCF REST Starter kit. You should be able to re-host them in a Web API host relatively easily. You may have to change places where you access WebOperationContext, but it should not be a huge change.
I solved my problem by adopting another method. It authenticates all requests. I can't control which method it applies to, but I was able to work around that.
I created a custom ServiceAuthorizationManager class to process the Authorization header. The CheckAccess() method returns true to allow the request through or false if the user is not authenticated or not authorized to perform the service. I hooked it up to the ServiceHost for my services by creating a custom WebServiceHostFactory class and assigning an instance to the Authorization.ServiceAuthorizationManager in its CreateServiceHost() methods.
Although I can't directly check method attributes for the service being executed, the Message.Headers member of the object passed to CheckAccess() has a To property that contains the URI of the service being called. If necessary, I could examine it to determine what method the request would be routed to.
The ServiceAuthorizationManager applies to all requests, so no web methods or classes must be marked with any special attributes to enable it.