Search code examples
asp.net-core-mvcasp.net-identity-3

How to make vNext use my custom Identity code?


I want to implement a custom sign in system because my users are stored in a different database and I just have a dll to verify credentials so I don't want a database. I just want the ability to login (with roles: admin and user) and logout for this app. In the database of the tool I save just the username and his role (no password).

First: what classes must I implement achieve the desired effect?

Second: how do I configure the app so it will use my custom code?


Solution

  • I'm not sure I did it 100% right way, but take a look:

    1. Configure cookies authentication

            public void Configure(IApplicationBuilder app)
            {
                app.UseCookieAuthentication(options =>
                {
                    options.AutomaticAuthentication = true;
                    options.SlidingExpiration = true;
                    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                });
    
            }
    

    2. Sign-In

    public class LoginController: Controller 
    {
    
       public IActionResult SignIn(LoginModel form)
       {    
            var userId = CustomLoginLogic(form);
    
            var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.NameIdentifier, result.UserId)
                    };
            var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));                       
            context.Response.SignIn(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
            return Content("");
       }
    }