Пример #1
0
        public async Task <IHttpActionResult> Post([FromBody] UserLoginModel model)
        {
            IUserRepository userRepository = _uow.GetRepository <IUserRepository>();
            string          hash           = Md5Tool.CreateUtf8Hash(model.Password);
            dynamic         user           = await userRepository.GetQueryable().AsNoTracking().Include(x => x.UserRoles.Select(y => y.Role)).Where(x => x.UserName == model.UserName && x.Password == hash).Select(x => new
            {
                x.UserName,
                Roles = x.UserRoles.Select(y => y.Role.Name)
            }).FirstOrDefaultAsync();

            if (user != null)
            {
                string secretKey       = ConfigurationManager.AppSettings["SecretKey"];
                double tokenExpiration = double.Parse(ConfigurationManager.AppSettings["TokenExpirationMinutes"]);
                string token           = new CustomJwtAuthorizationProvider().GenerateToken(secretKey, user.UserName, user.Roles, tokenExpiration);
                return(Ok(new
                {
                    access_token = token,
                    token_type = "bearer",
                    expires_in = TimeSpan.FromMinutes(tokenExpiration).TotalSeconds
                }));
            }

            return(Unauthorized());
        }
Пример #2
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            AuthenticationHeaderValue authRequest = actionContext.Request.Headers.Authorization;

            if (authRequest != null && authRequest.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase))
            {
                string token = authRequest.Parameter;
                if (!string.IsNullOrEmpty(token))
                {
                    string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(token));
                    string username     = decodedToken.Substring(0, decodedToken.IndexOf(":", StringComparison.Ordinal));
                    string password     = decodedToken.Substring(decodedToken.IndexOf(":", StringComparison.Ordinal) + 1);
                    if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                    {
                        IUserRepository userRepository = _uow.GetRepository <IUserRepository>();
                        string          hash           = Md5Tool.CreateUtf8Hash(password);
                        dynamic         user           = userRepository.GetQueryable().AsNoTracking().Include(x => x.UserRoles.Select(y => y.Role)).Where(x => x.UserName == username && x.Password == hash).Select(x => new
                        {
                            x.UserName,
                            Roles = x.UserRoles.Select(y => y.Role.Name)
                        }).FirstOrDefault();
                        if (user != null)
                        {
                            IList <Claim> claims = new List <Claim>
                            {
                                new Claim(ClaimTypes.Name, user.UserName),
                                new Claim(ClaimTypes.NameIdentifier, user.UserName)
                            };
                            AuthorizeAttribute authorizeAttribute = actionContext.ActionDescriptor
                                                                    .GetCustomAttributes <AuthorizeAttribute>(true)
                                                                    .FirstOrDefault();
                            if (authorizeAttribute != null)
                            {
                                string[] roles = authorizeAttribute.Roles.Split(',');
                                foreach (string role in roles)
                                {
                                    if (user.Roles.Contains(role))
                                    {
                                        claims.Add(new Claim(ClaimTypes.Role, role));
                                    }
                                }
                            }

                            actionContext.RequestContext.Principal =
                                new ClaimsPrincipal(new ClaimsIdentity(claims, "Basic"));
                        }
                    }
                }
            }

            //actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            base.OnAuthorization(actionContext);
        }
        public async Task <IHttpActionResult> Register([FromBody] UserRegisterModel model)
        {
            IUserRepository userRepository = _uow.GetRepository <IUserRepository>();
            User            user           = new User
            {
                UserName = model.UserName,
                Email    = model.Email,
                Password = Md5Tool.CreateUtf8Hash(model.Password)
            };

            userRepository.Add(user);
            await _uow.CommitAsync();

            return(Ok());
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            IUserRepository userRepository = _uow.GetRepository <IUserRepository>();
            string          hash           = Md5Tool.CreateUtf8Hash(context.Password);
            dynamic         user           = await userRepository.GetQueryable().AsNoTracking().Include(x => x.UserRoles.Select(y => y.Role)).Where(x => x.UserName == context.UserName && x.Password == hash).Select(x => new
            {
                x.UserName,
                Roles = x.UserRoles.Select(y => y.Role.Name)
            }).FirstOrDefaultAsync();

            if (user != null)
            {
                ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
                //identity.AddClaim(new Claim("sub", user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserName));
                foreach (string role in user.Roles)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                }

                AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties
                {
                    AllowRefresh = true,
                    IsPersistent = true,
                    IssuedUtc    = DateTimeOffset.Now,
                    ExpiresUtc   = DateTimeOffset.Now.AddMinutes(double.Parse(ConfigurationManager.AppSettings["TokenExpirationMinutes"]))
                });
                context.Validated(ticket);
            }
            else
            {
                context.Rejected();
                //context.SetError("invalid_grant", "The user name or password is incorrect.");
            }
        }
        public void InitializeDatabase(SchoolExpressDbContext context)
        {
            if (!context.Database.Exists())
            {
                return;
            }

            IList <AuthorizeAttribute> authorizeAttributes = Assembly.GetExecutingAssembly().GetTypes()
                                                             .Where(type => typeof(ApiController).IsAssignableFrom(type))
                                                             .SelectMany(type => type.GetMethods())
                                                             .Where(method => method.IsPublic && method.IsDefined(typeof(AuthorizeAttribute), true))
                                                             .Select(m => m.GetCustomAttributes(typeof(AuthorizeAttribute), true).First() as AuthorizeAttribute).ToList();

            string[] controllerRoles = authorizeAttributes.Select(a => a.Roles).Distinct().ToArray();

            DbSet <User> userDbSet = context.Set <User>();
            User         user      = userDbSet.FirstOrDefault(x => x.UserName == "admin");

            if (user == null)
            {
                user = new User
                {
                    UserName = "******",
                    Email    = "*****@*****.**",
                    Password = Md5Tool.CreateUtf8Hash("admin123")
                };
                userDbSet.Add(user);
                context.SaveChanges();
            }

            DbSet <Role>     roleDbSet     = context.Set <Role>();
            DbSet <UserRole> userRoleDbSet = context.Set <UserRole>();

            string[] existingRoles = userRoleDbSet.AsNoTracking().Include(x => x.Role).Where(x => x.UserId == user.Id).Select(x => x.Role.Name).ToArray();

            foreach (string roleName in controllerRoles)
            {
                bool exist = false;
                Role role  = new Role {
                    Name = roleName
                };

                foreach (string existingRole in existingRoles)
                {
                    if (existingRole == roleName)
                    {
                        exist = true;
                        break;
                    }
                }

                if (!exist)
                {
                    roleDbSet.Add(role);
                    context.SaveChanges();
                    context.Entry(role).State = EntityState.Detached;
                }

                if (!existingRoles.Contains(roleName))
                {
                    //int roleId = roleDbSet.AsNoTracking().Where(x => x.Name == roleName).Select(x => x.Id).First();
                    UserRole userRole = new UserRole
                    {
                        UserId = user.Id,
                        RoleId = role.Id
                    };
                    userRoleDbSet.Add(userRole);
                    context.SaveChanges();
                    context.Entry(userRole).State = EntityState.Detached;
                }
            }

            foreach (string existingRoleName in existingRoles)
            {
                bool exist = false;
                foreach (string roleName in controllerRoles)
                {
                    if (existingRoleName == roleName)
                    {
                        exist = true;
                        break;
                    }
                }

                if (!exist)
                {
                    Role role = roleDbSet.AsNoTracking().FirstOrDefault(x => x.Name == existingRoleName);
                    if (role != null)
                    {
                        UserRole userRole = new UserRole
                        {
                            UserId = user.Id,
                            RoleId = role.Id
                        };

                        userRoleDbSet.Attach(userRole);
                        userRoleDbSet.Remove(userRole);
                        context.SaveChanges();
                        context.Entry(userRole).State = EntityState.Detached;

                        roleDbSet.Attach(role);
                        roleDbSet.Remove(role);
                        context.SaveChanges();
                        context.Entry(role).State = EntityState.Detached;
                    }
                }
            }
        }