GetOwinContext through WCF throw nullreferenceException - wcf

i already have an MVC ASP.NET application where I manage authentication, using ASP.NET Identity for that.
I created a WCF service in the App, to allow other applications create new accounts using the service that my app provide to them.
When i call the WCF service, i get a NullReference from GetOwinContext() when service try to use userManager property.
This is my WCF Service Implementation:
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using MyCompany.MyProject.Core.Security.Auth;
using MyCompany.MyProject.Core.Security.Auth.Models;
using MyCompany.MyProject.MvcWebHost.Services.Contracts;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Host.SystemWeb;
using System.ServiceModel;
public class AuthenticationService : IAuthenticationService
{
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public OperationResultDTO CreateUserAccount(UserAccountDTO userDto)
{
OperationResultDTO result = new OperationResultDTO();
var user = new ApplicationUser();
user.UserName = userDto.Identifier.ToString();
user.Email = userDto.Email;
Task<IdentityResult> adminresult = UserManager.CreateAsync(user, userDto.Password);
if (adminresult.IsCompleted && adminresult.IsFaulted != false)
{
result.IsSuccess = true;
result.HasError = false;
}
else
{
result.IsSuccess = false;
result.HasError = true;
result.ErrorMessage = "This is an error message!";
}
return result;
}
}
How can i solve it?

OWIN is not supported with WCF as you can see here, http://owin.org/#projects
If you still want to use OWIN you have to switch to REST or drop OWIN if you want to use WCF

Related

Serve both REST and GraphQL APIs from .NET Core application

I have a .NET Core REST API server that is already serving customers.
Can I configure the API server to also support GraphQL by adding the HotChocolate library and defining the queries? Is it OK to serve both GraphQL and REST APIs from my .NET Core server?
Yes, supporting both REST APIs (controllers) and GraphQL is totally OK.
If you take libraries out of the picture, handling a GraphQL request just means handling an incoming POST to /graphql.
You can write a typical ASP.NET Core controller that handles those POSTs, if you want. Frameworks like Hot Chocolate provide middleware like .UseGraphQl() that make it more convenient to configure, but conceptually you can think of .UseGraphQl() as adding a controller that just handles the /graphql route. All of your other controllers will continue to work just fine!
There is a way you can automate having both APIs up and running at the same time using hotchocolate and schema stitching.
Basically I followed this tutorial offered by Ian webbington.
https://ian.bebbs.co.uk/posts/LessReSTMoreHotChocolate
Ian uses swagger schema from its API to create a graphql schema which saves us time if we think about it. It's easy to implement, however you still need to code to expose graphql endpoints.
This is what I implemented to connect all my graphql and rest APIs in just one API gateway. I'm sharing my custom implementation to have swagger schema (REST) running under hotchocolate (Graphql):
using System;
using HotChocolate;
using HotChocolate.AspNetCore;
using HotChocolate.AspNetCore.Playground;
using HotChocolate.AspNetCore.Voyager;
using HotChocolate.AspNetCore.Subscriptions;
using HotChocolate.Stitching;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using SmartGateway.Api.Filters;
using SmartGateway.Api.RestServices.SmartConfig;
namespace SmartGateway.Api.Extensions
{
public static class GraphQlExtensions
{
public static IServiceCollection AddGraphQlApi(this IServiceCollection services)
{
services.AddHttpClient("smartauth", (sp, client) =>
{
sp.SetUpContext(client); //GRAPHQL API
client.BaseAddress = new Uri(AppSettings.SmartServices.SmartAuth.Endpoint);
});
services.AddHttpClient("smartlog", (sp, client) =>
{
sp.SetUpContext(client); //GRAPHQL API
client.BaseAddress = new Uri(AppSettings.SmartServices.SmartLog.Endpoint);
});
services.AddHttpClient("smartway", (sp, client) =>
{
sp.SetUpContext(client); //GRAPHQL API
client.BaseAddress = new Uri(AppSettings.SmartServices.SmartWay.Endpoint);
});
services.AddHttpClient<ISmartConfigSession, SmartConfigSession>((sp, client) =>
{
sp.SetUpContext(client); //REST API
client.BaseAddress = new Uri(AppSettings.SmartServices.SmartConfig.Endpoint);
}
);
services.AddDataLoaderRegistry();
services.AddGraphQLSubscriptions();
services.AddStitchedSchema(builder => builder
.AddSchemaFromHttp("smartauth")
.AddSchemaFromHttp("smartlog")
.AddSchemaFromHttp("smartway")
.AddSchema(new NameString("smartconfig"), SmartConfigSchema.Build())
.AddSchemaConfiguration(c =>
{
c.RegisterExtendedScalarTypes();
}));
services.AddErrorFilter<GraphQLErrorFilter>();
return services;
}
public static IApplicationBuilder UseGraphQlApi(this IApplicationBuilder app)
{
app.UseWebSockets();
app.UseGraphQL("/graphql");
app.UsePlayground(new PlaygroundOptions
{
Path = "/ui/playground",
QueryPath = "/graphql"
});
app.UseVoyager(new PathString("/graphql"), new PathString("/ui/voyager"));
return app;
}
}
}
Set up HttpContext extension:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace SmartGateway.Api.Extensions
{
public static class HttpContextExtensions
{
public static void SetUpContext(this IServiceProvider servicesProvider, HttpClient httpClient)
{
HttpContext context = servicesProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
if (context?.Request?.Headers?.ContainsKey("Authorization") ?? false)
{
httpClient.DefaultRequestHeaders.Authorization =
AuthenticationHeaderValue.Parse(context.Request.Headers["Authorization"].ToString());
}
}
}
}
You need this to handle and pass the HTTPClient to your swagger Sdk.
using System.Net.Http;
namespace SmartGateway.Api.RestServices.SmartConfig
{
public interface ISmartConfigSession
{
HttpClient GetHttpClient();
}
public class SmartConfigSession : ISmartConfigSession
{
private readonly HttpClient _httpClient;
public SmartConfigSession(HttpClient httpClient)
{
_httpClient = httpClient;
}
public HttpClient GetHttpClient()
{
return _httpClient;
}
}
}
This is my graphql Schema:
namespace SmartGateway.Api.RestServices.SmartConfig
{
public static class SmartConfigSchema
{
public static ISchema Build()
{
return SchemaBuilder.New()
.AddQueryType<SmartConfigQueries>()
.AddMutationType<SmartConfigMutations>()
.ModifyOptions(o => o.RemoveUnreachableTypes = true)
.Create();
}
}
public class SmartConfigMutations
{
private readonly ISmartConfigClient _client;
public SmartConfigMutations(ISmartConfigSession session)
{
_client = new SmartConfigClient(AppSettings.SmartServices.SmartConfig.Endpoint, session.GetHttpClient());
}
public UserConfigMutations UserConfig => new UserConfigMutations(_client);
}
}
Finally, this is how you publish endpoints:
using System.Threading.Tasks;
using SmartConfig.Sdk;
namespace SmartGateway.Api.RestServices.SmartConfig.UserConfigOps
{
public class UserConfigMutations
{
private readonly ISmartConfigClient _client;
public UserConfigMutations(ISmartConfigClient session)
{
_client = session;
}
public async Task<UserConfig> CreateUserConfig(CreateUserConfigCommand createUserConfigInput)
{
var result = await _client.CreateUserConfigAsync(createUserConfigInput);
return result.Response;
}
public async Task<UserConfig> UpdateUserConfig(UpdateUserConfigCommand updateUserConfigInput)
{
var result = await _client.UpdateUserConfigAsync(updateUserConfigInput);
return result.Response;
}
}
}
More documentation about hotchocolate and schema stitching here:
https://hotchocolate.io/docs/stitching

Can we use Microsoft.AspNet.WebApi.Client from an ASP.NET Core application?

We want to be able to use the package Microsoft.AspNet.WebApi.Client from our ASP.NET Core MVC web application to make an HTTP call to an outside system. It does work but I couldn't find the corresponding source code in .NET core (github). Is it okay to use this library from the ASP.NET road map point of view? Will it be supported in ASP.NET Core going forward? Most importantly, will this package be supported in non-Windows platforms, as part of ASP.NET Core/.NET Core?
You can try what I did for a REST Client. I found that the assembly you have mentioned in it's latest version does not work in the recently released ASP.Net Core 1.0. Instead of "Microsoft.AspNet.WebApi.Client", use "System.Net.Http".
Then where you would have built an Http POST request like this:
using AvailabilityPricingClient.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AvailabilityPricingClient.Core.Model;
using System.Net.Http;
using System.Net.Http.Headers;
namespace AvailabilityPricingClient.Client
{
public class ProductAvailabilityPricing : IProductAvailabilityPricing
{
private HttpClient _client;
public ProductAvailabilityPricing(string apiUrl)
{
_client = new HttpClient();
_client.BaseAddress = new Uri(apiUrl);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public void Dispose()
{
_client.Dispose();
}
public async Task<IEnumerable<Availablity>> GetAvailabilityBySkuList(IEnumerable<string> skuList)
{
HttpResponseMessage response = _client.PostAsJsonAsync("/api/availabilityBySkuList", skuList).Result;
if (response.IsSuccessStatusCode)
{
var avail = await response.Content.ReadAsAsync<IEnumerable<Availablity>>();
return avail;
}
return null;
}
}
}
You will now build like this:
using AvailabilityPricingClient.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AvailabilityPricingClient.Core.Model;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
namespace AvailabilityPricingClient.Client
{
public class ProductAvailabilityPricing : IProductAvailabilityPricing
{
private HttpClient _client;
public ProductAvailabilityPricing(string apiUrl)
{
_client = new HttpClient();
_client.BaseAddress = new Uri(apiUrl);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public void Dispose()
{
_client.Dispose();
}
public async Task<IEnumerable<Availablity>> GetAvailabilityBySkuList(IEnumerable<string> skuList)
{
var output = JsonConvert.SerializeObject(skuList);
HttpContent contentPost = new StringContent(output, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = _client.PostAsync("/api/availabilityBySkuList", contentPost).Result;
if (response.IsSuccessStatusCode)
{
var avail = await response.Content.ReadAsStringAsync()
.ContinueWith<IEnumerable<Availablity>>(postTask =>
{
return JsonConvert.DeserializeObject<IEnumerable<Availablity>>(postTask.Result);
});
return avail;
}
return null;
}
}
}
This way you interface does not change only the body of your request code changes.
This is working for me....Good luck....

Is it possible to secure a web api with Authentication Filters using the local AD system acounts?

I've looked at implementing a way to maybe impersonate your AD user to secure my Web API, using my local domain AD.
All the samples I've found they use basic or token authentication. or secure it using Azure AD.
I want to implement my custom authorization business logic using my local domain AD/Impersonation. All I can achieve is using BASIC authentication and the challenge always POPS UP a form to input username/password. I would like to bypass that and use my local domain + custom logic to authenticate/authorize users.
Is there a way where I can impersonate the windows user to authenticate and authorize resources in my web api?
this is what my challenge function looks like:
void Challenge(HttpRequestMessage request, HttpResponseMessage response)
{
var host = request.RequestUri.DnsSafeHost;
response.Headers.Add(WWWAuthenticateHeader, string.Format("Basic realm=\"{0}\"", host));
}
Thanks very much!
First, you should read this:
How to get HttpClient to pass credentials along with the request?
Second (if you're doing a "one hop").
If you enable "Windows Authentication" and disable "Anonymous Authentication" (in IIS under "Authentication").......you can get at the Windows Identity.
You'll want to write a custom AuthorizeAttribute.
Here is a basic one to try out:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace MyLibrary.CustomAttributes.WebApi
{
public class IdentityWhiteListAuthorizationAttribute : System.Web.Http.AuthorizeAttribute
{
public const string ErrorMessageBadIdentityContent = "IIdentity.Name was empty or IIdentity was not a WindowsIdentity. CurrentAction='{0}'";
public const string ErrorMessageBadIdentityReasonPhrase = "IIdentity.Name was empty or IIdentity was not a WindowsIdentity. The most likely reason is that the web service is not setup for WindowsAuthentication and/or Anonymous Authentication is enabled.";
public const string ErrorMessageNotAuthenticated = "IIdentity.IsAuthenticated was false. '{0}'";
public IdentityWhiteListAuthorizationAttribute()
{
}
private string CurrentActionName { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
this.CurrentActionName = actionContext.ActionDescriptor.ActionName;
base.OnAuthorization(actionContext);
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
/* this will authenticate if the authorization-header contained a "Negotiate" windows Identity. Note, WebApi must be running in Windows-Authentication mode (and the WebApi-web.config must be set for "<authentication mode="Windows" />") for this to work. (the client will send the windows identity via the DefaultRequestHeaders.Authorization header */
string currentActionName = this.CurrentActionName;
IPrincipal httpContextCurrentUserPrinc = HttpContext.Current.User; /* */
IIdentity ident = httpContextCurrentUserPrinc.Identity;
bool badIdentity = false;
string errorMessageContent = string.Empty;
string errorMessageReasonPhrase = string.Empty;
if (null == ident)
{
badIdentity = true;
errorMessageContent = string.Format(ErrorMessageBadIdentityContent, currentActionName);
errorMessageReasonPhrase = ErrorMessageBadIdentityReasonPhrase;
}
if (!badIdentity)
{
/* Ensure that we have an actual userName which means windows-authentication was setup properly */
if (string.IsNullOrEmpty(ident.Name))
{
badIdentity = true;
errorMessageContent = string.Format(ErrorMessageBadIdentityContent, currentActionName);
errorMessageReasonPhrase = ErrorMessageBadIdentityReasonPhrase;
}
}
if (!badIdentity)
{
if (!ident.IsAuthenticated)
{
badIdentity = true;
errorMessageContent = string.Format(ErrorMessageNotAuthenticated, ident.Name);
errorMessageReasonPhrase = string.Format(ErrorMessageNotAuthenticated, ident.Name);
}
}
if (!badIdentity)
{
if (ident.GetType() != typeof(WindowsIdentity))
{
badIdentity = true;
errorMessageContent = string.Format(ErrorMessageBadIdentityContent, currentActionName);
errorMessageReasonPhrase = ErrorMessageBadIdentityReasonPhrase;
}
}
if (badIdentity)
{
HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(errorMessageContent),
ReasonPhrase = errorMessageReasonPhrase
};
throw new HttpResponseException(resp);
}
return true;
}
}
}
Apply that attribute to a webapi controller and/or method(s).
You could also write a DelegatingHandler...and use the same code above......

SilverLight Enabled Wcf Service - can't keep track of session

I'm new to Silverlight and WCF services. I'm trying to write a client application that can manipulate an object server side.
My problem is that each time my Silverlight client makes a call to the service, it enters into the constructor systematically
public SilverLightEnabledWcfService()
{
}
In the below example, I simply want to increment or decrement a number depending on the activity client side.
How am I supposed to do this properly?
I also tried to create a regular ASP.net client page and I got the same result, ie the server doesn't remember the session. So I don't think the problem is in my client, but I'm still happy to post the code if it helps.
Thanks !!
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Count.Library;
namespace Count.WebApp
{
[ServiceContract(Namespace = "")]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class SilverLightEnabledWcfService
{
public SilverLightEnabledWcfService()
{
}
private Class1 _class1;
[OperationContract]
public int Add1()
{
if (_class1 == null)
_class1 = new Class1(0);
_class1.Add1();
return Value;
}
[OperationContract]
public int Remove1()
{
if (_class1 == null)
_class1 = new Class1(0);
_class1.Remove1();
return Value;
}
public int Value
{
get
{
return _class1.Count;
}
}
}
}
Sessions require the wsHttpBinding, but this is not supported by Silverlight. There are workarounds, though:
http://web-snippets.blogspot.com/2008_08_01_archive.html
http://forums.silverlight.net/forums/t/14130.aspx

How do I authenticate a WCF Data Service?

I've created an ADO.Net WCF Data Service hosted in a Azure worker role. I want to pass credentials from a simple console client to the service then validate them using a QueryInterceptor. Unfortunately, the credentials don't seem to be making it over the wire.
The following is a simplified version of the code I'm using, starting with the DataService on the server:
using System;
using System.Data.Services;
using System.Linq.Expressions;
using System.ServiceModel;
using System.Web;
namespace Oslo.Worker
{
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class AdminService : DataService<OsloEntities>
{
public static void InitializeService(
IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
}
[QueryInterceptor("Pairs")]
public Expression<Func<Pair, bool>> OnQueryPairs()
{
// This doesn't work!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (HttpContext.Current.User.Identity.Name != "ADMIN")
throw new Exception("Ooops!");
return p => true;
}
}
}
Here's the AdminService I'm using to instantiate the AdminService in my Azure worker role:
using System;
using System.Data.Services;
namespace Oslo.Worker
{
public class AdminHost : DataServiceHost
{
public AdminHost(Uri baseAddress)
: base(typeof(AdminService), new Uri[] { baseAddress })
{
}
}
}
And finally, here's the client code.
using System;
using System.Data.Services.Client;
using System.Net;
using Oslo.Shared;
namespace Oslo.ClientTest
{
public class AdminContext : DataServiceContext
{
public AdminContext(Uri serviceRoot, string userName,
string password) : base(serviceRoot)
{
Credentials = new NetworkCredential(userName, password);
}
public DataServiceQuery<Order> Orders
{
get
{
return base.CreateQuery<Pair>("Orders");
}
}
}
}
I should mention that the code works great with the signal exception that the credentials are not being passed over the wire.
Any help in this regard would be greatly appreciated!
Thanks....
You must throw an exception of type DataServiceException.