How to implement IIdentity for a custom User object in ASP.NET MVC? - asp.net-mvc

In my ASP.NET MVC app, I'm trying to create a custom HttpContent.User object. I've started by creating a Member class, which implements IPrincioal.
public class Member : IPrincipal
{
public string Id { get; set; }
public IIdentity Identity { get; set; }
public bool IsInRole(string role) { throw new NotImplementedException(); }
...
}
Then at authentication time I set HttpContext.User to an instance of a Member class:
FormsAuthentication.SetAuthCookie(email, false);
HttpContext.User = member;
Then later I want to check if the user is authenticated, like so:
if (User.Identity.IsAuthenticated) { ... }
That's where I'm stuck. I'm not sure what I need to do for the public IIdentity Identity property on the instance of the Member. So that I can use the HttpContext.User object something like this:
IsAuthenticated = HttpContext.User.Identity.IsAuthenticated;
ViewBag.IsAuthenticated = IsAuthenticated;
if (IsAuthenticated) {
CurrentMember = (Member)HttpContext.User;
ViewBag.CurrentMember = CurrentMember;
}

A Principal is not something you can just set once when writing the auth cookie and forget later. During subsequent requests, the auth cookie is read and the IPrincipal / IIdentity is reconstructed before executing an action method. When that happens, trying to cast the HttpContext.User to your custom Member type will throw an exception.
One option would be to intercept in an ActionFilter, and just wrap the standard implementation.
public class UsesCustomPrincipalAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var systemPrincipal = filterContext.HttpContext.User;
var customPrincipal = new Member(systemPrincipal)
{
Id = "not sure where this comes from",
};
filterContext.HttpContext.User = customPrincipal;
}
}
public class Member : IPrincipal
{
private readonly IPrincipal _systemPrincipal;
public Member(IPrincipal principal)
{
if (principal == null) throw new ArgumentNullException("principal");
_systemPrincipal = principal;
}
public string Id { get; set; }
public IIdentity Identity { get { return _systemPrincipal.Identity; } }
public bool IsInRole(string role)
{
return _systemPrincipal.IsInRole(role);
}
}
This way, you're not losing anything that comes out of the box with the default IPrincipal and IIdentity implementations. You can still invoke IsAuthenticated on the IIdentity, or even IsInRole(string) on the IPrincipal. The only thing you're gaining is the extra Id property on your custom IPrincipal implementation (though I'm not sure where this comes from or why you need it).

Related

Custom Authorize Attribute in Web API

I want to create my custom authorization in web api controller to check the roles of the user and if its active user. So far this is my code and I don't know yet how/what to override in this codes.
Thanks! your help is appreciated :D
using Avanza.Conference.Persistence;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace Avanza.Conference.Core.Extensions
{
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
ApplicationDbContext _context = new ApplicationDbContext(); // my entity
public override void OnAuthorization(HttpActionContext actionContext)
{
//Sample on what to do here??
if (AuthorizeRequest(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
//Code to handle unauthorized request
var challengeMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
throw new HttpResponseException(challengeMessage);
}
private bool AuthorizeRequest(HttpActionContext actionContext)
{
//Sample on what to do here??
return true;
}
}
}
Here is the sample you required, this check the request contains the authenticationtoken then only allow to execute the request. you can here check your session is available to check user logged in or not.
public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization({
System.Web.Http.Controllers.HttpActionContext actionContext)
private readonly string Resource {get; set; }base.OnAuthorization(actionContext);
if (actionContext.Request.Headers.GetValues("authenticationToken") != null)
string authenticationToken =public Convert.ToStringCustomAuthorize(
string resource, string actionContext.Request.Headers.GetValues("authenticationToken").FirstOrDefault()action);
//authenticationTokenPersistant{
// it is saved in someResource data= storeresource;
// i will compare the authenticationToken sent byAction client= withaction;
// authenticationToken persist in database against specific user, and act accordingly}
public override ifvoid OnAuthorization(authenticationTokenPersistant != authenticationToken)
{
HttpContextSystem.CurrentWeb.ResponseHttp.AddHeader("authenticationToken",Controllers.HttpActionContext authenticationTokenactionContext);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");{
actionContext.Response = actionContext.Requestbase.CreateResponseOnAuthorization(HttpStatusCode.ForbiddenactionContext);
return;
}
//Check your post authorization logic using Resource HttpContext.Current.Response.AddHeader("authenticationToken",and authenticationToken);Action
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "Authorized");
//Your logic here to return return;
authorize or unauthorized response }
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.ExpectationFailed);}
actionContext.Response.ReasonPhrase = "Please provide valid inputs";
}

Using Ninject in asp.net mvc GenerateUserIdentityAsync to add custom claim

I need to add custom claims when a user signs in (external sign in from Google) by performing a read to the database and adding the values returned. I am using Ninject for dependency injection to inject controllers with interfaces to my business layer services.
So I have located the identityModels.cs method to add claims:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
string userId = userIdentity.GetUserId();
//var _iUserBLL = (IUserBLL)System.Web.Mvc.DependencyResolver.Current.GetService(typeof(IUserBLL));
//UserBO objUser = _iUserBLL.GetById(userId);
//userIdentity.AddClaim(new Claim("Value1", objUser.Value1));
//userIdentity.AddClaim(new Claim("Value2", objUser.Value2));
return userIdentity;
}
Here the System.Web.Mvc.DependencyResolver.Current.GetService line fails and causes it to crash. This works elsewhere and I've also tried the same approach I use to inject controllers like:
public class MyController : Controller
{
private readonly IUserBLL _iUserBLL;
public MyController (IUserBLL iUserBLL)
{
_iUserBLL = iUserBLL;
}
}
And even:
[Inject]
public IUserBLL _iUserBLL { get; set; }
But when used in the GenerateUserIdentityAsync method the _iUserBLL is null. Any ideas how I can inject my IUserBLL to make a custom database call here?
A bit more info - if you aren't familiar with this method, it's part of the Identity code generated in a visual studio project with individual user accounts.
The full class is like so:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
...
}
}
So I tried the constructor in here, which doesn't work:
public class ApplicationUser : IdentityUser
{
private readonly IUserBLL _iUserBLL;
public ApplicationUser (IUserBLL iUserBLL)
{
_iUserBLL = iUserBLL;
}
...
}
The IdentityUser is declared in the inner workings of the pre supplied identity.entityframework class and is called from within that which I can't edit, so I'm confused how to approach this?
Thanks for your reply Sam, it put me onto a solution. Here is the code I ended up with. I had trouble with the static 'Create' method so I used the [Inject] attribute instead. Is there a way to alter the static 'Create' method to use IUserBLL in the constructor? Here is the code that I have working:
In App_Start/IdentityConfig.cs
// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
[Inject]
public IUserBLL _iUserBLL { get; set; }
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
var userIdentity = user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
UserBO objUser = _iUserBLL.GetById(user.Id);
userIdentity.Result.AddClaim(new Claim("Claim1", objUser.Value1));
userIdentity.Result.AddClaim(new Claim("Claim2", objUser.Value2));
return userIdentity;
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
In my NinjectWebCommon.cs I also include these lines, extra to all my bindings:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<System.Security.Principal.IPrincipal>().ToMethod(context => HttpContext.Current.User).InRequestScope();
kernel.Bind<ApplicationUserManager>().ToMethod(context => HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>()).InRequestScope();
kernel.Bind<ApplicationSignInManager>().ToMethod((context) =>
{
var cbase = new HttpContextWrapper(HttpContext.Current);
return cbase.GetOwinContext().Get<ApplicationSignInManager>();
});
...
}
ApplicationUser is an entity object and this kind of objects are responsible to holding data not doing logic. It will be much better if you add your custom claim in UserManager rather than ApplicationUser. Consider this:
public class ApplicationUserManager: UserManager<ApplicationUser>
{
private readonly IUserBLL _iUserBLL;
public ApplicationSignInManager(IUserStore<ApplicationUser> store,
IUserBLL iUserBLL)
: base(store)
{
// if you already fully integrated Identity with ninject,
// ninject could automatically resolve this for you.
_iUserBLL=iUserBLL;
// other configurations here
}
public override async Task<ClaimsIdentity> CreateIdentityAsync(
ApplicationUser user,
string authenticationType)
{
var userIdentity=await base.CreateIdentityAsync(user, authenticationType);
UserBO objUser = _iUserBLL.GetById(userId);
userIdentity.AddClaim(new Claim("Value1", objUser.Value1));
userIdentity.AddClaim(new Claim("Value2", objUser.Value2));
return userIdentity;
}
}

MVC custom roleprovider how to hook it up to HttpContext.Current.User.IsInRole("myrole")

I have an MVC app and I wrote a custom roleprovider for it as shown:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using VectorCheck.Models;
namespace VectorCheck.Security
{
public class MyRoleProvider : RoleProvider
{
private VectorCheckRepository<User> _repository { get; set; }
public MyRoleProvider()
{
_repository = new VectorCheckRepository<User>();
}
public MyRoleProvider(VectorCheckRepository<User> repository)
{
_repository = repository;
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] GetRolesForUser(string username)
{
var user = _repository.GetUser(username);
return new string[] { user.Role.Name };
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
var user = _repository.GetUser(username);
return string.Compare(user.Role.Name, roleName, true) == 0;
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
This works really well with restricting access to controllers and actions using:
[Authorize(Roles = "Administrator")]
above the controller or action.
I also want restricted access to some things in the view though using:
HttpContext.Current.User.IsInRole("Administrator")
This method isn't part of my roleprovider though so isn't getting overridden.
Does anyone know how to do it for this method as well?
If you've hooked your RoleProvider as the role provider for the application in web.config, then this should work automatically; the framework will create a RolePrincipal for an authenticated user at the start of the request that will call the GetRolesForUser method on your role provider, passing the name from the IIdentity as the user name.
The framework implementation of RolePrincipal's IsInRole(string role) method is something like this (I've added comments)
public bool IsInRole(string role)
{
if (_Identity == null)
throw new ProviderException(SR.GetString(SR.Role_Principal_not_fully_constructed));
if (!_Identity.IsAuthenticated || role == null)
return false;
role = role.Trim();
if (!IsRoleListCached) {
_Roles.Clear();
// here the RoleProvider is used to get the roles for the user
// and are cached in a collection on the RolePrincipal so that
// they are only fetched once per request
string[] roles = Roles.Providers[_ProviderName].GetRolesForUser(Identity.Name);
foreach(string roleTemp in roles)
if (_Roles[roleTemp] == null)
_Roles.Add(roleTemp, String.Empty);
_IsRoleListCached = true;
_CachedListChanged = true;
}
return _Roles[role] != null;
}
Set a breakpoint inside of your RoleProvider GetRolesForUser method to ensure that it is being called correctly and also inspect the IPrincipal (HttpContext.Current.User) to ensure that it is of type RolePrincipal for an authenticated user.
Sorry I am late to the party here;
For the benefit of other people with the same problem - Russ Cam's answer is spot on to finding the answer.
In my case, my custom roleManager did not have 'enabled="true" and cacheRolesInCookie="true". This seemed to stop the GetRolesForUser being called.
Working Code For the web.config:
<roleManager defaultProvider="CustomUserRolesMVCRoleProvider" enabled="true" cacheRolesInCookie="true">
Really Good Tutorial on this topic at http://www.brianlegg.com/post/2011/05/09/Implementing-your-own-RoleProvider-and-MembershipProvider-in-MVC-3.aspx

Use custom ASP.NET MVC IValueProvider, without setting it globally?

I want to be able to grab keys/values from a cookie and use that to bind a model.
Rather than building a custom ModelBinder, I believe that the DefaultModelBinder works well out of the box, and the best way to choose where the values come from would be to set the IValueProvider that it uses.
To do this I don't want to create a custom ValueProviderFactory and bind it globally, because I only want this ValueProvider to be used in a specific action method.
I've built an attribute that does this:
/// <summary>
/// Replaces the current value provider with the specified value provider
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class SetValueProviderAttribute : ActionFilterAttribute
{
public SetValueProviderAttribute(Type valueProviderType)
{
if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");
_ValueProviderType = valueProviderType;
}
private Type _ValueProviderType;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
IValueProvider valueProviderToAdd = GetValueProviderToAdd();
filterContext.Controller.ValueProvider = valueProviderToAdd;
}
private IValueProvider GetValueProviderToAdd()
{
return (IValueProvider)Activator.CreateInstance(_ValueProviderType);
}
}
Unfortunately, the ModelBinder and its IValueProvider are set BEFORE OnActionExecuting (why?????). Has anyone else figured out a way to inject a custom IValueProvider into the DefaultModelBinder without using the ValueProviderFactory?
You should still use a ValueProviderFactory in this case.
The method that you have to implement on your ValueProviderFactory has this signature:
IValueProvider GetValueProvider(ControllerContext controllerContext)
Within your implementation of that method you can inspect the controller context, and if the incoming request is for the controller/action that you want to leverage cookies on, return some CustomCookieValueProvider.
If you don't want to leverage cookies for the request, just return null and the framework will filter that out of from the list of Value Providers.
As a bonus, you might not want to hard code the logic for when to use the CustomCookieValueProvider into the ValueProviderFactory. You could, perhaps, leverage DataTokens to match when to use cookies with given routes. So add a route like this:
routes.MapRoute("SomeRoute","{controller}/{action}").DataTokens.Add("UseCookies", true);
Notice the DataTokens.Add() call in there, now inside you GetValueProvider method you could do something like this:
if (controllerContext.RouteData.DataTokens.ContainsKey("UseCookies"))
{
return new CustomCookieValueProvider(controllerContext.RequestContext.HttpContext.Request.Cookies);
}
return null;
Here is an alternative that lets you specify IValueProviders as attributes against an actions parameters.
This makes the IValueProviders transient and not Global.
public interface IControllerContextAware
{
ControllerContext ControllerContext { get; set; }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class ValueProviderAttribute : CustomModelBinderAttribute
{
public Type[] ValueProviders { get; private set; }
public ValueProviderAttribute(params Type[] valueProviders)
{
if (valueProviders == null)
{
throw new ArgumentNullException("valueProviders");
}
foreach (var valueProvider in valueProviders.Where(valueProvider => !typeof(IValueProvider).IsAssignableFrom(valueProvider)))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The valueProvider {0} must be of type {1}", valueProvider.FullName, typeof(IValueProvider)), "valueProviders");
}
ValueProviders = valueProviders;
}
public override IModelBinder GetBinder()
{
return new ValueProviderModelBinder
{
ValueProviderTypes = ValueProviders.ToList(),
CreateValueProvider = OnCreateValueProvider
};
}
protected virtual IValueProvider OnCreateValueProvider(Type valueProviderType, ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProvider = (IValueProvider)Activator.CreateInstance(valueProviderType);
if (valueProvider is IControllerContextAware)
{
(valueProvider as IControllerContextAware).ControllerContext = controllerContext;
}
return valueProvider;
}
private class ValueProviderModelBinder : DefaultModelBinder
{
public IList<Type> ValueProviderTypes { get; set; }
public Func<Type, ControllerContext, ModelBindingContext, IValueProvider> CreateValueProvider { get; set; }
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviders = from type in ValueProviderTypes
select CreateValueProvider(type, controllerContext, bindingContext);
bindingContext.ValueProvider = new ValueProviderCollection(valueProviders.Concat((Collection<IValueProvider>)bindingContext.ValueProvider).ToList());
return base.BindModel(controllerContext, bindingContext);
}
}
}
This is basically the code form the ModelBinderAttribute, but with a few tweaks.
It isn't sealed and so you can alter the way in which the IValueProviders are created if need be.
Here is a simple example which looks in another field, possibly a hidden or encrypted field, and takes the data and puts it into another property.
Here is the model, which has no knowledge of the IValueProvider, but does know about the hidden field.
public class SomeModel
{
[Required]
public string MyString { get; set; }
[Required]
public string MyOtherString { get; set; }
[Required]
public string Data { get; set; }
}
THen we have the IValueProvider, in this case, my provider knows explicitly about my model, but this doesn't have to be the case.
public class MyValueProvider : IValueProvider, IControllerContextAware
{
public ControllerContext ControllerContext { get; set; }
public bool ContainsPrefix(string prefix)
{
var containsPrefix = prefix == "MyString" && ControllerContext.HttpContext.Request.Params.AllKeys.Any(key => key == "Data");
return containsPrefix;
}
public ValueProviderResult GetValue(string key)
{
if (key == "MyString")
{
var data = ControllerContext.RequestContext.HttpContext.Request.Params["Data"];
var myString = data.Split(':')[1];
return new ValueProviderResult(myString, myString, CultureInfo.CurrentCulture);
}
return null;
}
}
and then the action that ties all this together:
[HttpGet]
public ActionResult Test()
{
return View(new SomeModel());
}
[HttpPost]
public ActionResult Test([ValueProvider(typeof(MyValueProvider))]SomeModel model)
{
return View(model);
}
Figured out how to do this. First, create a custom model binder that takes a value provider type in the constructor - but inherits from default modelbinder. This allows you to use standard model binding with a custom value provider:
/// <summary>
/// Uses default model binding, but sets the value provider it uses
/// </summary>
public class SetValueProviderDefaultModelBinder : DefaultModelBinder
{
private Type _ValueProviderType;
public SetValueProviderDefaultModelBinder(Type valueProviderType)
{
if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");
_ValueProviderType = valueProviderType;
}
/// <summary>
/// Before binding the model, set the IValueProvider it uses
/// </summary>
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
bindingContext.ValueProvider = GetValueProvider();
return base.BindModel(controllerContext, bindingContext);
}
private IValueProvider GetValueProvider()
{
return (IValueProvider)Activator.CreateInstance(_ValueProviderType);
}
}
Then we create a model binding attribute that will inject the value provider type in the custom model binder created above, and use that as the model binder:
/// <summary>
/// On the default model binder, replaces the current value provider with the specified value provider. Cannot use custom model binder with this.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
public class SetValueProviderAttribute : CustomModelBinderAttribute
{
// Originally, this was an action filter, that OnActionExecuting, set the controller's IValueProvider, expecting it to be picked up by the default model binder
// when binding the model. Unfortunately, OnActionExecuting occurs AFTER the IValueProvider is set on the DefaultModelBinder. The only way around this is
// to create a custom model binder that inherits from DefaultModelBinder, and in its BindModel method set the ValueProvider and then do the standard model binding.
public SetValueProviderAttribute(Type valueProviderType)
{
if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");
_ValueProviderType = valueProviderType;
}
private Type _ValueProviderType;
public override IModelBinder GetBinder()
{
var modelBinder = new SetValueProviderDefaultModelBinder(_ValueProviderType);
return modelBinder;
}
}

Custom Validation for Duplicate UserName in DB

If you have better approach to handle custom Validation please let me know. I don't want service layer for this please.
Read below 5th option what I want.
I have
1 - IUserRepository -> bool IsUserRegistered(string userName);
2 - UserRepository with Method
readonly EFDBContainer _db = new EFDBContainer();
public bool IsUserRegistered(string userName)
{
return _db.Users.Any(d => d.UserName == userName);
}
3 - Ninject --> UserController is DI
public static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserRepository>().To<UserRepositary>();
}
4 - UserController
private readonly IUserRepository _repository;
public ProfileController(IUserRepository repository)
{
_repository = repository;
}
Create Method on Controller
HttpPost]
public ActionResult Create(string confirmButton, User user)
{
if (ModelState.IsValid)
{
try
{
_repository.Create(user); --> This calling Create Method below before this EnsureValid is Called
return //Do Redirection
}
catch (RuleViolationException)
{
this.UpdateModelStateWithViolations(user, ViewData.ModelState);
}
}
return //to View;
}
Create Method from Repository
public void Create(User user)
{
user.EnsureValid(); --> Go to User object and do validation
//Add object to DB
}
5 - What I want:
Here I want DI so that I can call 1st IsUserRegistered interface method on User object
IsUserRegistered below is not working right now. I need a way to use the Interface
public partial class User: IRuleEntity
{
public List<RuleViolation> GetRuleViolations()
{
List<RuleViolation> validationIssues = new List<RuleViolation>();
if (IsUserRegistered(userName))
validationIssues.Add(new RuleViolation("UserName", UserName, "Username already exists. Please enter a different user name."));
return validationIssues;
}
public void EnsureValid()
{
List<RuleViolation> issues = GetRuleViolations();
if (issues.Count != 0)
throw new RuleViolationException("Business Rule Violations", issues);
}
}
Write your own validation attribute and add it to the user name.
See http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/. It explains how to inject dependencies into validators.
See also the sample application that comes with the Ninject MVC extension it has an example of a validator that has a dependency. https://github.com/ninject/ninject.web.mvc

Resources