alexanderzeitler.com - Using WCF Web APIs / WCF Http with ASP.NET Forms Authentication









Search Preview

Using WCF Web APIs / WCF Http with ASP.NET Forms Authentication | Alexander Zeitler

alexanderzeitler.com

.com > alexanderzeitler.com

SEO audit: Content analysis

Language Error! No language localisation is found.
Title Using WCF Web APIs / WCF Http with ASP.NET Forms Authentication | Alexander Zeitler
Text / HTML ratio 69 %
Frame Excellent! The website does not use iFrame solutions.
Flash Excellent! The website does not have any flash contents.
Keywords cloud = public WCF return service string class authentication ASPNET HTTP var contact configuration services APIs CookieContainer RESTful called values FormsAuthentication
Keywords consistency
Keyword Content Title Description Headings
= 39
public 18
WCF 12
return 9
service 8
string 8
Headings
H1 H2 H3 H4 H5 H6
1 3 0 0 0 0
Images We found 4 images on this web page.

SEO Keywords (Single)

Keyword Occurrence Density
= 39 1.95 %
public 18 0.90 %
WCF 12 0.60 %
return 9 0.45 %
service 8 0.40 %
string 8 0.40 %
class 8 0.40 %
authentication 8 0.40 %
ASPNET 8 0.40 %
HTTP 8 0.40 %
var 7 0.35 %
contact 7 0.35 %
configuration 6 0.30 %
services 6 0.30 %
APIs 6 0.30 %
CookieContainer 5 0.25 %
RESTful 5 0.25 %
called 5 0.25 %
values 5 0.25 %
FormsAuthentication 5 0.25 %

SEO Keywords (Two Word)

Keyword Occurrence Density
= new 10 0.50 %
WCF HTTP 7 0.35 %
from the 5 0.25 %
to be 5 0.25 %
public class 5 0.25 %
the ASPNET 4 0.20 %
to the 4 0.20 %
the WCF 4 0.20 %
in the 4 0.20 %
able to 3 0.15 %
as follows 3 0.15 %
the service 3 0.15 %
HTTP APIs 3 0.15 %
looks as 3 0.15 %
is the 3 0.15 %
ASPNET MVC 3 0.15 %
is returned 3 0.15 %
public void 3 0.15 %
which is 3 0.15 %
has to 3 0.15 %

SEO Keywords (Three Word)

Keyword Occurrence Density Possible Spam
the WCF HTTP 4 0.20 % No
looks as follows 3 0.15 % No
WCF HTTP APIs 3 0.15 % No
has to be 2 0.10 % No
Username and Password 2 0.10 % No
contained in the 2 0.10 % No
be able to 2 0.10 % No
To be able 2 0.10 % No
have to be 2 0.10 % No
services should return 2 0.10 % No
RESTful services should 2 0.10 % No
Implementing the service 2 0.10 % No
ASPNET MVC 3 2 0.10 % No
MVC 3 website 2 0.10 % No
return View public 2 0.10 % No
Service contained in 2 0.10 % No
2 0.10 % No
View public ActionResult 2 0.10 % No
which is done 2 0.10 % No
as follows public 2 0.10 % No

SEO Keywords (Four Word)

Keyword Occurrence Density Possible Spam
operation IList processors MediaTypeProcessorMode 2 0.10 % No
looks as follows public 2 0.10 % No
ASPNET MVC 3 website 2 0.10 % No
users=> 2 0.10 % No
RESTful services should return 2 0.10 % No
return View public ActionResult 2 0.10 % No
Service contained in the 2 0.10 % No
To be able to 2 0.10 % No
as follows public class 2 0.10 % No
the WCF HTTP APIs 2 0.10 % No
IList processors MediaTypeProcessorMode mode 2 0.10 % No
MediaTypeProcessorMode mode processorsAddnew JsonProcessoroperationmode 2 0.10 % No
processors MediaTypeProcessorMode mode processorsAddnew 2 0.10 % No
button plus an ActionLink 1 0.05 % No
AccountController Controller public ActionResult 1 0.05 % No
loginUrl=~AccountLogOn timeout=2880 name=ASPXFORMSAUTH > 1 0.05 % No
timeout=2880 name=ASPXFORMSAUTH > 1 0.05 % No
name=ASPXFORMSAUTH > The 1 0.05 % No
> The account 1 0.05 % No
The account controller 1 0.05 % No

Internal links in - alexanderzeitler.com

Fixing Chrome 58+ [missing_subjectAltName] with openssl when using self signed certificates
Fixing Chrome 58+ [missing_subjectAltName] with openssl when using self signed certificates | Alexander Zeitler
Accessing an HTTP API running on your MacBook in a Docker container from your iPhone/iPad using dnsmasq
Accessing an HTTP API running on your MacBook in a Docker container from your iPhone/iPad using dnsmasq | Alexander Zeitler
Deploying Ubuntu Mate Desktop as a developer environment in a Azure VM
Deploying Ubuntu Mate Desktop as a developer environment in a Azure VM | Alexander Zeitler
Deploying Ubuntu Mate Desktop as a developer environment in AWS EC2
Deploying Ubuntu Mate Desktop as a developer environment in AWS EC2 | Alexander Zeitler
Debugging mocha tests in a Docker container using Visual Studio Code
Debugging mocha tests in a Docker container using Visual Studio Code | Alexander Zeitler
Debugging mocha tests with Visual Studio Code when Node.js is installed using nvm
Debugging mocha tests with Visual Studio Code when Node.js is installed using nvm | Alexander Zeitler
Debugging a ES6 Node.js application in a Docker container using Visual Studio Code
Debugging a ES6 Node.js application in a Docker container using Visual Studio Code | Alexander Zeitler
Some thoughts on Open Source Software
Some thoughts on Open Source Software | Alexander Zeitler
Resizing a VMware Workstation VM partition using GParted - get the swap partition out of my way!
Resizing a VMware Workstation VM partition using GParted - get the swap partition out of my way! | Alexander Zeitler
Workflows: using Docker Machine and Docker Compose together in development
Workflows: using Docker Machine and Docker Compose together in development | Alexander Zeitler
Chrome crashes on Ubuntu in VMware Workstation
Chrome crashes on Ubuntu in VMware Workstation | Alexander Zeitler
Rename Visual Studio project including files, folders and namespaces
Rename Visual Studio project including files, folders and namespaces | Alexander Zeitler
A lap around AWS and docker-machine
A lap around AWS and docker-machine | Alexander Zeitler
Integration-testing ASP.NET 5 / MVC 6 Controllers on DNX Beta 4
Integration-testing ASP.NET 5 / MVC 6 Controllers on DNX Beta 4 | Alexander Zeitler
Deploying a ASP.NET MVC 6 API as Azure API App in Azure App Services
Deploying a ASP.NET MVC 6 API as Azure API App in Azure App Services | Alexander Zeitler
lowerCamelCase JSON with ASP.NET MVC 6
lowerCamelCase JSON with ASP.NET MVC 6 | Alexander Zeitler
Running ASP.NET 5 Beta 4 in Docker with DNX runtime #aspnet5 #docker
Running ASP.NET 5 Beta 4 in Docker with DNX runtime #aspnet5 #docker | Alexander Zeitler
Stop complaining or improve yourself
Stop complaining or improve yourself | Alexander Zeitler
#NodeJS / #ExpressJS: Adding routes dynamically at runtime
#NodeJS / #ExpressJS: Adding routes dynamically at runtime | Alexander Zeitler
mongoose: Referencing schema in properties or arrays
mongoose: Referencing schema in properties or arrays | Alexander Zeitler
MongoDB development environment journal size management using mongoctl
MongoDB development environment journal size management using mongoctl | Alexander Zeitler
Farewell...
Farewell... | Alexander Zeitler
Inspecting AngularJS $scope using Firebug and Chrome Developer Tools
Inspecting AngularJS $scope using Firebug and Chrome Developer Tools | Alexander Zeitler
Useful @Brackets extensions for Web Developers
Useful @Brackets extensions for Web Developers | Alexander Zeitler
.NET User Group Karlsruhe: StreamInsight: Complex Event Processing by Microsoft
.NET User Group Karlsruhe: StreamInsight: Complex Event Processing by Microsoft | Alexander Zeitler
“Commit all must be called when a managed buffer has focus” in Microsoft SQL Server Data Tools
“Commit all must be called when a managed buffer has focus” in Microsoft SQL Server Data Tools | Alexander Zeitler
.NET User Group Karlsruhe: Git
.NET User Group Karlsruhe: Git | Alexander Zeitler
Open Source Windows 8 App: Sprudelsuche
Open Source Windows 8 App: Sprudelsuche | Alexander Zeitler
Open Source– Scheissegal?
Open Source– Scheissegal? | Alexander Zeitler
Lowercase JSON with ASP.NET Web API
Lowercase JSON with ASP.NET Web API | Alexander Zeitler
.NET Usergroup Karlsruhe: Think Big – Entwicklung skalierbarer Anwendungen mit Windows Azure
.NET Usergroup Karlsruhe: Think Big – Entwicklung skalierbarer Anwendungen mit Windows Azure | Alexander Zeitler
ASP.NET Web API and RavenDb
ASP.NET Web API and RavenDb | Alexander Zeitler
ASP.NET Web API Round-Up Slides
ASP.NET Web API Round-Up Slides | Alexander Zeitler
ASP.NET MVC 4 public beta including ASP.NET Web API
ASP.NET MVC 4 public beta including ASP.NET Web API | Alexander Zeitler
Hash Bang Urls in Single Page Applications mit ASP.NET MVC
Hash Bang Urls in Single Page Applications mit ASP.NET MVC | Alexander Zeitler
.NET User Group Karlsruhe: Know your Tools
.NET User Group Karlsruhe: Know your Tools | Alexander Zeitler
Git flow init liefert: flags: FATAL unable to determine getopt version unter Cygwin
Git flow init liefert: flags: FATAL unable to determine getopt version unter Cygwin | Alexander Zeitler
Using JsonValue and JsonArray in WCF Web API
Using JsonValue and JsonArray in WCF Web API | Alexander Zeitler
.NET User Group Karlsruhe: PowerShell 3.. 2.. 1..
.NET User Group Karlsruhe: PowerShell 3.. 2.. 1.. | Alexander Zeitler
What’s new in WCF Web API Preview 5 – introducing the test client
What’s new in WCF Web API Preview 5 – introducing the test client | Alexander Zeitler
Externe Templates in KnockoutJS laden
Externe Templates in KnockoutJS laden | Alexander Zeitler
WCF Web API: Role based access control with basic authentication
WCF Web API: Role based access control with basic authentication | Alexander Zeitler
.NET User Group Karlsruhe: Produce Cleaner Code with Aspect-Oriented Programming (AOP)
.NET User Group Karlsruhe: Produce Cleaner Code with Aspect-Oriented Programming (AOP) | Alexander Zeitler
REST using the WCF Web API – POST it!
REST using the WCF Web API – POST it! | Alexander Zeitler
REST using the WCF Web API – getting more RESTful responses (Part 5)
REST using the WCF Web API – getting more RESTful responses (Part 5) | Alexander Zeitler
TypeLoadException when mocking COM objects - Could not load type … from assembly. The type is marked…
TypeLoadException when mocking COM objects - Could not load type … from assembly. The type is marked… | Alexander Zeitler
REST using the WCF Web API – getting RESTful the BDD way (Part 4)
REST using the WCF Web API – getting RESTful the BDD way (Part 4) | Alexander Zeitler
REST using the WCF Web API – refactoring to IoC style (Part 3)
REST using the WCF Web API – refactoring to IoC style (Part 3) | Alexander Zeitler
REST using the WCF Web API – Basics (Part2)
REST using the WCF Web API – Basics (Part2) | Alexander Zeitler
Microsoft Web API – the REST is done by WCF (Part 1)
Microsoft Web API – the REST is done by WCF (Part 1) | Alexander Zeitler
Microsoft Web API – den REST macht WCF (Teil 1)
Microsoft Web API – den REST macht WCF (Teil 1) | Alexander Zeitler
.NET User Group Karlsruhe: Flexible Softwarearchitekturen mit Inversion of Control (IoC)
.NET User Group Karlsruhe: Flexible Softwarearchitekturen mit Inversion of Control (IoC) | Alexander Zeitler
machine.fakes ReSharper Templates
machine.fakes ReSharper Templates | Alexander Zeitler
CreateCert.cmd aus dem Windows Azure Platform Training Kit funktioniert nicht
CreateCert.cmd aus dem Windows Azure Platform Training Kit funktioniert nicht | Alexander Zeitler
JSON via jQuery direkt an einen ASP.NET MVC 3 Controller senden
JSON via jQuery direkt an einen ASP.NET MVC 3 Controller senden | Alexander Zeitler
POSTing Json data using the HttpClient from WCF Web API
POSTing Json data using the HttpClient from WCF Web API | Alexander Zeitler
Using the new WCF Web APIs HttpClient with ASP.NET Forms Authentication
Using the new WCF Web APIs HttpClient with ASP.NET Forms Authentication | Alexander Zeitler
Keyboard Jedi unter x64
Keyboard Jedi unter x64 | Alexander Zeitler
Using WCF Web APIs / WCF Http with ASP.NET Forms Authentication
Using WCF Web APIs / WCF Http with ASP.NET Forms Authentication | Alexander Zeitler
WCF Web APIs / WCF Http mit ASP.NET Forms Authentication verwenden
WCF Web APIs / WCF Http mit ASP.NET Forms Authentication verwenden | Alexander Zeitler
ILSpy – Open Source .NET Assembly Browser und Decompiler
ILSpy – Open Source .NET Assembly Browser und Decompiler | Alexander Zeitler

Alexanderzeitler.com Spined HTML


Using WCF Web APIs / WCF Http with ASP.NET FormsHallmark| Alexander Zeitler Toggle navigation Home Feed Using WCF Web APIs / WCF Http with ASP.NET FormsHallmarkWritten on March 02, 2011 Since a while Microsoft is working on WCF to ease the usage in RESTful scenarios. The new WCF HTTP APIs make hosting WCF services in (existing) ASP.NET (MVC) Websites easier without having the configuration overhead as before. The current builds unquestionably lack of simple hallmark and authorization, but there are plans to support OAuth in the near future. I've been asking myself, why not just using existing and reliable techniques like ASP.NET Forms Authentication.Withoutsome attempts I have been worldly-wise to get a (almost for my use cases) working solution running Requirements My passport and hallmark requirements are: Role based FormsHallmarkboth for the ASP.NET MVC 3 website and the WCF HTTP services hosted inside RESTful hallmark should not parse or fill forms on a website but use forms hallmark credentials versus a WCF HTTP hallmark service Inside a browser RESTful services should return XML Invoked from a panel test vendee the RESTful services should return JSON Implementing the service host The solution is based on WCF Web APIs Preview 3. First we create an empty ASP.NET MVC 3 website. XML is returned by the WCF HTTP APIs automatically if requested. The response JSON we need a so tabbed JsonProcessor which is included in the APIs. To be worldly-wise to process the input from the form we need to use a FormUrlEncodedProcessor which moreover once exists. This leads us to the pursuit service configuration: public matriculation ContactManagerConfiguration : HttpHostConfiguration, IProcessorProvider { private readonly CompositionContainer _container; public ContactManagerConfiguration(CompositionContainer container) { _container = container; } public void RegisterRequestProcessorsForOperation(HttpOperationDescription operation, IList<Processor> processors, MediaTypeProcessorMode mode) { processors.Add(new JsonProcessor(operation,mode)); processors.Add(new FormUrlEncodedProcessor(operation,mode)); } public void RegisterResponseProcessorsForOperation(HttpOperationDescription operation, IList<Processor> processors, MediaTypeProcessorMode mode) { processors.Add(new JsonProcessor(operation,mode)); } public object GetInstance(Type serviceType, InstanceContext instanceContext, Message message) { var contract = AttributedModelServices.GetContractName(serviceType); var identity = AttributedModelServices.GetTypeIdentity(serviceType); var definition = new ContractBasedImportDefinition(contract, identity, null, ImportCardinality.ExactlyOne, false, false, CreationPolicy.NonShared); return _container.GetExports(definition).First().Value; } } We'll create two services: Contact Service, contained in the ContactResource matriculation Login Service, contained in the LoginResource matriculation The implementions will be shown later on. Both services are registered inside Global.asax.cs In order to register the so tabbed ServiceRoutes an extension method AddServicesRoute() has been introduced. The registration is the following: var itemize = new AssemblyCatalog(typeof(Global).Assembly); var container = new CompositionContainer(catalog); var configuration = new ContactManagerConfiguration(container); RouteTable.Routes.AddServiceRoute<ContactResource>("contact", configuration); RouteTable.Routes.AddServiceRoute<LoginResource>("login", configuration); To be worldly-wise to run WCF HTTP and normal MVC routes inside the same application, the WCF HTTP routes have to be filtered from the MVC routes which is washed-up by an IRouteConstraint: public matriculation WcfRoutesConstraint : IRouteConstraint { public WcfRoutesConstraint(params string[] values) { this._values = values; } private string[] _values; public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { // Get the value tabbed "parameterName" from the // RouteValueDictionary tabbed "value" string value = values[parameterName].ToString(); // Return true is the list of unliable values contains // this value. bool match = !_values.Contains(value); return match; } } The WcfRouteConstraint is passed to the MapRoute definition: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", whoopee = "Index", id = UrlParameter.Optional }, // Parameter defaults new { controller = new WcfRoutesConstraint(new string[] {"contact","login"}) } ); Die ContactResource looks as follows -- to alimony it simply without any database wangle etc.: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceContract] [Export] public matriculation ContactResource { [ImportingConstructor] public ContactResource() { } sieht wie folgt ausschnel [WebGet(UriTemplate="{id}")] public ContactDto Get(string id, HttpResponseMessage responseMessage) { var contact = new ContactDto { Name = "Alexander Zeitler" }; return contact; } } The LoginResource looks as follows: [ServiceContract] [Export] public matriculation LoginResource { [ImportingConstructor] public LoginResource() { } [WebInvoke(UriTemplate="", Method = "POST")] public void Login(Credentials credentials, HttpResponseMessage responseMessage) { bool auth = Membership.ValidateUser(credentials.Username, credentials.Password); if (auth) { FormsAuthentication.SetAuthCookie(credentials.Username,true); } else { responseMessage.StatusCode = HttpStatusCode.Unauthorized; } } } The subtitle is simple: Using an self implemented Credentials parameter having two properties Username and Password the login data is passed by a POST-method into the service. The credentials are stuff hallmark versus the ASP.NET membership database (you'll have to setup it using aspnet_regsql.exe). When succeeding the ASP.NET FormsAuthentication cookie is returned. When lightweight HTTP error 401 unauthoried is returned. To get the ASP.NET FormsAuthentication working the web.config has to be modified. First the URLs stuff protected have to be obstructed for unrecognized users. The login service (not the web page here!) has to be visible to all users: <location path=""> <system.web> <authorization> <allow roles="Admins"/> <deny users="*"/> </authorization> </system.web> </location> <location path="login"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location> This is the FormsAuthentication configuration required: <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" name=".ASPXFORMSAUTH" /> </authentication> The worth controller looks as follows: public matriculation AccountController : Controller { [HttpGet] public ActionResult Logon() { Response.StatusCode = (int)HttpStatusCode.Unauthorized; return View(); } [HttpPost] public ActionResult Logon(string username, string password) { if(Membership.ValidateUser(username, password)) { FormsAuthentication.SetAuthCookie(username,true); } return View(); } public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Logon", "Account"); } } The parameterless "Logon"Whoopeeis used to woodcut unrecognized calls from RESTful clients. The POST version of "Logon" is used for FormsAuthentication inside a browser. The "LogOff"Whoopeeshould be self-explanatory... The towardly Logon-View consists of a form containing both Username and Password input fields, the submit sawed-off plus an ActionLink to the LogOffWhoopeemethod. Implementing the service vendee The vendee has to functions:HallmarkReading the contact data when stuff authenticatedHallmarkis washed-up using the HttpWebRequest class: HttpWebRequest loginRequest = (HttpWebRequest)HttpWebRequest.Create("http://localhost:44857/login"); loginRequest.Method = "POST"; CookieContainer cookieContainer = new CookieContainer(); loginRequest.CookieContainer = cookieContainer; loginRequest.ContentType = "application/x-www-form-urlencoded"; ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "Username=foo&Password=bar"; byte[] data = encoding.GetBytes(postData); loginRequest.ContentLength = postData.Length; Stream dataStream = loginRequest.GetRequestStream(); dataStream.Write(data, 0, data.Length); dataStream.Close(); loginRequest.GetResponse(); It's important to set the ContentType and using the CookieContainer. The CookieContainer stores the received cookies from the server (servcice) without loginRequest.GetResponse() is called. If hallmark has been successful the contact data can be read from the contact service. To pass the request to the protected contact service through the FormsAuthentication, the cookie stuff received surpassing needs to be passed within the request which is washed-up be re-using the CookieContainer: HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:44857/contact/1"); request.CookieContainer = cookieContainer; request.Accept = "application/json"; request.Method = "GET"; try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); string result = reader.ReadToEnd(); JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer(); ContactDto contact = jsonDeserializer.Deserialize<ContactDto>(result); Console.WriteLine(contact.Name); Console.ReadLine(); } reservation (WebException e) { Console.WriteLine(((HttpWebResponse)e.Response).StatusCode); Console.ReadLine(); } Calling the Website (http://localhost:44857/contact/1) without a successful login (http://localhost:44857/Account/Logon) returns the contacts XML definition: The panel vendee will return the de-serialized JSON: If hallmark fails the "Unauthorized" status lawmaking will be returned: Please note that I've have posted an update of the vendee that uses the shiny new HttpClient. Hence all requirements have been implemented. As well as the early shit of the WCF HTTP APIs this solution doesn't raise a requirement of stuff well-constructed or working perfectly and should be used as a understructure for discussion. You can download the sample implementation from here: WcfHttpMvcAuth.zip (9.45 mb) Please enable JavaScript to view the comments powered by Disqus. Copyright © Alexander Zeitler 2003 - 2016 | Impressum