1

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?

Mihai Bratulescu
  • 1,915
  • 3
  • 27
  • 43

1 Answers1

1

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("");
   }
}
STO
  • 10,390
  • 8
  • 32
  • 32
  • I understood the ideea of `CustomLoginLogic(form)` that just returns the user ID based on my BL needs but the claim part I don't fully understand. What is the name of the claim? And how do I use it to authorize access based on this? Using roles I was doing: `[Authorize(Roles = "Admin")]` – Mihai Bratulescu Jul 29 '15 at 10:10
  • I guess you could also add another claim with type `ClaimTypes.Role` and check if it helps for role-based authorization – STO Jul 29 '15 at 10:28
  • I figured out the purpose of `ClaimTypes` but I have 1 last issue: it does not reddirect to login when accessing a controller action with a role it does not have. How do I do this last step? I tryed: `options.LoginPath = new PathString("/Account/Login");` – Mihai Bratulescu Jul 29 '15 at 10:56
  • never mind, it was going to my dummy always authentication controller and redirecting back – Mihai Bratulescu Jul 29 '15 at 11:19