ASP.Net Ajax or API? - asp.net

[Not sure if this is the right place to ask this. If this question belongs on a different SO forum, please let me know.]
I am designing a web page that has a list of items which the user can drag up or down in the list. The user can also add new items to the list or delete items from the list. FWIW, I'm doing this in ASP.Net Core.
So, as the user interacts with the list, JS in the browser wants to call back to the server to tell it about list modifications. My two options (I think) are to call either Ajax or REST API endpoints on the server. Both schemes result in an asynchronous round-trip to the server, with a return value that indicates success or failure.
As I understand things, Ajax has the advantage that it comes with user authentication baked in. That is, I can easily enforce the notion that the caller must be an authenticated (logged in) user (the Ajax endpoint is no different than any other Controller GET or POST endpoint in this respect). The only real downside to using Ajax that I can think of is having to dream up a bunch of endpoint names for all of the various functions I need to expose. The bigger issue is that using Ajax for this just smells wrong to me.
A collection of REST API endpoints, on the other hand, come with some nifty semantics that make code maintenance and testing a bit easier to manage. But from what I've read, RESTful calls don't understand the concept that the caller has previously authenticated itself and owns a cookie to prove that.
As you can tell, I'm new to the world of REST APIs. I may be totally wrong about my assumptions around authentication and REST APIs. If that problem really is easy to work around, could some kind person post a simple example to lead me on my way...

I do something very similar in several places and use AJAX calls to my Controller Actions. You can get back pretty much anything you want from raw JSON to fully-rendered partial views and more. You have much better security (for the amount of time put in) than an API as well.
An upside to an API, if applicable, is if you want it to have public endpoints.

if I understand right you can use Signal R https://dotnet.microsoft.com/apps/aspnet/real-time its used for asynchronous notifications to client-side web applications

I agree that Restful APIs are testable and maintainable.
You can use JWT authentication for securing your Restful APIs, and it can be configured to return the bearer token only if the user is logged in.
And you can write your own ExtendAuthorizationFilter and register it into Startup.cs file.
services.AddMvc(
options => options.Filters.Add(new ExtendAuthorizationFilter())
).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
and
public class ExtendAuthorizationFilter : IAsyncAuthorizationFilter
{
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
//Your code here
}
}
here is JWT sample implementation with jQuery ajax.

Related

Authorising users in an ASP.NET (MVC5) web api project

Ok, so I'm struggling a little bit with trying to get a authentication process in my ASP.NET MVC5 (Web API 2) project. To start, here are some requirements:
I can't use Entity Framework (all access to the DB needs to be done through stored procedures)
Needs to target .NET Framework 4.5.2
I am not using ASP.NET Core
I would like to be able to use Bearer (or similar) tokens for authentication
I would like to invalidate tokens if a user logs out or automatically invalidate them after 24 hours
I would like to pass (and receive) XML when sending requests to the "login" (or "token") endpoint (note that ideally the solution should respect the "Content-Type" and "Accepts" headers, so if I send it JSON it should respond in JSON, and if I send it XML it should respond in XML)
I will not be using external providers (e.g. Google) anytime soon (maybe never)
I would like to use the <Authorize> attributes to help with protecting other endpoints
I am using VB.NET, although answers to this question can be in C# (I can convert them or rewrite them to suit)
I would like to store the tokens in the database so I can record which user is doing what within the API
(note that there are lots of reasons why I can't change the above)
I've tried to do this with Owin (OAuth) but I've found the following issues when comparing this to the requirements:
I can't seem to send the token endpoint any XML
Responses from the authentication endpoints (both successful and unsuccessful) are in JSON
I can't invalidate the tokens when logging out
I am happy to move away from OAuth if that is the best way to go for what I want. I would prefer to use Microsoft built nuget packages (ie no third party solutions) or I'm happy to partially roll my own solution (I would like to leverage as much of in-built or Microsoft built code, including Identity and Claims as possible so I can minimise testing efforts).
I have read numerous StackOverflow questions about this and search heaps on the internet, but most articles stick with OAuth despite the above issues or they rely on EntityFramework. My current solution uses the code from here (pretty much copy/pasted with some custom code in ApplicationOAuthProvider.GrantResourceOwnerCredentials()): https://www.codeproject.com/Articles/1187872/Token-Based-Authentication-for-Web-API-where-Legac
Thanks for the help!
I did some more extensive research and it looks like OAuth is not applicable for my specific situation. Although it seems like a nice authentication method, I really need to invalidate tokens via the DB, and I need the API to always send/receive XML (these are apparently not applicable when using OAuth).
To solve these problems, I have rolled my own token-based solution that creates a hashed token on the client side, so I never send passwords over the wire (which is a little bit nicer) because the token is generated on the client side (note that I am controlling what happens on the client side - these are all in house clients and I am writing the libraries these clients will use). This involved me creating my own filter which inherits System.Web.Http.AuthorizeAttribute.
If anyone stumbles across this question and provides a really good answer, I'm more than happy to mark theirs as accepted.

Linkedin Refreshing An Access Token

I've some troubles whit spring-social-api for linkedin. After 60 days access token expires and I can't use it to post on timeline of access token user. There is a way to pass this mistake?
Repeating my answer from http://forum.springsource.org/showthread.php?138943-Linkedin-refresh-accesstoken :
Although I can't honestly say I've tried it with LinkedIn, you should be able to obtain the connection (via a ConnectionRepository) and call refresh() on it. In fact, this should work with any OAuth2-secured API (except for Facebook who doesn't quite play by the OAuth2 spec).
I've not tried it with LinkedIn yet, because up until recently Spring Social was working with LinkedIn via their OAuth 1.0a authentication. But it sounds like a good thing to test.
Therefore, Spring Social supports refresh of access tokens. But it is a manual effort on your part to (1) catch the ExpiredAuthorizationException, (2) use ConnectionRepository to fetch the Connection, and (3) call refresh() to update the connection.
What would be more awesome is if Spring Social were to somehow catch that ExpiredAuthorizationException for you, automatically call refresh() and then reattempt the call that triggered the exception; making it seamless for the caller. That is something I've been pondering, but there's no implementation yet.
One possible solution is an aspect. But it'd need to be configured by the developer to properly wrap whatever API binding types (LinkedInTemplate, for example) the application is using. Another option I'm thinking over is to dig down into AbstractOAuth2ApiBinding and configure the RestTemplate that it exposes to handle that exception. It's a bit iffy on whether it can work, but if it does work, then any API binding that extends AbstractOAuth2ApiBinding would automatically get refresh capability...except, again, for Facebook who doesn't play by OAuth2 rules.

List currently logged in users in BlazeDS

I really need some expert help here!. Does anybody knows of a way of getting the list of the users currently connected to a BlazeDS server? Is there any built-in mechanism of knowing this? or do I have to implement some kind of server side logic every time a user access my Flex application and store all logged in users details somewhere and retrieve them later?
The nearest thing I can think of, using BlazeDS, is to obtain a list of clients currently subscribed to a destination, but this won't solve the problem IMO.
First of all, you need to define a destination and make sure that all clients will actually subscribe to it (see BlazeDS documentation for this). Then, on the server, you can then get a reference to the message service
MessageService messageService;
messageService = (MessageService) messageBroker.getService("message-service");
and ask for all subscribers with the getSubscribersIds method on the MessageService instance, specifying the name of your destination. This will only returns a number of identifiers, internally generated by BlazeDS (they are also available on the client side of the connection).
To resolve the same problem, I used this approach in combination to a custom server-side logic to store logged-in users (explicitly invoked login/logout methods). Regularly looking at the subscribers can help to clean this store, because in my experience there's no way to be sure that a "logout" method will always successfully called, expecially from Flex client running in the browser, while BlazeDS will automatically take care of cleanup of the subscribers.
I don't like very much this approach, probably someone came up with a better solution..

How can I pass FormsAuthentication.SetAuthCookie from Data Access Layer Class to WebService to Javascript?

I am using DotNetOpenAuth in my ASP.Net Website. I have modified it to work with Facebook Connect as well, using the same methods and database structures. Now I have come across a problem.
I have added a Facebook Connect button to a login page. From that HTML button, I have to somehow pull information from the Facebook Connect connection and pass it into a method to authenticate the user. The way I am currently doing this is by:
Calling a Javascript Function on the onlogin function of the FBML/HTML Facebook Connect button.
The javascript function calls a Web service to login, which it does correctly.
The web service calls my data access layer to login.
And here is the problem: FormsAuthentication.SetAuthCookie is set at the data access layer. The Cookie is beyond the scope of the user's page and therefore is not set in the browser.
This means that the user is authenticated, but the user's browser is never notified.
So, I need to figure out if this is a bad way of doing what I need or if there is a better way to accomplish what I need. I am just not sure and have been trying to find answers for hours. Any help you have would be great.
Yes, it sounds like you are having a design crisis brought on by trying to do too much at one time/in one place.
If you break this operation up in to two calls from the client you will find your options opening up quite a bit. It might take some more work but ultimately the code will be less complex. <-- a good thing.
And in my opinion, the first clue pointing to a crisis of design would be when I said to myself "Self, having an authentication method buried two calls deep in my DAL is not working the way I would like...." lol.... I am joking and serious same time.
Good luck.

Communication between pages

I want to enable an user to be able to communicate with other users through a site. I know that ASP.net is stateless, but what can I use for this synced communication? Java servlets?
I don't think you need to set up Java just to use a servlet for this. I would use AJAX and the database. I don't know ASP.NET but I PHP is similar in this case, being also basically "stateless". If you want to display some kind of asynchronous communication between two different users, say, from two different sessions, without a lot of refreshing (like chat), you can have the AJAX page constantly poll the database for new messages, and display them when they come in. You can also use AJAX to insert the new messages, giving the user read/write access to this messages data structure. Since the "other" user is doing the same thing, user A should see new messages pop up when user B types them in.
Is that what you mean?
You probably don't want to use sessions for things like chat messages but you probably could use some type of implementation of queueing using MSMQ.
The approach to chat could be done in many different ways, this is just a suggesting off the top of my head.
Could do a messaging solution in Java Servlets using the application context. Objects stored as attributes in the application context are visible from anywhere in your webapp.
Update: Chat like functionality... I guess that would be AJAX polling your message structure stored in the app context unless you want to use something like applets.
Don't know if it's any good, but there's a chat servlet here that might be useful to use or learn from if you decide to go the Java route...
ASP.NET is "stateless" but it maintains state using Sessions. You can use them by default just using the Session[] keyword.
Look at ASP.NET Session State for some details from Microsoft.

Resources