Log in function in monorail c# - castle-monorail

Could anyone give me any good link to log in function in monorail c#?
I am a newbie to monorail c# and need to implement one log in function.
Thank you.
Mealea

Here's one from Ayende Rahien

Like in Ayende's solution, the best way is to just use the ASP.net authentication mechanisms. Here's an example action on a LoginController:
[AccessibleThrough(Verb.Post)]
public void Authenticate(string username, string password, bool autoLogin, string returlUrl)
{
SomeWebServiceAuthenticationProvider wsSecurity = new SomeWebServiceAuthenticationProvider();
bool isValid = wsSecurity.ValidateUser(username, password);
if (isValid)
{
//first perform a logout to make sure all other cookies are cleared
InternalLogout();
FormsAuthentication.SetAuthCookie(username, autoLogin);
PropertyBag["username"] = username;
PropertyBag["password"] = password;
PropertyBag["autoLogin"] = autoLogin;
//redirect back to the Home page, or some other page
if (!RedirectToPreviousUrl()) Redirect("home", "index");
}
else
{
Flash["auth_error"] = "Invalid user name or password.";
RedirectToAction("Index");
}
}
You can substitute some other authentication mechanism in place of 'SomeWebServiceAuthenticationProvider"... the point here is that we're just calling the standard FormsAuthentication methods.

Related

Perpetual expiry of claims in SignInWithClaimsAsync

I am using ASP.NET Core 3.1 with Identity and storing some basic user information like their full name in a claim using the code below (I am aware of checking password and stuff, ignoring it for brevity):
var user = await _userManager.FindByNameAsync(Input.Username);
var claims = new List<Claim>
{
new Claim("UserFullname", user.Fullname, ClaimValueTypes.String)
}
await _signInManager.SignInWithClaimsAsync(user, Input.RememberMe, claims);
I am accessing it in the _Layout.cshtml using the line below:
var userFullname = User.Claims.Single(c => c.Type == "UserFullname").Value;
The problem is, this seems to expire in some time even though the user is still logged in. I want this to be perpetual until the user logs out.
I am sure there has to be some way in startup.cs to control this and as far as possible, I would like to avoid overriding anything.
--EDIT--
As mentioned in the comments for answer by #yinqiu, I tried the cookie authentication scheme using the line below:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
But it did not help either.
I think you can try to override the SignInWithClaimsAsync method.
public override async Task SignInWithClaimsAsync(ApplicationUser user, AuthenticationProperties authenticationProperties, System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> additionalClaims)
{
if (authenticationProperties != null && authenticationProperties.IsPersistent)
{
authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddYears(1);
}
await base.SignInWithClaimsAsync(user, authenticationProperties, additionalClaims);
}
This is the appropriate solution of your case:
If you are inheriting Identity Classes (IdentityRole,IdentityUser) into your custom classes then you need to use your inherited classes otherwise you use the default Identity Classes. You need a custom ClaimIdentity Class let assume 'ApplicationClaimsIdentityFactory' and this class should be inherited by UserClaimsPrincipalFactory<AspNetUser, AspNetRole>
Step1 Register your dependencies in Startup.cs
services.AddIdentity<AspNetUser, AspNetRole>().AddEntityFrameworkStores<ICRCOMDMSEntities>().AddDefaultTokenProviders();
services.AddScoped<IUserClaimsPrincipalFactory<AspNetUser>, ApplicationClaimsIdentityFactory>();
Step2:
Override the method CreateAsync in your custom claimsIdentityFactory Calss and here you need to create your custom claims and return like
public async override Task<ClaimsPrincipal> CreateAsync(AspNetUser user)
{
var principal = await base.CreateAsync(user);
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim("UserLastLogin", user.LastLoginDate.ToString("dd/MM/yyyy hh:mm:ss tt"))
});
return principal;
}
Now your claims persists until user is logged in.

Implementing user session in Sencha and SpringBoot

I am trying to make a web app in Sencha Touch with Springboot as my back-end. My app is going to have users and each one of them is going to have their own separate activity. How do I make my app "know" what user is logged in so it can display their specific details? I am a newbie and don't know exactly how this needs to be done, especially on the server side (Springboot). If somebody could throw some light, that would be awesome! Thanks!
Assuming you are planning to use Spring Security, the current-user data can be obtained through its principal. There are a few ways to get the principal. One way is to have a principal parameter in the controller method, and Spring will inject it. Like this:
#RequestMapping(value = "/user", method = RequestMethod.GET)
#ResponseBody
public String currentUserName(Principal principal) {
return principal;
}
Another way would be to have a utility method like this:
public static User getUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof User) {
return (U) principal;
}
}
return null;
}
This can then be called from the controller method.

User authenticate play framework

Like many others in here I'm following the documentation about authentication on the documentation in here:
https://www.playframework.com/documentation/2.2.1/JavaGuide4
Everything was ok until I got to the part of implementing the validate function.
public String validate() {
user=User.authenticate(email, password);
if (user == null) {
return "Invalid user or password";
}
return null;
}
Am I suppose to implement the User class? import some library that I'm not aware of?
I'm new at play so please forgive my ignorance!,
and many thanks in advance!

ExtendedMembershipProvider and WebSecutiry.Login, where does persistCookie go?

Ok, so I have implemented a custom ExtendedMembershipProvider for use with an MVC4 application, all of this is wired up and working ok however I have been having an issue with the forms authentication cookie.
I am creating my own cookie which is fine when calling my login process directly however if I use the WebSecurity.Login function I can't seem to control the cookie myself.
So this leads me to my question, WebSecurity.Login takes three parameters (one of which is optional):
public static bool Login(
string userName,
string password,
bool persistCookie (optional)
)
Now this function invokes the ValidateUser function on the ExtendedMembershipProvider which only takes two parameters:
public abstract bool ValidateUser(
string username,
string password
)
Where does the persistCookie parameter go? Does WebSecurity.Login handle the cookie generation itself and if so how can I override this?
Any help is much appreciated guys!!
WebSecurity.Login probably executes following code:
static bool Login(string userName, string password, bool persistCookie)
{
if(System.Web.Security.Membership.Provider.ValidateUser(userName, password))
{
System.Web.Security.FormsAuthentication.SetAuthCookie(userName, persistCookie);
return true;
}
return false;
}
If you want to change behavior, change this snippet in accordance with the guidelines from following answer.

UserNamePasswordValidator and Session Management

I'm using WCF custom Validator with HTTPS (.NET 4.5). Validate on success returns Customer object which I would like to use later. Currently I'm able to do it with Static variables which I like to avoid if possible. I tried to use HttpContext which becomes null in main thread. My understanding Validate runs under different thread. Is there any way I could share session info without involving DB or File share. See related threads here and here.
In Authentication.cs
public class CustomValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
//If User Valid then set Customer object
}
}
In Service.cs
public class Service
{
public string SaveData(string XML)
{
//Need Customer object here. Without it cannot save XML.
//HttpContext null here.
}
}
I can suggest you an alternative approach. Assuming that the WCF service is running in ASP.Net compatibility mode and you are saving the customer object to session storage. Create a class such as AppContext
The code would look something like this
public class AppContext {
public Customer CurrentCustomer {
get {
Customer cachedCustomerDetails = HttpContext.Current.Session[CUSTOMERSESSIONKEY] as Customer;
if (cachedCustomerDetails != null)
{
return cachedCustomerDetails;
}
else
{
lock (lockObject)
{
if (HttpContext.Current.Session[CUSTOMERSESSIONKEY] != null) //Thread double entry safeguard
{
return HttpContext.Current.Session[CUSTOMERSESSIONKEY] as Customer;
}
Customer CustomerDetails = ;//Load customer details based on Logged in user using HttpContext.Current.User.Identity.Name
if (CustomerDetails != null)
{
HttpContext.Current.Session[CUSTOMERSESSIONKEY] = CustomerDetails;
}
return CustomerDetails;
}
}
}
}
The basic idea here is to do lazy loading of data, when both WCF and ASP.Net pipelines have executed and HTTPContext is available.
Hope it helps.
Alright this should have been easier. Since the way UserNamePasswordValidator works, I needed to use custom Authorization to pass UserName/Password to the main thread and get customer info again from the database. This is an additional DB call but acceptable workaround for now. Please download code from Rory Primrose's genius blog entry.