How to implement custom authentication in ASP.NET MVC 5
Yes, you can. Authentication and Authorization parts work independently. If you have your own authentication service you can just use OWIN's authorization part. Consider you already have a UserManager
which validates username
and password
. Therefore you can write the following code in your post back login action:
[HttpPost]
public ActionResult Login(string username, string password)
{
if (new UserManager().IsValid(username, password))
{
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, username),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name,username),
// optionally you could add roles if any
new Claim(ClaimTypes.Role, "RoleName"),
new Claim(ClaimTypes.Role, "AnotherRole"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
// invalid username or password
ModelState.AddModelError("", "invalid username or password");
return View();
}
And your user manager can be something like this:
class UserManager
{
public bool IsValid(string username, string password)
{
using(var db=new MyDbContext()) // use your DbConext
{
// for the sake of simplicity I use plain text passwords
// in real world hashing and salting techniques must be implemented
return db.Users.Any(u=>u.Username==username
&& u.Password==password);
}
}
}
In the end, you can protect your actions or controllers by adding an Authorize
attribute.
[Authorize]
public ActionResult MySecretAction()
{
// all authorized users can use this method
// we have accessed current user principal by calling also
// HttpContext.User
}
[Authorize(Roles="Admin")]
public ActionResult MySecretAction()
{
// just Admin users have access to this method
}
ASP.NET MVC 5: Custom Authentication
It seems to me that you do not provide authentication information with each request after the authentication. Can you verify that you have some session cookie or authentication header sent with each request after the authentication happens?
MVC5: Custom Authentication
I ended up creating a new MVC application with no authentication. Then I created a custom module that hooks into the ASP.NET request pipeline (https://msdn.microsoft.com/en-us/library/bb470252.aspx)
public class MyAuthModule : IHttpModule
{
public void Dispose()
{
// Implement when you need to release unmanaged resources
}
public void Init(HttpApplication context)
{
context.AuthenticateRequest += Context_AuthenticateRequest;
context.PostAuthenticateRequest += Context_PostAuthenticateRequest;
}
private void Context_AuthenticateRequest(object sender, EventArgs e)
{
// Call custom library to authenticate
// and create a new ClaimsPrincipal with the info from the JSON object.
}
private void Context_PostAuthenticateRequest(object sender, EventArgs e)
{
// Optional: Inspect the ClaimsPrincipal and add more claims
}
}
Then register this module in web.config:
<system.webServer>
<modules>
<add name="MyAuthModule"
type="MvcDemo.Auth.MyAuthModule, MvcDemo" />
</modules>
</system.webServer>
Related Topics
How to Create an Expression Tree Calling Ienumerable<Tsource>.Any(...)
Owin's Getexternallogininfoasync Always Returns Null
Excel Error Hresult: 0X800A03Ec While Trying to Get Range with Cell's Name
How to Automate Sap Gui with C#
Wpf Error 40 Bindingexpression Path Error: Property Not Found on 'Object'
When to Use a Sortedlist<Tkey, Tvalue> Over a Sorteddictionary<Tkey, Tvalue>
Wait for an Ajax Call to Complete with Selenium 2 Webdriver
Custom JSON Serialization for Each Item in Ienumerable
The Notorious Yet Unaswered Issue of Downloading a File When Windows Security Is Required
Starting and Stopping Iis Express Programmatically
Give Some Command to View in Mvvm
How to Make a Combobox Non-Editable in .Net