Пример #1
0
        public override Task <bool> CheckAccessAsync(ResourceAuthorizationContext context)
        {
            //The IdentityServer admin must add the relevant application claim to the user allow the user to access the application
            if (!context.Principal.HasClaim("application", Properties.Settings.Default.ClientId))
            {
                return(Nok());
            }
            switch (context.Resource.First().Value)
            {
                #region A resouce roughly translates to a table in your database
                //This determines if the user has access to the resource.
                //If the user has access, the action parameter will determine
                //whether the action being performed is authorised or not.
                //Again, it's up to you to decided what acions are defined
                //for which resource.
                #endregion
            case "SubUser":
                return(DefaultActionAuthorize(context));

            case "SuperUserEndOfShift":
                return(DefaultActionAuthorize(context));

            case "TempModel":
                return(DefaultActionAuthorize(context));

            default:
                return(Nok());
            }
        }
Пример #2
0
        public override Task <bool> CheckAccessAsync(ResourceAuthorizationContext ctx)
        {
            var resource = ctx.Resource.First().Value;

            if (resource == UhomeResources.VideoClip)
            {
                return(CheckAccessVideoClipAsync(ctx));
            }

            if (resource == UhomeResources.Case)
            {
                return(CheckAccessCaseAsync(ctx));
            }

            if (resource == UhomeResources.User)
            {
                return(CheckAccessUserAsync(ctx));
            }

            if (resource == UhomeResources.DownloadItem)
            {
                return(CheckAccessDownloadItemAsync(ctx));
            }

            if (resource == UhomeResources.Event)
            {
                return(CheckAccessEventAsync(ctx));
            }

            return(Nok());
        }
Пример #3
0
        public override Task <bool> CheckAccessAsync(ResourceAuthorizationContext context)
        {
            //TRACE EVERYTHING. We will have to clean out logs every week, month or something.
            Logger.Trace("\n\nClaimsAuthorizationManager\n_______________________\n");

            Logger.Trace("\nAction:");
            Logger.Trace("  " + context.Action.First().Value);

            Logger.Trace("\nResources:");
            foreach (var resource in context.Resource)
            {
                Logger.Trace("  " + resource.Value);
            }

            Logger.Trace("\nClaims:");
            foreach (var claim in context.Principal.Claims)
            {
                Logger.Trace("  " + claim.Value);
            }
            Logger.Trace("  " + context.Action.First().Value);

            //Handle Authorization. So it dont need to be in a big switch, we need to figure out how we want to this.
            //I just want authoriation seperated from business logic, and unit tests can be made on the authorizationManager.

            var action = context.Action.First().Value;



            return(Ok());
        }
Пример #4
0
        private Task <bool> CheckRolesAccessAsync(ResourceAuthorizationContext context)
        {
            var principal    = context.Principal;
            var resourceName = Resources.Roles;

            if (principal.Identity.IsAuthenticated)
            {
                var actionName = GetActionName(context);

                if (HasResourceAndAction(principal, resourceName, actionName))
                {
                    // No se puede eliminar el Rol 1
                    if (actionName == Resources.RolesActions.Eliminar)
                    {
                        if (GetResourceId(context) == "1")
                        {
                            return(Nok());
                        }
                    }

                    return(Ok());
                }
            }
            return(Nok());
        }
Пример #5
0
        private Task <bool> CheckRealmAssetAccessAsync(ResourceAuthorizationContext context, Realm realm, string path)
        {
            var action = context.Action.First().Value;

            switch (action)
            {
            case GunchoResources.AssetActions.Create:
            case GunchoResources.AssetActions.Import:
                //XXX
                return(Nok());

            case GunchoResources.AssetActions.Delete:
            case GunchoResources.AssetActions.Edit:
                return(Eval(HasRealmAccessLevel(context, realm, RealmAccessLevel.EditSource)));

            case GunchoResources.AssetActions.Share:
                return(Eval(HasRealmAccessLevel(context, realm, RealmAccessLevel.EditAccess)));

            case GunchoResources.AssetActions.List:
            case GunchoResources.AssetActions.View:
            case GunchoResources.AssetActions.ViewHistory:
                return(Eval(HasRealmAccessLevel(context, realm, RealmAccessLevel.ViewSource)));
            }

            return(Nok());
        }
Пример #6
0
        private Task <bool> CheckUsuariosAccessAsync(ResourceAuthorizationContext context)
        {
            var principal    = context.Principal;
            var resourceName = Resources.Usuarios;

            if (principal.Identity.IsAuthenticated)
            {
                var actionName = GetActionName(context);

                if (HasResourceAndAction(principal, resourceName, actionName))
                {
                    // No se puede editar o eliminar a si mismo
                    if (actionName == Resources.UsuariosActions.Editar || actionName == Resources.UsuariosActions.Eliminar)
                    {
                        var userId = principal.FindFirst("user_sid").Value;
                        if (GetResourceId(context) == userId)
                        {
                            return(Nok());
                        }
                    }

                    return(Ok());
                }
            }
            return(Nok());
        }
Пример #7
0
        private Task <bool> DefaultActionAuthorize(ResourceAuthorizationContext context)
        {
            #region Below is a sample of what actions are.
            //You can create actions to suit the requirements of your app
            //such as "delete", "update", "create" etc
            #endregion
            switch (context.Action.First().Value)
            {
            case "read":
                return(Eval(context.Principal.HasClaim(ClaimTypes.Role, "reader")));

            case "edit":
                return(Eval(context.Principal.HasClaim(ClaimTypes.Role, "editor")));

            case "create":
                return(Eval(context.Principal.HasClaim(ClaimTypes.Role, "creator")));

            case "delete":
                return(Eval(context.Principal.HasClaim(ClaimTypes.Role, "remover")));

            case "Transactions":
                return(Eval(context.Principal.HasClaim(ClaimTypes.Role, "transactions")));   //not added yet

            case "PrintOut":
                return(Eval(context.Principal.HasClaim(ClaimTypes.Role, "printout")));   //not added yet

            default:
                return(Nok());
            }
        }
Пример #8
0
        public void AnonymousCannotEditEvent()
        {
            var ctx1 = new ResourceAuthorizationContext(Anonymous,
                                                        UhomeResources.EventActions.Edit, UhomeResources.Event);

            Assert.IsFalse(subject.CheckAccessAsync(ctx1).Result);
        }
Пример #9
0
        public void AnonymousCannotListUser()
        {
            var ctx = new ResourceAuthorizationContext(Anonymous,
                                                       UhomeResources.Actions.List, UhomeResources.User);

            Assert.IsFalse(subject.CheckAccessAsync(ctx).Result);
        }
Пример #10
0
        public Task <bool> CheckAccessVideoClipAsync(ResourceAuthorizationContext ctx)
        {
            var user = ctx.Principal.Identity;

            if (!user.IsAuthenticated)
            {
                return(Nok());
            }

            var action = ctx.Action.First().Value;

            if (action == UhomeResources.VideoClipActions.View)
            {
                return(Ok());
            }

            if (action == UhomeResources.VideoClipActions.Edit)
            {
                if (ctx.Principal.IsInRole("Admin"))
                {
                    return(Ok());
                }
            }

            return(Nok());
        }
Пример #11
0
        public override Task <bool> CheckAccessAsync(ResourceAuthorizationContext context)
        {
            var           permissions = db.Permission.Where(p => true).ToList();
            List <string> clients     = new List <string>()
            {
                "c-01", "c-02", "c-04"
            };                                                                //this should not be hard code but get from database
            var sources = context.Resource;
            var claims  = context.Principal;
            var aa      = context.Action;

            if (permissions.Any(p => sources.Any(r => r.Value == p.ResourceName) && claims.HasClaim("client_role", p.RoleName)))
            {
                return(Ok());
            }
            if (permissions.Any(p => context.Action.Any(a => a.Value == p.ActionName) && claims.HasClaim("client_role", p.RoleName)))
            {
                return(Ok());
            }
            if (permissions.Any(p => context.Action.Any(a => a.Value == p.ActionName) && clients.Contains(context.Principal.Claims.First(c => c.Type == "client_id").Value)))
            {
                return(Ok());
            }
            return(Nok());
        }
Пример #12
0
        public async Task Invoke(IDictionary <string, object> env)
        {
            var context = new OwinContext(env);

            var resourceContext = context.ResolveDependency <ResourceContext>();
            var options         = context.ResolveDependency <MultiTenantBlobStorageOptions>();

            resourceContext.Route = await context.ResolveDependency <IRequestTenantResolver>().GetRouteAsync(context.Request);

            resourceContext.Action = string.Format("{0}_{1}{2}",
                                                   resourceContext.Route.Path.IsMissing() ? (resourceContext.Route.Resource.IsMissing() ? Constants.Actions.TenantPrefix : Constants.Actions.ContainerPrefix) : Constants.Actions.BlobPrefix,
                                                   context.Request.Method.ToLower(),
                                                   context.Request.Query["comp"].IsPresent() ? "_" + context.Request.Query["comp"] : "");



            var requestHandler = context.ResolveDependency <IRequestHandlerService>();
            var authService    = context.ResolveDependency <IAuthenticationService>();

            resourceContext.User = context.Authentication.User = await authService.AuthenticateRequestAsync(context.Request, options) ?? new ClaimsPrincipal();

            ResourceAuthorizationContext resourceAuthContext = null;

            if (await authService.SkipAuthorizationManagerAsync(context, resourceContext) || await context.CheckAccessAsync(resourceAuthContext = resourceContext.GetResourceAuthorizationContext()))
            {
                await requestHandler.HandleAsync(context, resourceContext);
            }
            else
            {
                HandleUnauthorizedRequest(context, resourceAuthContext);
            }

            // context.Response.Body.Flush();
        }
Пример #13
0
        public void AuthenticatedStaffCanViewAssignedCase()
        {
            var staff            = User("StaffUser", new string[] { "Staff" });
            var applicationUser1 = new ApplicationUser();

            applicationUser1.UserName = staff.Identity.Name;
            db.Users.Add(applicationUser1);
            var applicationUser2 = new ApplicationUser();

            applicationUser2.UserName = "******";
            db.Users.Add(applicationUser2);
            var @case = CreateCase();

            @case.ApplicationUserId = applicationUser2.Id;
            db.Cases.Add(@case);
            @case.CaseAssignment = new CaseAssignment();
            @case.CaseAssignment.ApplicationUserId = applicationUser1.Id;
            @case.CaseAssignment.AssignmentDate    = System.DateTime.Now;
            @case.UpdatedAt = System.DateTime.Now;
            db.SaveChanges();

            var ctx = new ResourceAuthorizationContext(staff,
                                                       UhomeResources.Actions.View, UhomeResources.Case, @case.ID.ToString());

            Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
        }
Пример #14
0
        public void Authenticated_Manager_Cannot_Edit_Track()
        {
            var ctx = new ResourceAuthorizationContext(User("test", "Manager"),
                                                       ChinookResources.TrackActions.Edit,
                                                       ChinookResources.Track);

            Assert.IsFalse(subject.CheckAccessAsync(ctx).Result);
        }
Пример #15
0
        public void AuthenticatedAdminCanEditUser()
        {
            var admin = User("AdminUser", new string[] { "Admin" });
            var ctx   = new ResourceAuthorizationContext(admin,
                                                         UhomeResources.Actions.Edit, UhomeResources.User);

            Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
        }
Пример #16
0
        public void AuthenticatedNonAdminCannotEditUser()
        {
            var user = User("John");
            var ctx  = new ResourceAuthorizationContext(user,
                                                        UhomeResources.Actions.Edit, UhomeResources.User);

            Assert.IsFalse(subject.CheckAccessAsync(ctx).Result);
        }
Пример #17
0
        public void Authenticated_Admin_Can_Edit_Track()
        {
            var ctx = new ResourceAuthorizationContext(User("test", "Admin"),
                                                       ChinookResources.TrackActions.Edit,
                                                       ChinookResources.Track);

            Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
        }
Пример #18
0
        public void Authenticated_Can_View_Album()
        {
            var ctx = new ResourceAuthorizationContext(User("test"),
                                                       ChinookResources.AlbumActions.View,
                                                       ChinookResources.Album);

            Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
        }
Пример #19
0
        public void Anonymous_Cannot_Access_Track()
        {
            var ctx = new ResourceAuthorizationContext(Anonymous,
                                                       ChinookResources.TrackActions.Edit,
                                                       ChinookResources.Track);

            Assert.IsFalse(subject.CheckAccessAsync(ctx).Result);
        }
Пример #20
0
        public void AuthenticatedCanListCase()
        {
            var user = User("John");
            var ctx  = new ResourceAuthorizationContext(user,
                                                        UhomeResources.Actions.List, UhomeResources.Case);

            Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
        }
Пример #21
0
        public void AuthenticatedManagerCanAdminEditCase()
        {
            var manager = User("ManagerUser", new string[] { "Manager" });
            var ctx     = new ResourceAuthorizationContext(manager,
                                                           UhomeResources.Actions.AdminEdit, UhomeResources.Case);

            Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
        }
Пример #22
0
 public override Task <bool> CheckAccessAsync(ResourceAuthorizationContext context)
 {
     return(this.Eval(
                this.currentPolicies.ContainsPolicy(
                    context.Resource.First().Value,
                    context.Action.First().Value,
                    context.Principal.Claims.Where(x => x.Type.Equals(ClaimTypes.Role)).Select(x => x.Value).ToList())));
 }
        private Task <bool> CheckProfileEditAccessAsync(ResourceAuthorizationContext context)
        {
            var profileUser = context.Resource.Skip(1).Take(1).Single().Value;
            var username    = context.Principal.Identity.Name;

            username = username.Substring(username.LastIndexOf(@"\", StringComparison.OrdinalIgnoreCase) + 1);
            return(Eval(profileUser == username));
        }
 private Task <bool> AuthorizeContactDetails(ResourceAuthorizationContext context)
 {
     switch (context.Action.First().Value)
     {
     default:
         return(Nok());
     }
 }
Пример #25
0
        public void Authenticated_NonAdmin_Cannot_Edit_Album()
        {
            var ctx = new ResourceAuthorizationContext(User("test"),
                                                       ChinookResources.AlbumActions.Edit,
                                                       ChinookResources.Album);

            Assert.IsFalse(subject.CheckAccessAsync(ctx).Result);
        }
Пример #26
0
        public void AuthenticatedCanViewEvent()
        {
            var user = User("John");
            var ctx  = new ResourceAuthorizationContext(user,
                                                        UhomeResources.EventActions.View, UhomeResources.Event);

            Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
        }
Пример #27
0
        Task <bool> CheckTodoReadAccessAsync(ResourceAuthorizationContext context)
        {
            if (!context.Principal.Claims.Any(claim => claim.Type == "scope" && claim.Value == "read"))
            {
                return(Nok());
            }

            return(Ok());
        }
Пример #28
0
        public void AuthenticatedAdminCanEditEvent()
        {
            var roles = new string[] { "Admin" };
            var user  = User("John", roles);
            var ctx   = new ResourceAuthorizationContext(user,
                                                         UhomeResources.EventActions.Edit, UhomeResources.Event);

            Assert.IsTrue(subject.CheckAccessAsync(ctx).Result);
        }
Пример #29
0
        public void AuthenticatedNonAdminCannotEditEvent()
        {
            var roles = new string[] { "Manager", "Staff", "FreeAccount", "SilverAccount", "GoldAccount" };
            var user  = User("John", roles);
            var ctx   = new ResourceAuthorizationContext(user,
                                                         UhomeResources.EventActions.Edit, UhomeResources.Event);

            Assert.IsFalse(subject.CheckAccessAsync(ctx).Result);
        }
Пример #30
0
        public static Task <bool> CheckAccessAsync(this HttpRequestMessage request, IEnumerable <Claim> actions, IEnumerable <Claim> resources)
        {
            var authorizationContext = new ResourceAuthorizationContext(
                request.GetOwinContext().Authentication.User ?? Principal.Anonymous,
                actions,
                resources);

            return(request.CheckAccessAsync(authorizationContext));
        }