How to create a simple login in ASP.NET core without database and authorize controller access

Viewed 7686

I am using ASP.NET Core 3.1. How should create a simple ASP.NET Core based login without the use of databases. Lets say instead of using a database, I have the login UserName and Password in the appsettings.json. I could easily access and get the appsettings values. But how should I go about implementing the login functionality and how should I configure services in the startup.cs (in Configure and ConfigureServices).

In Configure() method I have added the app.UseAuthentication();

When I login and move to the Controller class which uses the annotation [Authorize] I get the following error

An unhandled exception occurred while processing the request. InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions). Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

1 Answers

Firstly it's not a good idea to store user's credentials into appsettings.json . If you want to implement that for testing purpose , you can use cookie authentication :

Use cookie authentication without ASP.NET Core Identity

A simple code sample below is for your reference :

  1. In the Startup.ConfigureServices method, create the Authentication Middleware services with the AddAuthentication and AddCookie methods:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Login";
            });
    

    And enable middleware in Configure :

    app.UseAuthentication();
    app.UseAuthorization();
    
  2. You can apply the [Authorize] attribute on protected controllers/actions. When user is not Authenticated , by defalut user will be redirect to LoginPath for cookie authentication . /Account/Login action will show username/password textbox to collect user's credential .

  3. After user inputs credential and click submit button , the post method will check credential and create cookie :

    public class AccountController : Controller
    {
    
        private readonly IOptions<List<UserToLogin>> _users;
        public AccountController (IOptions<List<UserToLogin>> users)
        {
    
            _users = users;
        }
    
        [HttpPost]
        public async Task<IActionResult> Login(UserToLogin userToLogin)
        {
            var user = _users.Value.Find(c => c.UserName == userToLogin.UserName && c.Password == userToLogin.Password);
    
            if (!(user is null))
            {
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name,userToLogin.UserName),
                    new Claim("FullName", userToLogin.UserName),
                    new Claim(ClaimTypes.Role, "Administrator"),
                };
    
                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
                var authProperties = new AuthenticationProperties
                {
    
                    RedirectUri = "/Home/Index",
    
                };
    
                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);
            }
    
            return Redirect("/Accout/Error");
        }
    }
    

    UserToLogin.cs :

    public class UserToLogin
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    
    }
    

    appsettings.json:

    {
        "Users": [
            {
                "UserName": "xxxxxxxx",
                "Password": "xxxxxxx"            
            },
            {
                "UserName": "xxxxxxxx",
                "Password": "xxxxxxxxxxxx"            
            }       
        ],           
    }
    

    And register in ConfigureServices :

    services.Configure<List<UserToLogin>>(Configuration.GetSection("Users"));
    
Related