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.
Related
I am managing and old web site (site, not application) that is a hybrid of Web Forms and Classic ASP. The Classic ASP is being phased out, but that is probably a year away. Right now, we are dropping the old form of authentication in favor of Windows Authentication in the web.config.
The problem is that I am attempting to post to a Classic page from the code behind of a web form (http://www.blahsiblah.com/index.aspx) and am getting a 401 error.
var webClient = new WebClient();
var urlClassicASP = "http://www.blahsiblah.com/classic.asp";
var responseArray = webClient.UploadValues(urlClassicASP, "POST", nameValueCollection);
This throws "The remote server returned an error: (401) Unauthorized"
My question is, how can I post to the classic page without invoking the authentication of the dotNet side?
There are multiple ways to achieve this
Here is a simple suggestion that I hope helps
.Net
Use 127.0.0.1 (or your internal 192.169 / 10.1* ) IP to post to the page vs the public URL
Add a parameter (call it 'bypassauth' or something unique ) when sending the request to the ASP page
Add a parameter that identifies the user that you have authenticated in the .Net side
ASP
Find the include where the authentication check is happening and in that check, add another condition before returning 401 that checks two things
1) Request is from local/internal IP
2) Has the bypassauth parameter
3) the user id is valid
This way your old ASP code will still continue to work if requested from a browser and expect user to be authenticated however, when sending the request from .net will let you bypass authentication
I'm sure there are other ideas too, but this is just one approach
My solution was to set:
webClient.UseDefaultCredentials = true;
I have a legacy WebForms application that consumes (ASP.net) Web-Services (using anonymous access) that reside on the same IIS server (same domain, different apps each with their own dedicated app pool). This application was hosted in a secured VPN but now there is a request to host it publicly.
What is the expedient (yet secure) method to secure the web services site without doing a substantial re-coding (on the application level). I have tried configuring the Web-Service site in IIS so that it enables only the Service account (Identity) under which the Web Applications App Pool runs but the current request mode coming from the application is always using Anonymous access. I need to restrict access to allow only the this specific web application. I am thinking of an ISAPI filter, but it is not recommended for IIS 7+ ?
ADDENDUM: I would love to find an IIS based solution. Currently I am trying to restrict access based to just the Web Application source. Problem is (as stated) is those request are all "Anonymous" if I could make those requests use "Network Service" or some other local Identity then I would be set.
I recommend you to use IdentityServer and OpenIdConnect to do that.
IdentityServer is a .NET/Katana-based framework and hostable component
that allows implementing single sign-on and access control for modern
web applications and APIs using protocols like OpenID Connect and
OAuth2. It supports a wide range of clients like mobile, web, SPAs and
desktop applications and is extensible to allow integration in new and
existing architectures.
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0
protocol. It allows Clients to verify the identity of the End-User
based on the authentication performed by an Authorization Server, as
well as to obtain basic profile information about the End-User in an
interoperable and REST-like manner. https://connect2id.com/learn/openid-connect
Using this, you can ask identity server to give you an access token and Id Token.
An identity token represents the outcome of an authentication process.
It contains at a bare minimum an identifier for the user (called the
sub aka subject claim). It can contain additional information about
the user and details on how the user authenticated at the OP.
An access token allows access to a resource. Clients request access
tokens and forward them to an API. Access tokens contain information
about the client and the user (if present). APIs use that information
to authorize access to their data.
In your case, you can for example implement the client credentials flow between your Webforms app and the WebService. (In this flow you are not gonna ask nothing to the users of the WebForms app). So, the idea is that the WebForms app is going to ask identity server to give it an access token to access the webservices resources. In the WebService you have to implement the authorization based on whatever you want (Scopes, claims etc). Please read LeastPrivilege blog (Dominick Baier), He is the master of these topic along with his buddy Brock Allen. Since I cannot post more than 1 link in StackOverflow which is really bad, you have to google them or google any additional information.
If you want a user authentication, you can use Implicit, Code or Hybrid flow. But that depends on what you really want to do.
I reckon you may have to do a bit of code but it's not too much. You can figure out a way to ask for authorization before any endpoint is reached.
I hope I was clear. If not, please ask me for more explanation.
After more research I have settled on an http Module Solution, as it has the following benefits:
• Minimal Coding
• No need to modify existing code base
• Easy deployment
• Follows existing ASP.Net security models for (Local access)
The Module (VS:DLL Project)
using System;
using System.Web;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FilterModule
{
class AuthorizeLocal : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(OnBeginRequest);
}
private void OnBeginRequest(Object s, EventArgs e)
{
HttpApplication app = s as HttpApplication;
HttpRequest req = app.Request;
HttpContext context = app.Context;
if (!req.IsLocal) // Is the request from a Local Source?
{
context.Response.Close(); // close the response: ends request
}
/* Optional Test Code - to view locally create an html page TestModule.html in target site */
string Identity = Thread.CurrentPrincipal.Identity.Name;
string filePath = context.Request.FilePath;
string fileExtension = VirtualPathUtility.GetExtension(filePath);
string fileName = VirtualPathUtility.GetFileName(filePath);
if (fileName.ToLower().Equals("testmodule.html"))
{
try
{
app.Context.Response.Write("app: " + app.ToString());
context.Response.Write("<br/>server: " + app.Server.ToString());
context.Response.Write("<br/>Thread.CurrentPrincipal.Identity.Name: " + Thread.CurrentPrincipal.Identity.Name);
context.Response.Write("<br/>HttpRequest: " + req.Url.ToString());
context.Response.Write("<br/>req.UserHostName: " + req.UserHostName);
context.Response.Write("<br/>req.UserHostAddress: " + req.UserHostAddress);
context.Response.Write("<br/>filePath: " + filePath);
context.Response.Write("<br/>fileName: " + fileName);
context.Response.Write("<br/>fileExtension: " + fileExtension);
context.Response.Write("<br/>req.IsLocal: " + req.IsLocal.ToString());
context.Response.Write("<br/>req.LogonUserIdentity: " + req.LogonUserIdentity);
context.Response.Write("<br/>req.UserHostName : " + req.UserHostName);
context.Response.Write("<br/>req.AnonymousID " + req.AnonymousID);
context.Response.Write("<br/>req.IsAuthenticated : " + req.IsAuthenticated);
}
catch (Exception Ex)
{
context.Response.Write("<br/> " + Ex.ToString());
}
}
//if (_eventHandler != null)
// _eventHandler(this, null);
}
public void Dispose()
{
}
}
}
Implementation
Add the compiled DLL (FilterModule.dll) to the Web Service (site) bin Directory.
Add the following to module definition in the Web Service (or site) configuration file (web.config)
in the <system.webServer> section under <modules>
add the following:
<add name ="FilterModule" type="FilterModule.AuthorizeLocal" />
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.
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.
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.