Using Neo4jUserManager - asp.net-mvc

I'm new at Neo4j and I'm going to use neo4j.AspNet.Identity for my authentication and authorization. I'm using neo4jUserManager and also neo4jUserStore.But when I run the application, in Neo4jUserManager create method I'll face with NullExceptionReference and I don't know why? Can Anybody help me?
Below is my code
public class Neo4jUserManager : UserManager<ApplicationUser>
{
public Neo4jUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public async Task SetLastLogin()
{
// Store.FindByIdAsync()
}
public static Neo4jUserManager Create(IdentityFactoryOptions<Neo4jUserManager> options, IOwinContext context)
{
var graphClientWrapper = context.Get<GraphClientWrapper>();
var manager = new Neo4jUserManager(new Neo4jUserStore<ApplicationUser>(graphClientWrapper.GraphClient));
// Configure validation logic for usernames
// manager.UserValidator = new UserValidator<Neo4jUser>(manager)
// {
// AllowOnlyAlphanumericUserNames = false,
// RequireUniqueEmail = true
// };
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = false;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
// manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<Neo4jUser>
// {
// MessageFormat = "Your security code is {0}"
// });
// manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<Neo4jUser>
// {
// Subject = "Security Code",
// BodyFormat = "Your security code is {0}"
// });
// manager.EmailService = new EmailService();
// manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}

To setup the graphClientWrapper, you can do this:
var gc = new GraphClient(new Uri("http://localhost.:7474/db/data"));
gc.Connect();
var graphClientWrapper = new GraphClientWrapper(gc);
var manager = new Neo4jUserManager(new Neo4jUserStore<ApplicationUser>(graphClientWrapper.GraphClient));
Also, as a side I would read up on how to use Owin. It should have been obvious to you that you're trying to pull from an IOwinContext object, and that if you're getting null you should investigate how to set that up. I imagine less than 5 minutes on Google would have helped you. OR just looking at what calls that method would have shown you how the EntityFramework was being setup in the template you're modifying.

Related

Xamarin set Cookies in Multiplatform iOS app using (Hybrid)WebView

I followed example from here (https://learn.microsoft.com/en-gb/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview#invoke-c-from-javascript) to setup WebView for my project and I can invoke C# code from WebView page event, that is working fine.
However, before sending a request I have to setup a Cookie and that cookie should be passed to remote server. I followed several examples from net I am getting it to work for Android but iOS its not working.
Code I got from another Stackoverflow question as follows.
Android Working
var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie(true);
cookieManager.RemoveAllCookie();
var cookies = UserInfo.CookieContainer.GetCookies(new System.Uri(AppInfo.URL_BASE));
for (var i = 0; i < cookies.Count; i++)
{
string cookieValue = cookies[i].Value;
string cookieDomain = cookies[i].Domain;
string cookieName = cookies[i].Name;
cookieManager.SetCookie(cookieDomain, cookieName + "=" + cookieValue);
}
iOS Not Working
// Set cookies here
var cookieUrl = new Uri(AppInfo.URL_BASE);
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
foreach (var aCookie in cookieJar.Cookies)
{
cookieJar.DeleteCookie(aCookie);
}
var jCookies = UserInfo.CookieContainer.GetCookies(cookieUrl);
IList<NSHttpCookie> eCookies =
(from object jCookie in jCookies
where jCookie != null
select (Cookie) jCookie
into netCookie select new NSHttpCookie(netCookie)).ToList();
cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);
I have tried code from WebView documentation here, Cookie section (https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=macos#cookies)
I'll really appreciate if anybody can point out what I am doing wrong any hints.
Thanks.
Update
In my HybridWebViewRenderer method I am adding my custom Cookie as follows.
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
userController.RemoveAllUserScripts();
userController.RemoveScriptMessageHandler("invokeAction");
HybridWebView hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup();
}
if (e.NewElement != null)
{
string cookieDomain = new System.Uri(((HybridWebView)Element).Uri).Host;
foreach (var c in NSHttpCookieStorage.SharedStorage.Cookies)
{
Console.WriteLine("Cookie (Delete)" + c.Name);
NSHttpCookieStorage.SharedStorage.DeleteCookie(c);
}
var cookieDict = new NSMutableDictionary();
cookieDict.Add(NSHttpCookie.KeyDomain, new NSString("." + cookieDomain));
cookieDict.Add(NSHttpCookie.KeyName, new NSString("ABC"));
cookieDict.Add(NSHttpCookie.KeyValue, new NSString("123e4567-e89b-12d3-a456-426652340003"));
cookieDict.Add(NSHttpCookie.KeyPath, new NSString("/"));
cookieDict.Add(NSHttpCookie.KeyExpires, DateTime.Now.AddDays(1).ToNSDate());
var myCookie = new NSHttpCookie(cookieDict);
NSHttpCookieStorage.SharedStorage.SetCookie(myCookie);
string filename = $"{hybridView.Uri}";
var request = new NSMutableUrlRequest(new NSUrl(filename));
var wkNavigation = LoadRequest(request);
}
}
In AppDelegate I have added.
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
return base.FinishedLaunching(app, options);
}
Still no luck :( .........
You need to set the cookie in the shared storage.
Set your shared storage policy to always accept your own cookies.
In your ApplicationDelegate:
NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;

How to get Quart Next_Fire_Time in human readable format with ASP.Net

I'm using Quartz Scheduling Framework 3.0.7v for my ASP.Net application. This is the code that I used to save new job in my application.
#region SetProperties
public static NameValueCollection getProperties()
{
var properties = new NameValueCollection
{
// json serialization is the one supported under .NET Core (binary isn't)
["quartz.serializer.type"] = "json",
// the following setup of job store is just for example and it didn't change from v2
// according to your usage scenario though, you definitely need
// the ADO.NET job store and not the RAMJobStore.
["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz",
["quartz.jobStore.useProperties"] = "true",
["quartz.jobStore.dataSource"] = "sqlserver",
["quartz.jobStore.tablePrefix"] = "QRTZ_",
["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz",
//["quartz.dataSource.default.provider"] = "SqlServer-41", // SqlServer-41 is the new provider for .NET Core
["quartz.dataSource.sqlserver.provider"] = "SqlServer",
["quartz.dataSource.sqlserver.connectionString"] = #"Server=sever; Database = QUARTZ_TaskScheduling;Asynchronous Processing=true; Trusted_Connection = True;",
["quartz.threadPool.threadCount"] = "1",
};
return properties;
}
#endregion
#region SaveJob
public static int SaveJob(NewJob newJob, string companyCode)
{
var result = -1;
try
{
var properties = getProperties();
properties.Add("quartz.scheduler.instanceName", newJob.SCHED_NAME);
var schedulerFactory = new StdSchedulerFactory(properties);
_scheduler = schedulerFactory.GetScheduler().Result;
string jobType;
jobType = newJob.JOB_GROUP;
var Trigger = TriggerBuilder.Create()
.WithIdentity(newJob.JOB_NAME + " " + DateTime.Now.ToString("yyyy-MM-dd"))
.StartNow()
.WithCronSchedule(newJob.CRON_EXPRESSION)
.Build();
switch (jobType)
{
case "Job1":
var Job1 = JobBuilder.Create<Job1>()
.WithIdentity(newJob.JOB_NAME, newJob.JOB_GROUP)
.Build();
_scheduler.ScheduleJob(Job1, Trigger).Wait();
break;
case "Job2":
var Job2 = JobBuilder.Create<Job2>()
.WithIdentity(newJob.JOB_NAME, newJob.JOB_GROUP)
.Build();
_scheduler.ScheduleJob(Job2, Trigger).Wait();
break;
default:
Console.WriteLine("Error matching job type");
break;
}
}
catch (Exception ex)
{
result = -1;
Console.WriteLine("save job failed", ex.InnerException);
}
return result;
}
#endregion
My code is working perfectly. QUARTZ_JOB_DETAILS, QUARTZ_TRIGGERS are inserted into the database perfectly. These insertions have done by the Quartz library.
The problem is I'm getting the Next_Fire_Time as a hash value. How can I convert this value to human readable format?
hash value sample

Installing Umbraco programmatically

I'm trying to install Umbraco without using the visual interface, in order to increase my productivity.
Currently my code looks like this:
var installApiController = new InstallApiController();
var installSetup = installApiController.GetSetup();
var instructions = new Dictionary<string, JToken>();
var databaseModel = new DatabaseModel
{
DatabaseType = DatabaseType.SqlCe
};
var userModel = new UserModel
{
Email = "my#email.com",
Name = "My name",
Password = "somepassword",
SubscribeToNewsLetter = false
};
foreach (var step in installSetup.Steps)
{
if (step.StepType == typeof(DatabaseModel))
{
instructions.Add(step.Name, JToken.FromObject(databaseModel));
}
else if (step.StepType == typeof(UserModel))
{
instructions.Add(step.Name, JToken.FromObject(userModel));
}
}
var installInstructions = new InstallInstructions
{
InstallId = installSetup.InstallId,
Instructions = instructions
};
InstallProgressResultModel progressInfo = null;
do
{
string stepName = "";
if (progressInfo != null)
{
stepName = progressInfo.NextStep;
}
try
{
progressInfo = installApiController.PostPerformInstall(installInstructions);
}
catch (Exception e)
{
throw new Exception(stepName, e);
}
}
while (progressInfo.ProcessComplete == false);
The code fails at this line: https://github.com/umbraco/Umbraco-CMS/blob/dev-v7.8/src/Umbraco.Web/Install/InstallSteps/NewInstallStep.cs#L47, and I believe it's because the ApplicationContext isnt updated for each of the installation steps (e.g. not updated after the database is created).
Is it possible to update the ApplicationContext manually after each step in the installation progress, or do I have to trigger all installation steps in separate HTTP requests?
The code works, if I run each step in separate HTTP requests.

JwtFormat: why does it add the token's issuer to the ValidIssuers property?

I'm taking a look at the source code of the JwtFormat class and I'm wondering why does it add the Issuer it recovers from the token to the list of ValidIssuers. Does that mean that it will accept all issuers as valid if I don't specify a key or provide a IssueValidator handler to the TokenValidationParameters that are being used?
Btw, I'm lookit at this class because I'm investigating an issue regarding the use of JWT tokens (azure ad v2.0) in a web api app that seems to be ignoring the ValidIssuer property:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
AccessTokenFormat = new JwtFormat(
GetTokenValidationParameters(),
new OpenIdConnectCachingSecurityTokenProvider(authority)),
Provider = new OAuthBearerAuthenticationProvider {
OnValidateIdentity = ValidateIdentity
}
});
private TokenValidationParameters GetTokenValidationParameters() {
return new TokenValidationParameters {
ValidAudience = ConfigData.ClientId,
ValidIssuer = "nobody",
ValidIssuers = null,
IssuerValidator = ValidateIssuer
};
}
I'm editing this to give more information about what's going on.
According to the source code, ValidateIssuer is true by default, so there's no need to set it again. Just to be sure, here's the source code:
public TokenValidationParameters()
{
this.RequireExpirationTime = true;
this.RequireSignedTokens = true;
this.SaveSigninToken = false;
this.ValidateActor = false;
this.ValidateAudience = true;
this.ValidateIssuer = true;
this.ValidateIssuerSigningKey = false;
this.ValidateLifetime = true;
}
I'm setting up the IssuerValidator because I want to make sure that if the ValidIssuer is set, then I want to compare the token's issuer with that value (and don't want to check against the ValidIssuers collection when the ValidIssuer's validation fails).
In case you're wondering where the ValidIssuers is being filled (and yes, even in my example, it's being automatically populated, even though I've set it explicityl to null), it's happening in JwtFormat's Unprotect method:
public AuthenticationTicket Unprotect(string protectedText)
{
if (string.IsNullOrWhiteSpace(protectedText))
throw new ArgumentNullException(nameof (protectedText));
if (!(this.TokenHandler.ReadToken(protectedText) is JwtSecurityToken))
throw new ArgumentOutOfRangeException(nameof (protectedText), Microsoft.Owin.Security.Jwt.Properties.Resources.Exception_InvalidJwt);
TokenValidationParameters validationParameters = this._validationParameters;
if (this._issuerCredentialProviders != null)
{
validationParameters = validationParameters.Clone();
IEnumerable<string> second1 = this._issuerCredentialProviders.Select<IIssuerSecurityTokenProvider, string>((Func<IIssuerSecurityTokenProvider, string>) (provider => provider.Issuer));
validationParameters.ValidIssuers = validationParameters.ValidIssuers != null ? validationParameters.ValidIssuers.Concat<string>(second1) : second1;
IEnumerable<SecurityToken> second2 = this._issuerCredentialProviders.Select<IIssuerSecurityTokenProvider, IEnumerable<SecurityToken>>((Func<IIssuerSecurityTokenProvider, IEnumerable<SecurityToken>>) (provider => provider.SecurityTokens)).Aggregate<IEnumerable<SecurityToken>>((Func<IEnumerable<SecurityToken>, IEnumerable<SecurityToken>, IEnumerable<SecurityToken>>) ((left, right) => left.Concat<SecurityToken>(right)));
validationParameters.IssuerSigningTokens = validationParameters.IssuerSigningTokens != null ? validationParameters.IssuerSigningTokens.Concat<SecurityToken>(second2) : second2;
}
SecurityToken validatedToken;
ClaimsIdentity identity = (ClaimsIdentity) this.TokenHandler.ValidateToken(protectedText, validationParameters, out validatedToken).Identity;
AuthenticationProperties properties = new AuthenticationProperties();
if (this.UseTokenLifetime)
{
DateTime validFrom = validatedToken.ValidFrom;
if (validFrom != DateTime.MinValue)
properties.IssuedUtc = new DateTimeOffset?((DateTimeOffset) validFrom.ToUniversalTime());
DateTime validTo = validatedToken.ValidTo;
if (validTo != DateTime.MinValue)
properties.ExpiresUtc = new DateTimeOffset?((DateTimeOffset) validTo.ToUniversalTime());
properties.AllowRefresh = new bool?(false);
}
return new AuthenticationTicket(identity, properties);
}
Btw, this method ends up being called (indirectly) by the AuthenticateCoreAsync method when it needs to deserialize the token:
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
try
{
string requestToken = (string) null;
string authorization = this.Request.Headers.Get("Authorization");
if (!string.IsNullOrEmpty(authorization) && authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
requestToken = authorization.Substring("Bearer ".Length).Trim();
OAuthRequestTokenContext requestTokenContext = new OAuthRequestTokenContext(this.Context, requestToken);
await this.Options.Provider.RequestToken(requestTokenContext);
if (string.IsNullOrEmpty(requestTokenContext.Token))
return (AuthenticationTicket) null;
AuthenticationTokenReceiveContext tokenReceiveContext = new AuthenticationTokenReceiveContext(this.Context, this.Options.AccessTokenFormat, requestTokenContext.Token);
await this.Options.AccessTokenProvider.ReceiveAsync(tokenReceiveContext);
if (tokenReceiveContext.Ticket == null)
tokenReceiveContext.DeserializeTicket(tokenReceiveContext.Token);
//remaining code removed
}
Since I really haven't read the specs, I was wondering if anyone could explain me this behavior (of always adding the token's issuer to the ValidIssuers collection and checking if the token's issuer is in the ValidIssuers - which will always be true!)
Final edit
Ok, my bad...Not enough coffee, I think...In fact, the issuer is being added not from the token itself, but from the IIssuerSecurityTokenProvider that is passed to the JwtFormat ctor (gets it from the metadata endpoint)...
Sorry guys...
Thanks.
Luis
I'm currently without Vs, because I'm writing on my mobile phone, there should be a ValidateIssuer Property in the TokenValidationParameters, but it looks like you set the IssuerValidator to ValidateIssuer, which should be true, so try it that way:
private TokenValidationParameters GetTokenValidationParameters() {
return new TokenValidationParameters {
ValidAudience = ConfigData.ClientId,
ValidIssuer = "nobody",
ValidateIssuer = true
};
}

How can i get HttpClient to work with NTLM in a pcl with android

have the following which works on Win10 phone in a pcl.
But i cannot get the same code to return OK on samsung s7 with android 7.0
project is xamarin forms.
nuget for system.net.http is 2.2.29.
I've include the same nuget in my UWP for the win10 phone and android projects.
i've also changed the user to include be "domain\user", "domain#user", "user#domain"
var httpClientHandler = new System.Net.Http.HttpClientHandler()
{
Credentials = credentials.GetCredential(new Uri(location), "NTLM")
};
I've tried and alternative to setting the httpClientHandler.Credentials.
var credentials = new NetworkCredentials("user", "pass", "domain");
var location = "http://apps.mysite.com/api#/doit";
var httpClientHandler = new HttpClientHandler{
Credentials = credentials
}
using (var httpClient = new HttpClient(httpClientHandler, true))
{
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
try
{
var httpResponseMessage = await httpClient.GetAsync(location);
if (httpResponseMessage.StatusCode != System.Net.HttpStatusCode.OK)
{
//handle error
}
else
{
//do something
}
}
catch (Exception)
{}
finally
{}
}
another strange thing. when i run this on android, the code hits the await httpclient.getasync(location);
and the immediately jumps to the finally.
I hava a simple form with username & password Entry Fields, plus an OK button.
all three controls are bound to a viewmodel. the OK button via an ICommand.
this code and the view live in the PCL. which has a reference to Microsoft.Net.Http.
I have Android and Universal Windows Xamarin forms builds that consume the PCL.
Android Properties. Default httpClient, SSL/TLS Default. supported arch armeabi, armeabi-v7a;x86
Android Manifest: Camera, flashlight and internet
private bool calcEnabled = false;
private ICommand okCommand;
private string message = string.Empty;
private string validatingMessage = "Validating!";
private string unauthorizedMessage = "Invalid Credentials!";
private string authenticatedMessage = "Validated";
private bool validating = false;
public ICommand OkCommand => okCommand ?? (okCommand = new Command<object>((o) => clicked(o), (o) => CalcEnabled));
protected async void clicked(object state)
{
try
{
Validating = true;
Message = validatingMessage;
var credentials = new
System.Net.NetworkCredential(Helpers.Settings.UserName, Helpers.Settings.Password, "www.domain.com");
var location = "http://apps.wwwoodproducts.com/wwlocator#/information";
var httpClientHandler = new System.Net.Http.HttpClientHandler()
{
Credentials = credentials.GetCredential(new Uri(location), "NTLM") };
using (var httpClient = new System.Net.Http.HttpClient(httpClientHandler))
{
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
try
{
var httpResponseMessage = await
httpClient.GetAsync(location);
if (httpResponseMessage.StatusCode != System.Net.HttpStatusCode.OK)
{
Message = unauthorizedMessage;
}
else
{
Message = authenticatedMessage;
Messenger.Default.Send<bool>(true);
}
}
catch (Exception)
{
Message = unauthorizedMessage;
}
finally
{
Validating = false;
}
}
}
catch (Exception)
{
throw;
}
}

Resources