borahan arslan
borahan arslan

Reputation: 81

Asp.Net Core 3.0 Authorization and Authentication

Wherever I look on the internet, identity is used in the login process related to net.core. Nobody talks about logging in with our normal username and password. We are logging in but this time on checks We cannot use [Authorize(Roles="Admin")] or [Authorize] attribute. To use it, we need to login as follows.

signInManager.PasswordSignInAsync (model.email, model.password, true, true);

Look at this link but the result is the same https://learn.microsoft.com/tr-tr/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1#ord is

If it turns out to be a result here, we are trying for it. What do I need to do to use the above attributes for my own login without using Policy, signInManager.PasswordSignInAsync is doing this exactly what I have added to the message as below, but it did not happen anyway.

My Login Code https://rextester.com/YBJ16358

My Startup

https://rextester.com/VZODZ96615

Upvotes: 0

Views: 815

Answers (1)

borahan arslan
borahan arslan

Reputation: 81

I solved the problem as follows. if username and password true

var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
            identity.AddClaim(new Claim(ClaimTypes.GivenName, user.Name));
            identity.AddClaim(new Claim(ClaimTypes.Surname, user.Surname));
            identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
            foreach (var role in _userManager.GetRolesAsync(user).Result)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            AuthenticationProperties _authentication = new AuthenticationProperties
            {
                IsPersistent = true,
                ExpiresUtc = DateTimeOffset.UtcNow
            };
            await _HttpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });

My Startup

 services.AddAuthentication(options =>
            {
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(config =>
            {
                config.Cookie.Name = "login";
                config.LoginPath = "/Account/Login";
                config.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            });

and App

   app.UseAuthentication();
   app.UseAuthorization();

Upvotes: 1

Related Questions