Beispiel #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
            .AddBasic(options =>
            {
                options.Realm = Configuration.GetSection("AppAuth")["realm"] ?? "bruno";
                options.AllowInsecureProtocol = true;

                var ldapAuth   = new LdapAuth(_logger);
                options.Events = new BasicAuthenticationEvents
                {
                    OnValidateCredentials = context =>
                    {
                        //if (context.Username == context.Password)
                        if (ldapAuth.Validate(context.Username, context.Password))
                        {
                            var claims = new[]
                            {
                                new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
                                new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
                            };

                            context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                            context.Success();
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthorization();

            services.AddMvc(
                //config =>
                //{
                //    var policy = new AuthorizationPolicyBuilder()
                //                     .RequireAuthenticatedUser()
                //                     .Build();
                //    config.Filters.Add(new AuthorizeFilter(policy));
                //}
                ).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            userForLoginDto.Username = userForLoginDto.Username.ToLower();
            // Check if dawgtag or not
            // SIU85[0-9]{7}
            Console.WriteLine("\n\n\n\nLOGGING IN");
            Console.WriteLine(userForLoginDto.Username);
            Console.WriteLine(userForLoginDto.Password);

            Claim idClaim;
            Claim nameClaim;
            Claim roleClaim;
            Regex dawgtagRx = new Regex("siu85[0-9]{7}", RegexOptions.Compiled);


            if (dawgtagRx.IsMatch(userForLoginDto.Username))
            {
                Console.WriteLine("Determined to be User.");
                // LDAP login
                LdapAuth ldapAuth = new LdapAuth();

                // Validate user via LDAP
                if (!ldapAuth.validateUser(userForLoginDto))
                {
                    return(Unauthorized());
                }

                // Assign security claims
                idClaim   = new Claim(ClaimTypes.NameIdentifier, userForLoginDto.Username);
                nameClaim = new Claim(ClaimTypes.Name, "user");
                roleClaim = new Claim(ClaimTypes.Role, "standard");
            }
            else
            {
                // Admin login
                if (userForLoginDto.Username != _config.GetSection("AdminPassword:Username").Value || userForLoginDto.Password != _config.GetSection("AdminPassword:Password").Value)
                {
                    return(Unauthorized());
                }

                Console.WriteLine("Determined to be Admin");
                idClaim   = new Claim(ClaimTypes.NameIdentifier, userForLoginDto.Username);
                nameClaim = new Claim(ClaimTypes.Name, userForLoginDto.Username);
                roleClaim = new Claim(ClaimTypes.Role, "admin");
            }

            var claims = new []
            {
                idClaim,
                nameClaim,
                roleClaim
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
Beispiel #3
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            // Check if dawgtag or not
            // SIU85[0-9]{7}

            Claim idClaim;
            Claim nameClaim;
            Claim roleClaim;

            Regex dawgtagRx = new Regex("[Ss][Ii][Uu]85[0-9]{7}", RegexOptions.Compiled);


            if (dawgtagRx.IsMatch(userForLoginDto.Username))
            {
                // LDAP login
                LdapAuth ldapAuth = new LdapAuth();

                // Validate user via LDAP
                var valid = ldapAuth.validateUser(userForLoginDto);

                // if invalid
                if (!valid)
                {
                    return(Unauthorized());
                }

                // Assign security claims
                idClaim   = new Claim(ClaimTypes.NameIdentifier, userForLoginDto.Username);
                nameClaim = new Claim(ClaimTypes.Name, userForLoginDto.Username);
                roleClaim = new Claim(ClaimTypes.Role, "standard");
            }

            else
            {   /**
                 * // Admin login
                 *
                 * var adminFromRepo = await _repo
                 *  .Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);
                 *
                 * if (adminFromRepo == null)
                 *  return Unauthorized();
                 *
                 *
                 * idClaim = new Claim(ClaimTypes.NameIdentifier, adminFromRepo.Id.ToString());
                 * nameClaim = new Claim(ClaimTypes.Name, adminFromRepo.Username);
                 * roleClaim = new Claim(ClaimTypes.Role, "admin");
                 */
                idClaim   = new Claim(ClaimTypes.NameIdentifier, userForLoginDto.Username);
                nameClaim = new Claim(ClaimTypes.Name, userForLoginDto.Username);
                roleClaim = new Claim(ClaimTypes.Role, "admin");
            }

            var claims = new []
            {
                idClaim,
                nameClaim,
                roleClaim
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }