Client application login using httprequest - asp.net

I am a bit new to ASP.NET and web development, and I am still confused about the following :
On the one hand I have a very complete ASP.NET MVC website based on NopCommerce that includes login, registration, e-commerce features, forums, etc.
On the other hand, I have a Windows Forms client application that needs to read and write data from and to my website database.
The first thing I would need to do is to allow users to login in the client application by sending a request to the server. I've been looking around the web for days and I can't manage to find a precise and secure way to do so.
I'm pretty much sure that I have to use System.Net.Http to make a request from the client. Will this request then got to be handled by a MVC controller action ? Maybe an already existing one ?
Here is the method I have so far, based on a tutorial found online (it is not complete at all) :
private static async void PostRequest(string addressPost)
{
IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("Query1", "Email"),
new KeyValuePair<string, string>("Query2", "Password")
};
HttpContent formContent = new FormUrlEncodedContent(queries);
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.PostAsync(addressPost, formContent))
{
using (HttpContent content = response.Content)
{
string myContent = await content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(myContent);
}
}
}
}
Any existing example or help would be greatly appreciated.

first we need to focus on the architecture of the application, we have here two applications, 1) web application, 2) WinForm application. and you want to share the same db for both, here are the drawbacks of doing so, you might found yourself one day your winform will lock a table because of updating etc, and your web application will lose access, thats not a good idea,
here is how i would do it.
create a web api plugin for your web application, and use api tokens for security, there is some available web api plugin for nopcommerce but its limited in functionality, so i guess you will have to add some methods based on your needs, next thing you will do is have your winform application communicate with your webapi, in that case your winform works independently and secure,
as a side note, you can have in your web api multiple tokens for each user if you want, you can manage that in your web api plugin, just make a table where you will store that info with user info and tokens for everyone and you can manage that from the web admin.

Related

Is it possible to restrict access to REST API built using Web API 2?

I built a REST API using ASP.NET Web API 2, so I could deliver data from a backend database to my applications running on any platform (mobile, web, desktop etc) However up until now, I simply call the website with the controller I need data from and that's it, it sends back the JSON string in the response.
But, the data is kind of special, and there is nothing to prevent another developer from simply calling the controllers and getting back the exact same data and building their own application around it.
My question is - is there anyway to restrict access to the API so that only my applications can get valid response from the server. (i.e. prevent other developers from using my REST API)
I already read these documentation Security, Authentication, and Authorization in ASP.NET Web API I'm just not sure which of these scenarios apply to me, or if any will do what I am asking.
EDIT - Another piece of info, my web service is running on Azure in case it is relevant.
Did you happen to check token based authentication?Please go through https://stackoverflow.com/a/38670221/4868839 and https://www.youtube.com/watch?v=rMA69bVv0U8 must be a good to start with.
there are different way to validate your web api.
Authentication Filters in ASP.NET Web API 2
using you can customise your authentication filter
you can refer sample Reference link
Token Based Authentication using ASP.NET Web API 2, Owin, and Identity
//App_Start/Startup class
public void ConfigureAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/v1/accesstoken"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(AppConfiguration.AccessTokenExpireDuration),
Provider = new SampleOAuthProvider() // class that override your method
};
// Token Generation
app.UseOAuthBearerTokens(OAuthServerOptions);
}
You can find reference from inherits Default implementation of IOAuthAuthorizationServerProvider used by Authorization
i hope it sholud helps you thanks.

Access Sharepoint Online document list through ASP.NET

I have been searching for quite sometime on this topic without finding the silver bullet. We have an intranet solution in ASP.NET where we simply want to show some files from our Sharepoint Online in Office 365.
There are a number of hits when you search for it on Google but nothing seems to be the "simple" way to go. I'm not a Sharepoint developer, but have a good understanding of the concepts as I manage our company's Office 365 and Sharepoint Online installations.
I have found current answers that tell me that REST services is the way to go, but here I need an OATH token to access them, and this is where my Sharepoint knowledge is limited. From what I have read the token can only be granted through an installed Sharepoint App, but I know for a fact that it can be done without it too.
I have purchased a synchronization tool that syncs our file share with a Sharepoint Document List and for this I don't need any tokens, I just type in my credentials and I don't have to install anything in Sharepoint.
So what am I seeking to get from this question?
Someone who knows Sharepoint well to steer me in the right direction and who maybe has a guide and knows that that method works. Maybe REST is the right way to go, but it just seems odd that my Sync software can do it without then.
If I do need to install a token granter in Sharepoint a little assistance in what to be aware of securitywise and how to approach it the best way.
Any help is greatly appreciated and thanks in advance! :)
Microsoft has two set of APIs that can access SharePoint Online:
SharePoint Client Object Model (CSOM):
With this one you can just use username and password to do authentication. follow the link you can find examples of how to access document list.
SharePoint REST API:
With this you need to use an OAuth token to do the authentication.
For you case, you should use the first one.
SharePoint Online also supports Claims-Based authentication mode. The general idea here is to obtain authentication cookies (apart from OAuth authentication flow where access token is issued) from the user credentials. Once the authentication cookie is obtained, you could perform authenticated SOAP (for example via CSOM API) or REST requests against SharePoint Online resources as demonstrated below.
Since you are developing ASP.NET web application,
SharePointOnlineCredentials class from SharePoint Online Client
Components SDK could be utilized which basically implements
claims-based authentication scheme. It could be installed via nuget
Example 1: request list items via CSOM API
using (var ctx = GetContext(webUri.ToString(), userName, password))
{
var list = ctx.Web.Lists.GetByTitle("Documents");
var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(items);
ctx.ExecuteQuery();
foreach (var item in items)
{
Console.WriteLine(item.FieldValues["FileRef"]);
}
}
where
private static ClientContext GetContext(string url,string username, string password)
{
var ctx = new ClientContext(url);
var securePassword = new SecureString();
foreach (char c in password) securePassword.AppendChar(c);
ctx.Credentials = new SharePointOnlineCredentials(username, securePassword);
return ctx;
}
Example 2: request list items via REST API
using (var client = new SPHttpClient(webUri, userName, password))
{
var listTitle = "Tasks";
var endpointUrl = string.Format("{0}/_api/web/lists/getbytitle('{1}')/items",webUri,listTitle);
var data = client.ExecuteJson(endpointUrl);
foreach (var item in data["value"])
{
Console.WriteLine(item["Title"]);
}
}
where
SPHttpClient.cs - implements HTTP client for SharePoint Online (SPHttpClient class)
SPHttpClientHandler.cs - implements HTTP handler for SharePoint Online

Get AngularJS to talk to .NET Web API secured with Azure AD

I have two different web projects on Microsoft Azure. One project is a .NET MVC web application and the other project is a .NET Web API.
Both projects are configured to use Azure AD. The MVC web application is able to get a token and use it to make requests against the Web API. Here's sample code from the MVC web app.
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = authContext.AcquireTokenSilent(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
// Make a call against the Web Api
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, webApiBaseAddress + "/api/list");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
So this code works just fine. However, what I need to do now is call the Web API directly from an AngularJS application. When I try to do that, I get a 401 unauthorized error.
The way I am doing this is by adding a header to the HTTP GET request sent by AngularJS. I'm setting "Bearer" to the result.AccessToken value that I am passing to the page from my MVC application (code above).
Obviously this doesn't work. I suppose now my question is what are my options? Is there an official or better way to do this? Let's say I wanted to make calls to the Web API from standard JavaScript (lets forget the complexities of AngularJS). Is there a way to authenticate with Azure AD?
the canonical way of obtaining a token for an in-browser JS application would be to use the OAuth2 implicit flow. Azure AD does not currently expose that flow, but stay tuned: we are working on enabling the scenario. No dates to share yet.
HTH!
V.
The work I mentioned in the older answer finally hit the preview stage. Please take a look at http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ - that should solve precisely the scenario you described. If you have feedback on the library please do let us know!
Thanks
V.

ASP.NET MVC with Forms Auth and WebApi with Basic Auth

I have a WebApi using Basic Auth nicely. And I have an MVC site using Forms Auth nicely. But here's the catch:
Client X has a dedicated database with any number of Contacts and Products. The MVC site is a dedicated site for them (via {clientId} routing), which allows their Contacts to log in (via Forms Auth) and place orders for their products. The Contact must be Form-ly logged in to place an order.
The product orders (need to) hit the WebApi to be recorded in the Client's database.
But since the WebApi uses Basic Auth to validate the Client, not the Contacts who placed the orders, every request comes back is 401 - Unauthorized.
I've checked out ThinkTecture as suggested by a number of posts here on SO, however it doesn't get me what I need because I'm not looking to allow Forms Auth in the WebApi. I don't want to authenticate the Contact from the Client's database in the WebApi, I want to authenticate the Client in the WebApi.
Has anyone come across a similar scenario and am I missing something glaringly obvious? Perhaps I need to implement both Forms and Basic on the site?
The very standard Api call I'm making from the site (where the UserName and Password are the Client's, not the Contact's):
var clientId = new Guid(RouteData.Values["clientId"].ToString());
var baseUrl = ConfigurationManager.AppSettings["ApiBaseAddress"];
var authHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", _shoppingCartSettings.UserName, _shoppingCartSettings.Password)));
var requestUrl = String.Format("api/{0}/inventory", clientId.ToString());
var httpWebRequest = WebRequest.Create(baseUrl + requestUrl);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authHeader);
httpWebRequest.Method = "GET";
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
try
{
using (var httpWebResponse = httpWebRequest.GetResponse())
{
// we never get here because of a 401
}
}
catch (WebException ex)
{
using (var httpWebResponse = ex.Response)
{
// we always get here
}
}
If I set up a separate test client and make the same call, it works great :/
Is your Web API under the same virtual directory and configuration as the MVC site? It looks like the Forms Auth HTTP module kicks in for your API, which you don't want. As long as you don't plan to call the API directly from the browser, move it to a separate virtual directory that is set up exclusively for basic auth, no forms auth module in the web.config for the API.
Why not have one login for your MVC site that has the ability to submit orders for every Client? It makes sense for your WebAPI to only allow Clients to submit orders for themselves. But I don't think it makes sense to have your MVC site authenticate as different Clients based on the Contact. Your MVC site would have to store the passwords for each Client.
Instead, create one login for the MVC site and give it the ability to submit an order for any Client.
After much banging of head against the not-so-proverbial wall, and a much needed shove by #0leg, I've discovered the cause.
In the Properties of my WebApi project file under Web > Servers, the Visual Studio Development Server was being used with a Virtual Path of "/", whereas my MVC project file was set up to use the Local IIS Web Server. The MVC project also had the Apply server settings to all users (store in project file) option checked.
Setting both to use the local IIS server resolved it.
Upon further contemplation, this now seems logical since they were essentially running on different servers.
Posting this for posterity's sake.

Loading the initial state on a silverlight application based on asp.net session

I'm writing a silverlight application that resembles a shopping cart system.
This app can only be launched from the asp.net website after the user is logged in to the site.
Upon first load, the app will send a request to the backend through WCF service to retreive all the existing items in the shopping cart.
Therefore the silverlight app needs to know who the current user is, to find which shopping cart to load.
I found there are a couple of ways so far, but not happy with any of them:
using wcf aspnet compat. silverlight can ask who the current user is by asking the wcf service.
pass parameters from the page to xaml by using xaml.InitParameters and pass in the minimum amount of information to identify a user in a serialized format.
pass parameters through query string to xaml (apparently this is also possible)
Can anyone share the best practice to achieve this?
Thanks
We use the first solution in our projects. You haven't to invent any type of serialization format or so in this case. A disadvantage of this approach - extra async logic at startup.
The example of service:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class UserInfoService : IUserInfoService
{
public UserInfo GetUserInfo()
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
return null;
var userInfo = new UserInfo
{
Login = HttpContext.Current.User.Identity.Name,
Fullname = ...,
};
return userInfo;
}
}
Sending userid via initParams or query string is not good idea I think. Such things should be more hidden.
The real important thing is to verify user on server on each service call because anyone can call your services in similar way as your app.
HTH

Resources