Using autofac with a CustomUser within MembershipReboot - autofac

I am trying to configure MRB with Autofac and a custom user class found on the sample site
e.g
public class CustomUser : RelationalUserAccount
{
[Display(Name="First Name")]
public virtual string FirstName { get; set; }
[Display(Name = "Last Name")]
public virtual string LastName { get; set; }
public virtual int? Age { get; set; }
}
public class CustomUserAccountService : UserAccountService<CustomUser>
{
public CustomUserAccountService(CustomConfig config, CustomUserRepository repo)
: base(config, repo)
{
}
}
My Repo
public class CustomDb : MembershipRebootDbContext<CustomUserAccount>
{
public CustomDb()
: base("CustomDatabase")
{
}
}
public class CustomUserAccountRepository : DbContextUserAccountRepository<CustomDb, CustomUserAccount>
{
public CustomUserAccountRepository(CustomDb db)
: base(db)
{
}
}
My controller is nothing special
UserAccountService<CustomUserAccount> _userAccountService;
AuthenticationService<CustomUserAccount> _authService;
public UserAccountController(
UserAccountService<CustomUserAccount> userAccountService, AuthenticationService<CustomUserAccount> authSvc)
{
this._userAccountService = userAccountService;
this._authService = authSvc;
}
Finally my startup.cs
private static void BuildAutofacContainer(IAppBuilder app, string authType)
{
var builder = new ContainerBuilder();
var config = CreateMembershipRebootConfiguration(app);
builder.RegisterInstance(config).As<MembershipRebootConfiguration>();
builder.RegisterType<DefaultMembershipRebootDatabase>()
.InstancePerLifetimeScope();
builder.RegisterType<DefaultUserAccountRepository>()
.As<IUserAccountRepository>()
.As<IUserAccountRepository<RelationalUserAccount>>()
.As<IUserAccountQuery>()
// .As<IUserAccountRepository<CustomUserAccount>>()
.As<IUserAccountQuery<BrockAllen.MembershipReboot.Relational.RelationalUserAccount>>()
.InstancePerLifetimeScope();
//builder.RegisterType<CustomUserRepository>().As<IUserAccountRepository<CustomUserAccount>>()
// .InstancePerLifetimeScope();//doesnt work
//builder.RegisterType<CustomUserAccount>()
// .As<CustomUserRepository>()
// .InstancePerRequest();doesnt work
//UserAccountService<CustomUserAccount> _userAccountService;
//AuthenticationService<CustomUserAccount> _authService;
builder.RegisterType<UserAccountService>().OnActivating(e =>
{
var owin = e.Context.Resolve<IOwinContext>();
var debugging = false;
#if DEBUG
debugging = true;
#endif
e.Instance.ConfigureTwoFactorAuthenticationCookies(owin.Environment, debugging);
})
.AsSelf()
.InstancePerLifetimeScope();
builder.RegisterType<UserAccountService<RelationalUserAccount>>().OnActivating(e =>
{
var owin = e.Context.Resolve<IOwinContext>();
var debugging = false;
#if DEBUG
debugging = true;
#endif
e.Instance.ConfigureTwoFactorAuthenticationCookies(owin.Environment, debugging);
})
.AsSelf()
.InstancePerLifetimeScope();
builder.Register(ctx =>
{
var owin = ctx.Resolve<IOwinContext>();
return new OwinAuthenticationService(authType, ctx.Resolve<UserAccountService>(), owin.Environment);
})
.As<AuthenticationService>()
.InstancePerLifetimeScope();
builder.Register(ctx => HttpContext.Current.GetOwinContext()).As<IOwinContext>();
builder.RegisterControllers(typeof(Startup).Assembly);
var container = builder.Build();
System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
private static MembershipRebootConfiguration CreateMembershipRebootConfiguration(IAppBuilder app)
{
var config = new MembershipRebootConfiguration();
config.RequireAccountVerification = false;
config.AddEventHandler(new DebuggerEventHandler());
var appInfo = new OwinApplicationInformation(
app,
"Test",
"Test Email Signature",
"/UserAccount/Login",
"/UserAccount/ChangeEmail/Confirm/",
"/UserAccount/Register/Cancel/",
"/UserAccount/PasswordReset/Confirm/");
var emailFormatter = new EmailMessageFormatter(appInfo);
// uncomment if you want email notifications -- also update smtp settings in web.config
config.AddEventHandler(new EmailAccountEventsHandler(emailFormatter));
// uncomment to enable SMS notifications -- also update TwilloSmsEventHandler class below
//config.AddEventHandler(new TwilloSmsEventHandler(appinfo));
// uncomment to ensure proper password complexity
//config.ConfigurePasswordComplexity();
return config;
}
As you can see I have tried to configure the autofac with these two attempts
//builder.RegisterType<CustomUserRepository>().As<IUserAccountRepository<CustomUserAccount>>()
// .InstancePerLifetimeScope();//doesnt work
//builder.RegisterType<CustomUserAccount>()
// .As<CustomUserRepository>()
// .InstancePerRequest();doesnt work
//UserAccountService<CustomUserAccount> _userAccountService;
//AuthenticationService<CustomUserAccount> _authService;
Can you spot how I am meant to bind the CustomUser to allow me to use autofac with it?
Thank you

Related

Get current logged in user in DbContext

For audit purposes I'm trying to get the current logged in user in my DbContext. However I'm having some issues with this. A few things to take into account:
In Blazor Server we have to use AddDbContextFactory
IHttpContextAccessor returns no result in deployed website (might be because IHttpContextAccessor is not thread safe?)
I created a custom DbContext that injects AuthenticationStateProvider.
public partial class CustomDbContext : DbContext
{
private AuthenticationStateProvider _authenticationStateProvider;
#region construction
public CustomDbContext ()
{
}
public CustomDbContext (AuthenticationStateProvider stateProvider)
{
_authenticationStateProvider = stateProvider;
}
[ActivatorUtilitiesConstructor]
public CustomDbContext (DbContextOptions<CustomDbContext> options, AuthenticationStateProvider stateProvider) : base(options)
{
_authenticationStateProvider = stateProvider;
}
public CustomDbContext(DbContextOptions<CustomDbContext> options) : base(options)
{
}
#endregion
...
In this DbContext, when overwriting the SaveChanges I get the User and their claims:
var state = await _authenticationStateProvider.GetAuthenticationStateAsync();
var userIdClaim = state.User.Claims.FirstOrDefault(c => c.Type == "userId")?.Value;
userId = userIdClaim != null && !string.IsNullOrEmpty(userIdClaim ) ? userIdClaim : string.Empty;
...
However when I call .CreateDbContext(); on the injected DbContextFactory, I get the following exception:
'Cannot resolve scoped service
'Microsoft.AspNetCore.Components.Authorization.AuthenticationStateProvider'
from root provider.'
I've found some topics about this, but the suggested solution there is to create a custom DbContextFactory that is scoped. But then you lose the reason why you are using the DbContextFactory, no?
Any ideas on how to solve this?
Thank you
The DBContextFactory is a singleton registered in the root application DI container, while the AuthenticationStateProvider is a scoped service that is registered in the Hub session DI container. You can't access a lower order service from a higher order service.
You need to rethink your design and provide the user information from whatever scoped service is making whatever call to need a DbConbtext.
Additional Information
I'm not sure what your data pipeline looks like so this example uses the Blazor template weather forecast.
First a View Service that components inject and use.
This injects the AuthenticationStateProvider. It gets the current user for each request and passes it to the data pipeline in a request object.
public class WeatherForecastViewService
{
private AuthenticationStateProvider _authenticationStateProvider; // scoped service
private WeatherForecastService _weatherForecastService; //Singleton Service
public WeatherForecastViewService(AuthenticationStateProvider authenticationStateProvider, WeatherForecastService weatherForecastService)
{
_authenticationStateProvider = authenticationStateProvider;
_weatherForecastService = weatherForecastService;
}
public async ValueTask SaveWeatherForecast(WeatherForecast record)
{
var user = await GetCurrentUser();
var request = new RecordRequest<WeatherForecast>(record, user );
await _weatherForecastService.SaveRecord(request);
}
private async ValueTask<ClaimsPrincipal> GetCurrentUser()
{
var state = await _authenticationStateProvider.GetAuthenticationStateAsync();
return state.User ?? new ClaimsPrincipal();
}
}
Here are the request and result objects:
public readonly struct RecordRequest<TRecord>
{
public TRecord Record { get; init; }
public ClaimsPrincipal Identity { get; init; }
public RecordRequest(TRecord record, ClaimsPrincipal identity)
{
this.Record = record;
this.Identity = identity;
}
}
public record RecordResult
{
public bool SuccessState { get; init; }
public string Message { get; init; }
private RecordResult(bool successState, string? message)
{
this.SuccessState = successState;
this.Message = message ?? string.Empty;
}
public static RecordResult Success(string? message = null)
=> new RecordResult(true, message);
public static RecordResult Failure(string message)
=> new RecordResult(false, message);
}
And here's the singleton data service
public class WeatherForecastDataService
{
// This is a singleton
private readonly IDbContextFactory<DbContext> _factory;
public WeatherForecastDataService(IDbContextFactory<DbContext> factory)
=> _factory = factory;
public async ValueTask<RecordResult> SaveRecord(RecordRequest<WeatherForecast> request)
{
if (!request.Identity.IsInRole("SomeRole"))
return RecordResult.Failure("User does not have authority");
// simulates some async DB activity
await Task.Delay(100);
// Get your DbContext from the injected Factory
// using var dbContext = this.factory.CreateDbContext();
// do your db stuff
return RecordResult.Success();
}
}
PS I haven'y actually run this code so there may be some typos!
IHttpContextAccessor returns no result in deployed website (might be because IHttpContextAccessor is not thread safe?)
Nothing to do with whether IHttpContextAccessor is not thread safe... It's simply because the HttpContext object is not available in Blazor Server App, as communication between the client side (browser) and server side is done through the SignalR protocol, not HTTP. But there is a way how to access the HttpContext object before the Blazor App is rendered, as the initial call to the app is always made through HTTP request; that is, when you enter a url into the address bar of your browser and hit the enter button. See here how to do that...
The following code snippet describes how to inject an AuthenticationStateProvider into the ApplicationDbContext object created by default when you select Individual Accounts in Blazor Server App.
Copy and test. It should work...
Data/ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext
{
public DbSet<Employee> Employees { get; set; }
private AuthenticationStateProvider _authenticationStateProvider;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options, AuthenticationStateProvider stateProvider)
: base(options)
{
_authenticationStateProvider = stateProvider;
}
public override async Task<int>
SaveChangesAsync(CancellationToken cancellationToken)
{
var stateProvider = await
_authenticationStateProvider.GetAuthenticationStateAsync();
if (stateProvider.User.Identity.IsAuthenticated)
{
Console.WriteLine("Authenticated User name: " +
stateProvider.User.Identity.Name);
}
// Delegate the saving action to the base class
return await base.SaveChangesAsync(cancellationToken);
}
}
Create an Employee Repository class service:
EmployeeRepository.cs
using <put here the namespace of your app>.Data;
using <put here the namespace of your app>.Models;
using Microsoft.EntityFrameworkCore;
public class EmployeeRepository
{
private readonly ApplicationDbContext ApplicationDbContext;
public EmployeeRepository(ApplicationDbContext
applicationDbContext)
{
ApplicationDbContext = applicationDbContext;
}
public async Task<Employee> CreateEmployee(Employee employee)
{
CancellationTokenSource cancellationTokenSource = new
CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
await ApplicationDbContext.Employees.AddAsync(employee);
await ApplicationDbContext.SaveChangesAsync(token);
return employee;
}
}
Index.razor
#inject EmployeeRepository EmployeeRepository
#using <Put here....>.Models
<button type="button" #onclick="SaveEmployee">Save Employee</button>
#if (emp != null)
{
<div>#emp.ID.ToString()</div>
<div>#emp.FirstName</div>
<div>#emp.LastName</div>
<div>#emp.City</div>
}
#code
{
private Employee emp;
private async Task SaveEmployee()
{
Employee employee = new Employee { FirstName = "Joana", LastName = "Brown", City = "London" };
emp = await EmployeeRepository.CreateEmployee(employee);
}
}
Create model class Employee:
Models/Employee.cs
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}
Note: To test this code, you'll have to create A Blazor Server App with Individual Accounts, create the database, including the Employees table
Last but not least: Startup
// Created by the default template
//services.AddDbContext<ApplicationDbContext>(options =>
// options.UseSqlServer(
// Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddDbContextFactory<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")),
ServiceLifetime.Scoped);
// This is your code...
services.AddScoped<ApplicationDbContext>(p =>
p.GetRequiredService<IDbContextFactory<ApplicationDbContext>>
().CreateDbContext());
services.AddScoped<EmployeeRepository>();
services.AddScoped<AuthenticationStateProvider,
RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddSingleton<WeatherForecastService>();
UPDATE:
but does that no against the the recommendations of Microsoft? They ae suggesting to always use using
var context = DbFactory.CreateDbContext();
You mean:
using var context = DbFactory.CreateDbContext();
No, it is not against the recommendations of Microsoft. It's another way to instantiate the DbContext. I did it that way in order to stick to this code by you:
services.AddScoped<ApplicationDbContext>(p => p.GetRequiredService<IDbContextFactory<ApplicationDbContext>>().CreateDbContext());
Anyhow, these are the changes you should make in order to reflect "Microsoft's recommendations"
Change:
services.AddScoped<ApplicationDbContext>(p => p.GetRequiredService<IDbContextFactory<ApplicationDbContext>>().CreateDbContext());
To:
services.AddScoped<ApplicationDbContext>();
Change:
private readonly ApplicationDbContext ApplicationDbContext;
public EmployeeRepository(ApplicationDbContext
applicationDbContext)
{
ApplicationDbContext = applicationDbContext;
}
To:
private readonly IDbContextFactory<ApplicationDbContext>
DbFactory;
public EmployeeRepository(IDbContextFactory<ApplicationDbContext>
_DbFactory)
{
DbFactory = _DbFactory;
}
And change:
await ApplicationDbContext.Employees.AddAsync(employee);
await ApplicationDbContext.SaveChangesAsync(token);
To:
await context.Employees.AddAsync(employee);
await context.SaveChangesAsync(token);
Also add:
using var context = DbFactory.CreateDbContext();
at the beginning of the EmployeeRepository.CreateEmployee method
Run and test.
Hope this work...
New Version
Data/ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext
{
public DbSet<Employee> Employees { get; set; }
private AuthenticationStateProvider _authenticationStateProvider;
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options, AuthenticationStateProvider stateProvider)
: base(options)
{
_authenticationStateProvider = stateProvider;
}
public override async Task<int>
SaveChangesAsync(CancellationToken cancellationToken)
{
var stateProvider = await
_authenticationStateProvider.GetAuthenticationStateAsync();
if (stateProvider.User.Identity.IsAuthenticated)
{
Console.WriteLine("Authenticated User name: " +
stateProvider.User.Identity.Name);
}
// Delegate the saving action to the base class
return await base.SaveChangesAsync(cancellationToken);
}
}
Create an Employee Repository class service:
EmployeeRepository.cs
using <put here the namespace of your app>.Data;
using <put here the namespace of your app>.Models;
using Microsoft.EntityFrameworkCore;
public class EmployeeRepository
{
private readonly IDbContextFactory<ApplicationDbContext> DbFactory;
public EmployeeRepository(IDbContextFactory<ApplicationDbContext> _DbFactory)
{
DbFactory = _DbFactory;
}
public async Task<Employee> CreateEmployee(Employee
employee)
{
using var context = DbFactory.CreateDbContext();
// CancellationTokenSource provides the token and have authority to cancel the token
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken token = cancellationTokenSource.Token;
await context.Employees.AddAsync(employee);
await context.SaveChangesAsync(token);
return employee;
}
}
Index.razor
#inject EmployeeRepository EmployeeRepository
#using <Put here....>.Models
<button type="button" #onclick="SaveEmployee">Save Employee</button>
#if (emp != null)
{
<div>#emp.ID.ToString()</div>
<div>#emp.FirstName</div>
<div>#emp.LastName</div>
<div>#emp.City</div>
}
#code
{
private Employee emp;
private async Task SaveEmployee()
{
Employee employee = new Employee { FirstName = "Joana", LastName = "Brown", City = "London" };
emp = await EmployeeRepository.CreateEmployee(employee);
}
}
Create model class Employee:
Models/Employee.cs
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}
Note: To test this code, you'll have to create A Blazor Server App with Individual Accounts, create the database, including the Employees table
Last but not least: Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddDbContextFactory<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")),
ServiceLifetime.Scoped);
services.AddScoped<ApplicationDbContext>();
services.AddScoped<EmployeeRepository>();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddDatabaseDeveloperPageExceptionFilter();
services.AddSingleton<WeatherForecastService>();
}

Xamarin forms - Cannot get object from REST API to xaml page

I am developing an Xamarin.Forms app in VS 2019. My REST API is hosted on GoDaddy.
When I call the api I get back my json converted object fine in my viewmodel. But the object is null
from my xaml page. See this code:
public class NewOrderViewModel : BaseViewModel
{
public NewOrderDetails NewOrderDetails { get; set; }
public ICommand OkCommand { get; private set;}
public ICommand CancelCommand { get; private set; }
readonly IPageService _pageService;
public NewOrderViewModel(IPageService pageService, int custId)
{
_pageService = pageService;
OkCommand = new Command(NewOrder);
CancelCommand = new Command(CancelOrder);
NewOrderDetails = new NewOrderDetails();
LoadNewOrderDetails(custId);
}
private async void LoadNewOrderDetails(int custId)
{
using (var client = new HttpClient(new System.Net.Http.HttpClientHandler()))
{
var response = await client.GetStringAsync("http://api.lates.com.au/api/Customers/" + custId.ToString());
var customer = JsonConvert.DeserializeObject<Customer>(response);
await _pageService.DisplayAlert("Value", customer.CustomerName, "OK"); //This confirms the correct customer is returned.
NewOrderDetails.CustomerName = customer.CustomerName;
foreach (var cd in customer.CustomerDepartments)
{
NewOrderDetails.CustomerDepartments.Add(cd);
}
NewOrderDetails.OrderDate = DateTime.Today;
NewOrderDetails.DeliveryDate = DateTime.Today;
NewOrderDetails.CustomerId = custId;
}
}
private void NewOrder()
{
_pageService.PopAsync();
_pageService.PushModalAsync(new CustomerOrder());
}
private void CancelOrder()
{
_pageService.PopAsync();
}
}
public partial class NewOrder : ContentPage
{
public NewOrder()
{
InitializeComponent();
imgAddIcon.Source = FileImageSource.FromFile("AddDocument64By64.png");
}
protected override void OnAppearing()
{
BindingContext = new NewOrderViewModel(new PageService(), 1);
//If i put a break point here the NewOrderDetails property of NewOrderViewModel is null - WHY???
}
}
It seems to be something to do with asynchronous timing. Let me know if you need more info.
Malcolm
If i put a break point here the NewOrderDetails property of
NewOrderViewModel is null - WHY???
At that time your break point hit, the data in NewOrderDetails has not be set because the httpRequest is still requesting and you have to await the request finish to get the data from Api.
To solve your problem, you have to implement INotifyPropertyChanged in both NewOrderDetails and NewOrderViewModel to notify the View update value after you get the data from Api. I will give you some code snippets:
In NewOrderDetails :
public class NewOrderDetails : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public NewOrderDetails()
{
}
public string CustomerName
{
set
{
if (customerName != value)
{
customerName = value;
OnPropertyChanged("CustomerName");
}
}
get
{
return customerName;
}
}
string customerName { get; set; }
}
In NewOrderViewModel :
public class NewOrderViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public NewOrderDetails NewOrderDetaila
{
set
{
if (newOrderDetails != value)
{
newOrderDetails = value;
OnPropertyChanged("NewOrderDetaila");
}
}
get
{
return newOrderDetails;
}
}
NewOrderDetails newOrderDetails { get; set; }
public NewOrderViewModel( int custId)
{
NewOrderDetaila = new NewOrderDetails();
LoadNewOrderDetails(custId);
}
private async void LoadNewOrderDetails(int custId)
{
//...
NewOrderDetaila.CustomerName = "133";
//...
}
}
And in Xaml binding:
<Label Text="{Binding NewOrderDetaila.CustomerName}"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
Try and let me know if it works for you.
One problem in your code is here:
using (var client = new HttpClient(new System.Net.Http.HttpClientHandler()))
{
var response = await client.GetStringAsync("http://api.lates.com.au/api/Customers/" + custId.ToString());
var customer = JsonConvert.DeserializeObject<Customer>(response);
await _pageService.DisplayAlert("Value", customer.CustomerName, "OK"); //This confirms the correct customer is returned.
NewOrderDetails.CustomerName = customer.CustomerName;
foreach (var cd in customer.CustomerDepartments)
{
NewOrderDetails.CustomerDepartments.Add(cd);
}
NewOrderDetails.OrderDate = DateTime.Today;
NewOrderDetails.DeliveryDate = DateTime.Today;
NewOrderDetails.CustomerId = custId;
}
HttpClient should be defined as static class, and reused during your application lifetime. Disposing and recreating HttpClient leads to socket errors. Your code is causing multiple requests. I suggest also move this method to Task, that returns the object.
Example method:
internal class SendData
{
private static HttpClient client = new HttpClient();
internal static async Task<string> MakeServerRequest(string url, string content)
{
try
{
var request = new StringContent(content, Encoding.UTF8, "application/json");
var result = await client.PostAsync(url, request);
var response = await result.Content.ReadAsStringAsync();
return response;
}
catch (Exception ex)
{
YOUR ADDITIONAL LOGIC HERE
return null;
}
}
}
This will return JSON string that you can serialize to object, and do whatever your app requires.

ApplicationUser within an ActionFilter in Asp.Net Core 2.0?

How can I access the current ApplicationUser (or UserManager) within an ActionFilter in Asp.Net Core 2.0?
I am trying to lock down the entire application until the user accepts the EULA (End User License Agreement), changes their password, and fills out required personal information.
public class ApplicationUser : IdentityUser
{
...
public DateTime? DateEULAAccepted { get; set; }
...
}
Here is the ActionFilter code:
public class ProfileRequiredActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var CurUser = UserManager<ApplicationUser>.GetUserAsync(filterContext.HttpContext.User);
...
if (CurUser.Result.DateEULAAccepted.ToString() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "AgreeToEULA" }));
}
...
}
}
}
I am instantiating the ActionFilter in the Startup > ConfigureServices as follows:
...
services.AddMvc(options =>
{
options.Filters.Add(new ProfileRequiredActionFilter());
});
...
Try adding your filter in ConfigureServices() as follows:
services.AddMvc(options => {
options.Filters.Add<ProfileRequiredActionFilter>();
});
You can then inject your UserManager into the filter as follows:
public class ProfileRequiredActionFilter : IActionFilter
{
private UserManager<ApplicationUser> _userManager;
public ProfileRequiredActionFilter(UserManager<ApplicationUser> userManager)
{
_userManager = userManager
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var CurUser = _userManager<ApplicationUser>.GetUserAsync(filterContext.HttpContext.User);
...
if (CurUser.Result.DateEULAAccepted.ToString() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "AgreeToEULA" }));
}
...
}
}
}

How can I achieve the following using IOC?

I want to use IOC with my service and I want to instead inject a class not an interface in the constructor as below in the services layer but I do not want to create a new object from the calling layer like var service = new InvoiceService(new ChangeInvoiceDueDateCommand()) instead I want to create something like this from my controller in MVC where the IInvoiceService is injected into the controller constructor but the problem I see is that
public InvoiceController(IInvoiceService invoiceService, IMapper mapper)
{
_invoiceService = invoiceService;
_mapper = mapper;
}
and then called like this
public ActionResult ChangeInvoiceDueDate(InvoiceChangeDueDateViewModel invoiceChangeDueDateViewModel )
{
var request = _mapper.Map<InvoiceChangeDueDateViewModel, ChangeInvoiceDuedateRequest>(invoiceChangeDueDateViewModel);
InvoiceChangeDueDateResponse response = _invoiceService.ChangeDueDate(request);
return View();
}
Service Layer
public class InvoiceService : IInvoiceService
{
private readonly ChangeInvoiceDueDateCommand _changeInvoiceDueDateCommand;
public InvoiceService(ChangeInvoiceDueDateCommand changeInvoiceDueDateCommand)
{
_changeInvoiceDueDateCommand = changeInvoiceDueDateCommand;
}
public InvoiceChangeDueDateResponse ChangeDueDate(ChangeInvoiceDuedateRequest invoiceChangeDueDateRequest)
{
_changeInvoiceDueDateCommand.Execute(invoiceChangeDueDateRequest);
return new InvoiceChangeDueDateResponse {Status = new Status()};
}
}
Command
public class ChangeInvoiceDueDateCommand : ICommand<ChangeInvoiceDuedateRequest>
{
private readonly IRepository<Invoice> _invoiceRepository;
readonly InvoiceDueDateChangeValidator _validator;
public ChangeInvoiceDueDateCommand(IRepository<Invoice> invoiceRepository)
{
_invoiceRepository = invoiceRepository;
_validator = new InvoiceDueDateChangeValidator();
}
public void Execute(ChangeInvoiceDuedateRequest request)
{
if (_validator.IsDuedateValid(request.NewDuedate))
{
Invoice invoice = _invoiceRepository.GetById(request.Id);
invoice.ChangedDueDate(request.NewDuedate);
_invoiceRepository.SaveOrUpdate(invoice);
}
else
{
throw new InvalidDueDateException();
}
}
}
ICommand
public interface ICommand<T> where T : IRequest
{
void Execute(T request);
}
IRequest
public interface IRequest
{
int Id { get; set; }
}
I worked it out. It was just a Windsor syntax issue. It ended up being as simple as registering the Command using the container.Register(Component.For<ChangeInvoiceDueDateCommand>());

ASP.NET MVC 2 Authorization with Gateway Page

I've got an MVC 2 application which won't be doing its own authentication, but will retrieve a user ID from the HTTP request header, since users must pass through a gateway before reaching the application.
Once in the app, we need to match up the user ID to information in a "users" table, which contains some security details the application makes use of.
I'm familiar with setting up custom membership and roles providers in ASP.NET, but this feels so different, since the user never should see a login page once past the gateway application.
Questions:
How do I persist the user ID, if at all? It starts out in the request header, but do I have to put it in a cookie? How about SessionState?
Where/when do I get this information? The master page shows the user's name, so it should be available everywhere.
I'd like to still use the [Authorize(Roles="...")] tag in my controller if possible.
We have a very similar setup where I work. As #Mystere Man mentioned, there are risks with this setup, but if the whole infrastructure is setup and running correctly, we have found it to be a secure setup (we do care about security). One thing to ensure, is that the SiteMinder agent is running on the IIS node you're trying to secure, as it will validate an encrypted SMSESSION key also passed in the headers, which will make the requests secure (it would be extremely difficult to spoof the value of the SMSESSION header).
We are using ASP.NET MVC3, which has global action filters, which is what we're using. But with MVC2, you could create a normal, controller level action filter that could be applied to a base controller class so that all of your controllers/actions will be secured.
We have created a custom configuration section that allows us to turn this security filter on and off via web.config. If it's turned off, our configuration section has properties that will allow you to "impersonate" a given user with given roles for testing and debugging purposes. This configuration section also allows us to store the values of the header keys we're looking for in config as well, in case the vendor ever changes the header key names on us.
public class SiteMinderConfiguration : ConfigurationSection
{
[ConfigurationProperty("enabled", IsRequired = true)]
public bool Enabled
{
get { return (bool)this["enabled"]; }
set { this["enabled"] = value; }
}
[ConfigurationProperty("redirectTo", IsRequired = true)]
public RedirectToElement RedirectTo
{
get { return (RedirectToElement)this["redirectTo"]; }
set { this["redirectTo"] = value; }
}
[ConfigurationProperty("sessionCookieName", IsRequired = true)]
public SiteMinderSessionCookieNameElement SessionCookieName
{
get { return (SiteMinderSessionCookieNameElement)this["sessionCookieName"]; }
set { this["sessionCookieName"] = value; }
}
[ConfigurationProperty("userKey", IsRequired = true)]
public UserKeyElement UserKey
{
get { return (UserKeyElement)this["userKey"]; }
set { this["userKey"] = value; }
}
[ConfigurationProperty("rolesKey", IsRequired = true)]
public RolesKeyElement RolesKey
{
get { return (RolesKeyElement)this["rolesKey"]; }
set { this["rolesKey"] = value; }
}
[ConfigurationProperty("firstNameKey", IsRequired = true)]
public FirstNameKeyElement FirstNameKey
{
get { return (FirstNameKeyElement)this["firstNameKey"]; }
set { this["firstNameKey"] = value; }
}
[ConfigurationProperty("lastNameKey", IsRequired = true)]
public LastNameKeyElement LastNameKey
{
get { return (LastNameKeyElement)this["lastNameKey"]; }
set { this["lastNameKey"] = value; }
}
[ConfigurationProperty("impersonate", IsRequired = false)]
public ImpersonateElement Impersonate
{
get { return (ImpersonateElement)this["impersonate"]; }
set { this["impersonate"] = value; }
}
}
public class SiteMinderSessionCookieNameElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class RedirectToElement : ConfigurationElement
{
[ConfigurationProperty("loginUrl", IsRequired = false)]
public string LoginUrl
{
get { return (string)this["loginUrl"]; }
set { this["loginUrl"] = value; }
}
}
public class UserKeyElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class RolesKeyElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class FirstNameKeyElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class LastNameKeyElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class ImpersonateElement : ConfigurationElement
{
[ConfigurationProperty("username", IsRequired = false)]
public UsernameElement Username
{
get { return (UsernameElement)this["username"]; }
set { this["username"] = value; }
}
[ConfigurationProperty("roles", IsRequired = false)]
public RolesElement Roles
{
get { return (RolesElement)this["roles"]; }
set { this["roles"] = value; }
}
}
public class UsernameElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
public class RolesElement : ConfigurationElement
{
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return (string)this["value"]; }
set { this["value"] = value; }
}
}
So our web.config looks something like this
<configuration>
<configSections>
<section name="siteMinderSecurity" type="MyApp.Web.Security.SiteMinderConfiguration, MyApp.Web" />
...
</configSections>
...
<siteMinderSecurity enabled="false">
<redirectTo loginUrl="https://example.com/login/?ReturnURL={0}"/>
<sessionCookieName value="SMSESSION"/>
<userKey value="SM_USER"/>
<rolesKey value="SN-AD-GROUPS"/>
<firstNameKey value="SN-AD-FIRST-NAME"/>
<lastNameKey value="SN-AD-LAST-NAME"/>
<impersonate>
<username value="ImpersonateMe" />
<roles value="Role1, Role2, Role3" />
</impersonate>
</siteMinderSecurity>
...
</configuration>
We have a custom SiteMinderIdentity...
public class SiteMinderIdentity : GenericIdentity, IIdentity
{
public SiteMinderIdentity(string name, string type) : base(name, type) { }
public IList<string> Roles { get; set; }
}
And a custom SiteMinderPrincipal...
public class SiteMinderPrincipal : GenericPrincipal, IPrincipal
{
public SiteMinderPrincipal(IIdentity identity) : base(identity, null) { }
public SiteMinderPrincipal(IIdentity identity, string[] roles) : base(identity, roles) { }
}
And we populate HttpContext.Current.User and Thread.CurrentPrincipal with an instance of SiteMinderPrincipal that we build up based on information that we pull from the request headers in our action filter...
public class SiteMinderSecurity : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
if (MyApp.SiteMinderConfig.Enabled)
{
string[] userRoles = null; // default to null
userRoles = Array.ConvertAll(request.Headers[MyApp.SiteMinderConfig.RolesKey.Value].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), r => r.Trim());
var identity = new SiteMinderIdentity(request.Headers[MyApp.SiteMinderConfig.UserKey.Value];, "SiteMinder");
if (userRoles != null)
identity.Roles = userRoles.ToList();
var principal = new SiteMinderPrincipal(identity, userRoles);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
}
else
{
var roles = Array.ConvertAll(MyApp.SiteMinderConfig.Impersonate.Roles.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), r => r.Trim());
var identity = new SiteMinderIdentity(MyApp.SiteMinderConfig.Impersonate.Username.Value, "SiteMinder") { Roles = roles.ToList() };
var principal = new SiteMinderPrincipal(identity, roles);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
}
}
}
MyApp is a static class that gets initialized at application startup that caches the configuration information so we're not reading it from web.config on every request...
public static class MyApp
{
private static bool _isInitialized;
private static object _lock;
static MyApp()
{
_lock = new object();
}
private static void Initialize()
{
if (!_isInitialized)
{
lock (_lock)
{
if (!_isInitialized)
{
// Initialize application version number
_version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
_siteMinderConfig = (SiteMinderConfiguration)ConfigurationManager.GetSection("siteMinderSecurity");
_isInitialized = true;
}
}
}
}
private static string _version;
public static string Version
{
get
{
Initialize();
return _version;
}
}
private static SiteMinderConfiguration _siteMinderConfig;
public static SiteMinderConfiguration SiteMinderConfig
{
get
{
Initialize();
return _siteMinderConfig;
}
}
}
From what I gather of your situation, you have information in a database that you'll need to lookup based on the information in the headers to get everything you need, so this won't be exactly what you need, but it seems like it should at least get you started.
Hope this helps.