Esempio n. 1
0
 protected override void Arrange()
 {
     Initialize();
     _filter  = new AuthenticateAttribute();
     _context = GetBaseAuthenticationContext();
     SetAuthorizationHeader(_context, "Bearer", null);
 }
        public void should_not_be_able_to_continue_if_the_employee_id_is_a_group()
        {
            // Mock out the context to run the action filter.
            var header = new Mock <HttpRequestHeaders>();

            var request = new Mock <HttpRequestMessage>();

            request.Setup(r => r.Headers).Returns(header.Object);

            var routeData = new RouteData(); //

            routeData.Values.Add("employeeId", "123");

            var actionExecutedContext = new Mock <HttpActionContext>();

            actionExecutedContext.SetupGet(c => c.Request).Returns(request.Object);

            var filter = new AuthenticateAttribute();

            filter.OnActionExecuting(actionExecutedContext.Object);



            // Assert
            //Assert.That(actionExecutedContext.Object.Result, Is.InstanceOfType(typeof(ContentResult)));
            //Assert.That((actionExecutedContext.Object.Result as ContentResult).Content, Is.EqualTo(filter.HtmlResultString));
        }
 public SessionController(Domain.Interfaces.Services.ApplicationServices.IUsuarioService usuarioService, ISessionService sessionService, ILoginService loginService, INewSessionService newSessionService, ILogger logger
                          , AuthenticateAttribute authenticateAttribute, TokenConfigurations tokenConfigurations)
 {
     _loginService          = loginService;
     _usuarioService        = usuarioService;
     _sessionService        = sessionService;
     _newSessionService     = newSessionService;
     _authenticateAttribute = authenticateAttribute;
     _logger = logger;
     _tokenConfigurations = tokenConfigurations;
 }
Esempio n. 4
0
        public void AuthorizeSubscriptionServiceRequests(IRequest request, IResponse response, object dto)
        {
            if (IsSubscriptionService(request.Dto.GetType()))
            {
                var attribute = new AuthenticateAttribute();
                AsyncHelper.RunSync(() => attribute.ExecuteAsync(request, response, dto));

                var requiredRoles = GetRequiredRoles(request.Dto);
                if (requiredRoles.Length > 0)
                {
                    RequiresAnyRoleAttribute.AssertRequiredRoles(request, requiredRoles);
                }
            }
        }
Esempio n. 5
0
        public void RedirectIfNotAuthenticated(string redirectUrl = null)
        {
            if (IsAuthenticated)
            {
                return;
            }

            redirectUrl = redirectUrl
                          ?? AuthenticateService.HtmlRedirect
                          ?? HostContext.Config.DefaultRedirectPath
                          ?? HostContext.Config.WebHostUrl
                          ?? "/";
            AuthenticateAttribute.DoHtmlRedirect(redirectUrl, Request, Response, includeRedirectParam: true);
            throw new StopExecutionException();
        }
Esempio n. 6
0
            protected override void Arrange()
            {
                _setContextCalled = false;

                var tokenValidator = MockRepository.GenerateStub <IOAuthTokenValidator>();

                tokenValidator.Stub(t => t.GetClientDetailsForTokenAsync(Arg <string> .Is.Anything))
                .Return(
                    Task.FromResult(
                        new ApiClientDetails
                {
                    ApiKey = "key", ClaimSetName = "claimSetName", NamespacePrefixes = new List <string>
                    {
                        "namespacePrefix"
                    },
                    EducationOrganizationIds = new List <int>(), IsSandboxClient = false
                }));

                var contextProvider = MockRepository.GenerateStub <IApiKeyContextProvider>();

                contextProvider.Stub(c => c.SetApiKeyContext(Arg <ApiKeyContext> .Is.Anything))
                .WhenCalled(call => { _setContextCalled = true; });

                var identityProvider = MockRepository.GenerateStub <IClaimsIdentityProvider>();

                identityProvider.Stub(
                    i => i.GetClaimsIdentity(
                        Arg <IEnumerable <int> > .Is.Anything,
                        Arg <string> .Is.Anything,
                        Arg <IReadOnlyList <string> > .Is.Anything,
                        Arg <IReadOnlyList <string> > .Is.Anything))
                .Return(new ClaimsIdentity());

                var configProvider = MockRepository.GenerateStub <IConfigValueProvider>();

                configProvider.Stub(i => i.GetValue("ExpectedUseSandboxValue"))
                .Return("false");

                Initialize(tokenValidator, contextProvider, identityProvider, configProvider);
                _filter  = new AuthenticateAttribute();
                _context = GetBaseAuthenticationContext();

                SetAuthorizationHeader(
                    _context,
                    "Bearer",
                    Guid.NewGuid()
                    .ToString());
            }
Esempio n. 7
0
            protected override void Arrange()
            {
                var tokenValidator = MockRepository.GenerateStub <IOAuthTokenValidator>();

                tokenValidator.Stub(t => t.GetClientDetailsForTokenAsync(Arg <string> .Is.Anything))
                .Return(Task.FromResult(new ApiClientDetails()));

                Initialize(tokenValidator);
                _filter  = new AuthenticateAttribute();
                _context = GetBaseAuthenticationContext();

                SetAuthorizationHeader(
                    _context,
                    "Bearer",
                    Guid.NewGuid()
                    .ToString());
            }
Esempio n. 8
0
        public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            AuthenticateAttribute.AuthenticateIfBasicAuth(req, res);

            var session = req.GetSession();

            if (session != null)
            {
                if (HasAllRoles(session))
                {
                    return;
                }
            }

            res.StatusCode        = (int)HttpStatusCode.Unauthorized;
            res.StatusDescription = "Invalid Role";
            res.Close();
        }
        public void ListGenerator()
        {
            List <Type>          controllers = RootController.ControllerTypes;
            List <MenuReference> menuList    = new List <MenuReference>();

            foreach (Type c in controllers)
            {
                // Get a list of all the endpoints on this controller
                MethodInfo[] actions = c.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                foreach (MethodInfo a in actions)
                {
                    // Look for a menu attribute that matches our requested menu
                    IrisMenuAttribute menu = a.GetCustomAttribute <IrisMenuAttribute>();
                    // We can skip over this action since we couldn't find a matching menu item
                    if (menu == null)
                    {
                        continue;
                    }

                    AuthenticateAttribute authAttribute = a.GetCustomAttribute <AuthenticateAttribute>(true);
                    if (authAttribute != null && authAttribute.MenuService() == false)
                    {
                        continue;
                    }

                    string[] route = menu.GetPathChain();
                    // Get token info for this step
                    string t = route[0];
                    string u = route[1];
                    string p = "";
                    if (route.Length == 3)
                    {
                        p = route[2];
                    }
                    MenuReference item = null;
                    if (u == "onGridReports" || u == "openProfileWindow" || u == "requestEntryWindow" || u == "roadRequestEntryWindow" || u == "utilityRequestEntryWindow" || u == "streetWiseConfigurationWindow")
                    {
                        item = new MenuReference {
                            Text = t, URL = u
                        }
                    }
                    ;
                    else if (p != "")
                    {
                        item = new MenuReference {
                            Text = t, URL = "/" + u + "/" + p
                        }
                    }
                    ;
                    else
                    {
                        item = new MenuReference {
                            Text = t, URL = "/" + u + "/" + u
                        }
                    };
                    menuList.Add(item);
                }
            }
            HttpRuntime.Cache.Remove("IrisMenu");
            HttpRuntime.Cache.Add("IrisMenu", new SelectList(menuList, "URL", "Text"), null, DateTime.Now.AddDays(14), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
        }
    }
Esempio n. 10
0
        /*
         * // not needed anymore, we do the type resolution ourselves now.
         *
         * private static readonly string[] _hideKnownAssemblies = new[] {
         *  "ServiceStack", // exclude the service stack assembly
         *   "ClrPlus",
         *  "b03f5f7f11d50a3a", // Microsoft
         *  "b77a5c561934e089", // Microsoft
         *  "31bf3856ad364e35" // Microsoft
         * };
         *
         * private static IEnumerable<Assembly> GetActiveAssemblies() {
         *  return AppDomain.CurrentDomain.GetAssemblies().Where(each => !_hideKnownAssemblies.Any(x => each.FullName.IndexOf(x) > -1));
         * }
         */

        public override void Configure(Container container)
        {
            _configured = true;
            // Feature disableFeatures = Feature.Jsv | Feature.Soap;
            SetConfig(new EndpointHostConfig {
                // EnableFeatures = Feature.All.Remove(disableFeatures), //all formats except of JSV and SOAP
                DebugMode             = true,             //Show StackTraces in service responses during development
                WriteErrorsToResponse = false,            //Disable exception handling
                DefaultContentType    = ContentType.Json, //Change default content type
                AllowJsonpRequests    = true,             //Enable JSONP requests
                ServiceName           = "RestService",
            });

#if DEBUG
            LogManager.LogFactory = new DebugLogFactory();
#endif
            using (var ps = RunspacePool.Dynamic()) {
                foreach (var restCommand in _activeCommands)
                {
                    PSObject command = ps.LookupCommand(restCommand.Name);

                    if (command != null)
                    {
                        var cmdletInfo = (command.ImmediateBaseObject as CmdletInfo);
                        if (cmdletInfo != null)
                        {
                            dynamic d = new AccessPrivateWrapper((ServiceController as ServiceController));

                            // for each type we're adding, see if it's already been added already.
                            if (!d.requestExecMap.ContainsKey(cmdletInfo.ImplementingType))
                            {
                                (ServiceController as ServiceController).RegisterGService(GetTypeFactory(cmdletInfo.ImplementingType), cmdletInfo.ImplementingType);
                                (ServiceController as ServiceController).RegisterNService(GetTypeFactory(cmdletInfo.ImplementingType), cmdletInfo.ImplementingType);
                            }

                            ReverseLookup.AddOrSet(cmdletInfo.ImplementingType, restCommand);
                            Routes.Add(cmdletInfo.ImplementingType, "/" + restCommand.PublishAs + "/", "GET");
                        }
                        else
                        {
                            throw new ClrPlusException("command isn't cmdletinfo: {0}".format(command.GetType()));
                        }
                    }
                }
            }

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new CustomBasicAuthProvider(),
                // new CustomCredentialsAuthProvider(),
            }
                                        ));

            // stick a request filter in to validate that the user has the right to actually
            // call this method.

            RequestFilters.Add((request, response, requestDto) => {
                var restCommand = ReverseLookup[requestDto.GetType()];

                // is this one of the restCommands?
                // and does it has roles defined?
                if (restCommand != null && !restCommand.Roles.IsNullOrEmpty())
                {
                    // ensure we're authenticated if the user passed the right stuff in the request
                    try {
                        AuthenticateAttribute.AuthenticateIfBasicAuth(request, response);
                    } catch (Exception e) {
                        Console.WriteLine(e.Message);
                        response.StatusCode = 401;
                        response.AddHeader("WWW-Authenticate", "Basic realm=\"rest-service\"");
                        response.StatusDescription = "Unauthorized";
                        response.EndServiceStackRequest(false);
                        return;
                    }

                    // get the session object.
                    var session = request.GetSession(false);

                    // check if we got our authentication.
                    if (!session.IsAuthenticated)
                    {
                        response.StatusCode = 401;
                        response.AddHeader("WWW-Authenticate", "Basic realm=\"rest-service\"");
                        response.StatusDescription = "Unauthorized";
                        response.EndServiceStackRequest(false);
                        return;
                    }

                    // validate the user has the role.
                    if (!restCommand.Roles.Any(session.HasRole))
                    {
                        response.StatusCode = 403;

                        response.StatusDescription = "Forbidden";
                        response.EndServiceStackRequest(false);
                    }

                    var req = (requestDto as IHasSession);
                    if (req != null)
                    {
                        req.Session = session;
                    }
                }
            });
        }
Esempio n. 11
0
 protected override void Arrange()
 {
     Initialize();
     _filter  = new AuthenticateAttribute();
     _context = GetBaseAuthenticationContext();
 }