Asp.net MVC let you intercept the actions via a feature they call: Filters. Filters are just attributes that you decorate into actions and them allow to you make an stop before or after the action-methods are executed (also are filters to intercept code before/after the result is executed, errors are thrown, etc). There are a few kind of Filter attributes, in the picture bellow into the blue square you’ve what filters came supported out-of-the-box.

Today we are going to talk about the AuthorizeAttribute and how to extend and test it.

AuthorizeAttribute (from the Msdn):

Represents an attribute that is used to restrict access by callers to an action method.

This filter is the first to be called when the Controller Action Invoker try to run Action methods. You can set into the attribute which are the Users or Roles can execute an Action, if the User/Role doesn’t fulfill with what was established into the Action an Unauthorized Result is raised. Remember that exactly after the filter execution ended in a ActionResult, that result is executed.

Now, let’s go to the hypothetical scenario that you need a custom authorization schema, that you need more than User/Role, or you just need neither of both, because your model is based on a Security Level. So you don’t care about who is the guy? / or what role it has?, you just need the security level it has.

With this scenario you can write a custom Authorize attribute:

In this CustomAuthorize attribute, we are doing first the well known authorization (which is, executing the code as is in the class base). When that authorization part passed, we go through our custom authorization part: we get the user from the Database (or whatever other source) and we check the security level. If it’s allowed to execute the action-method we end without setting the result. If it’s not, we set a HttpUnauthorizedResult. In the browser you will be redirected to the login page if you’re not allowed to execute that code.

Now the problem is when you need to test the authorization. Actually you can do it with some mock and overriding some code.

Another thing you’ve to know is that the object in charge of execute the actions is the ControllerActionInvoker. Then to invoke and action into your tests and see the result when the filters are invoked, we need to customize some, and override the method in charge of execute the result (the ActionResult), which is InvokeActionResult. Where is how should looks our method override:

Assert is a class from a Unit Testing framework, in this case in the example is using the Unit Testing framework that came with Visual Studio because every user can run the tests without have ie: Resharper installed. This Assert is expecting that the Result from the filter/action execution is the same with the TResult (is a generic parameter declared into the class). So with this class, we can make an easy test to see if the result is authorized or unauthorized.

Our test for authorized access, should be looking like this

First we are creating a new Controller, we mock stuff for authentication, and then using our custom action invoker to try to invoke the action using InvokeAction method (passing the Context and the Action name to be executed).

We are using some extensions and helpers methods, i.e.: SetFakeAuthenticatedContext is included into the example and there you’ll see which elements you need to mock when use Authorize filter-attributes.

To understand what happened in this first test method:

  1. Controller creation
  2. Mock authentication stuff using our user named:’pepe’.
  3. Using the custom invoker we launch the action ‘PermisiveAction’.
  4. The CustomAuthorized filter is raised, it pass the authorization.
  5. The action is executed and return a ViewResult (doing return View() into the code).
  6. The Assertion is made, everything ok and the test pass.

And now let’s see this another test

The difference with the previous one is in the step 4, 5 and 6. The action is not executed because the filter raise an HttpUnauthorizedResult. Download the example to understand better how to manage the testing of Authorization on Actions.

Download code example

7 Comments so far. Join the Conversation
del.icio.us this! Digg this! Share on Facebook! Share on LinkedIn! Tweet this! RSS 2.0 TOP

Hoy cuando empezaba a trabajar en un nuevo proyecto surgió la necesidad de esbozar un pequeño diagrama de casos de usos y de clases a un nivel general de análisis. Las opciones eran utilizar MS Visio, Rational Rose, Enterprise Architect, Umbrello, etc… (y la lista sigue…). Al final me decidí por yUML, esta es una excelente herramienta online (y gratuita) para crear diagramas a partir de una notación textual muy sencilla e intuitiva, no es necesario andar acomodando las elipses y evitando el cruce de lineas y flechas, lo hace por nosotros y siempre produce un diagrama legible y prolijo listo para incorporar al blog, a documentos, compartir con colegas y clientes.

Por ejemplo:
[User]-(Login)
[User]-(Do Something)
[User]-(Logout)
(Login)<(Reminder)
(Login)>(Captcha)
[User]-(note:This is Stickman{bg:yellow})

Produce:

http://yuml.me/diagram/usecase/[User]-(Login), [User]-(Do Something), [User]-(Logout) , (Login)<(Reminder) , (Login)>(Captcha), [User]-(note:This is Stickman{bg:yellow})

Recientemente se incorporó la posibilidad de agregar notas a los diagramas y de especificar una escala de zoom en el link.

También podemos crear diagramas de clases con la misma facilidad:

[Customer{bg:orange}]+1->*[Order]
[Order]++1-items >*[LineItem]
[Order{bg:green}]-0..1>[PaymentMethod]

Con escala de un 200%
http://yuml.me/diagram/scale:200/class/[Customer{bg:orange}]+1->*[Order], [Order]++1-items >*[LineItem], [Order{bg:green}]-0..1>[PaymentMethod]

En el sitio oficial de yUML pueden encontrar la sintaxis para construir los diagramas y muchos ejemplos muy completos de lo que se puede hacer hasta ahora.

Enlaces relacionados: www.yuml.me

2 Comments so far. Join the Conversation
Tags:
del.icio.us this! Digg this! Share on Facebook! Share on LinkedIn! Tweet this! RSS 2.0 TOP

NHibernate Validator Quickstart

By Dario Quintana | Filed in NHibernate.Validator

The NHibernate Validator Team had prepared examples to you be able to use this validation framework in a easy way. With four examples we are covering the following topics:

1) Winforms

In this example you will how you can easily integrate NHibernate Validator and some helper clases with System.Windows.Forms.

2) NHibernate Integration

Trying to integrate NHibernate Validator with NHibernate? Not a problem. In this example you will how really get these 2 great frameworks working together. NHibernate Validator let you intercept Saves and Updates from NHibernate validating your entities before these changes take place. Note you have to create a database based on the configured connection string.

3) Asp.Net MVC

Asp.Net MVC has a cool way to add validation errors from model and display them all into the View. This example cover the easy integration between these frameworks. Note, you need Asp.Net MVC installed into your machine.Download Asp.net MVC

4) Entity Validator

Sometimes you need to validate a property which depends of another(s) property(ies). The most common example is when you have to validate a range of dates. This example cover this funcionality and show to us how to configurate it using attributes, xml and fluent.

Download it here

Be the first to comment
del.icio.us this! Digg this! Share on Facebook! Share on LinkedIn! Tweet this! RSS 2.0 TOP

La Cámara Argentina de Empresas de Software Libre (Cadesol) comenzará a funcionar este mes con su primera actividad, un congreso para trazar un panorama del estado de estas aplicaciones en el país.

El “Primer Congreso de Software Libre y Negocios” se realizará el 19 de mayo desde las 9.00 en el Centro Cultural Borges de la ciudad de Buenos Aires.

El evento tiene como objetivo dar a conocer el trabajo de estas compañías en el país, y mejorar el acercamiento entre empresas y clientes.

Se realizarán diversas charlas de negocios, soluciones de software libre y casos de éxito. Entre las exposiciones figuran la participación de Pablo Recepter (Banco Credicoop), Gustavo Aguirre (OSDE) y Herman Maseberg (Loma Negra), que comentarán sus experiencias de trabajos con software libre.

Para consultar el programa del evento puede visitar http://www.cadesol.org.ar/evento/programa_completo.htm

Las actividades de Cadesol se focalizan en impulsar el desarrollo de negocios con software libre y “open source” por medio de acciones colectivas: proyectos, investigación, promoción y desarrollo.

Cadesol incluye proveedores de servicios en tecnologías libres como Linux, PHP, Python, Zope, Plone, Drupal, SugarCRM.

Fuente: www.infobaeprofesional.com

Be the first to comment
del.icio.us this! Digg this! Share on Facebook! Share on LinkedIn! Tweet this! RSS 2.0 TOP

Disponible la beta de NetBeans 6.7

By Gonzalo | Filed in Java

Ya se encuentra disponible la beta del IDE NetBeans 6.7.

Entre las nuevas características incluye: integración con Kenai.com (de especial interés para desarrolladores open source),  soporte nativo para Maven, integración con GlassFish y Hudson, soporte para javascript 1.7, SVG rich components en el Visual Mobile Designer, soporte para Qt en C/C++, y muchas otras novedades.

Se puede encontrar una lista completa de las características incluidas en NB 6.7 beta en la página de información de este release y en la página “New and Noteworthy” en el wiki de NetBeans.

Y  se puede descargarlo en la página de descargas de netbeans.org, en versiones para Windows (2000/XP/ Vista), OS X, Linux (x86/x64) y Solaris (x86/x64/sparc).

Be the first to comment
del.icio.us this! Digg this! Share on Facebook! Share on LinkedIn! Tweet this! RSS 2.0 TOP

Windows 7 RC

By Gonzalo | Filed in SO

Se ha lanzado la Release Candidate de Windows 7.

Como todo nuevo SO de Microsoft, hay personas a favor y en contra.

Por comentarios de personas de IT que lo estan probando, es el SO que definitivamente viene a reemplazar a XP (y no el intento de mejora que pretendió ser Vista).

Por lo pronto dejo un par de enlaces para conozcan y prueben este nuevo producto:

Página principal de Windows 7: http://www.microsoft.com/spain/windows/windows-7/default.aspx

Novedades en Windows 7: http://www.microsoft.com/spain/windows/windows-7/whats-new.aspx

10 cosas que los profesionales de IT deben saber: http://technet.microsoft.com/es-ar/library/dd350196.aspx

Descarga: http://www.microsoft.com/windows/windows-7/download.aspx

Be the first to comment
del.icio.us this! Digg this! Share on Facebook! Share on LinkedIn! Tweet this! RSS 2.0 TOP

Geniar en Twitter

By Gonzalo | Filed in Misc

Ahora pueden seguir las aventuras y desventuras diarias del equipo de Geniar en http://twitter.com/geniar

Be the first to comment
del.icio.us this! Digg this! Share on Facebook! Share on LinkedIn! Tweet this! RSS 2.0 TOP

Conversor WiFi de PC a TV

By Gonzalo | Filed in Tecnologia

22365b_oki

OKI presenta la solución PC2TV, dispositivo conversor de audio, vídeo, imágenes y gráficos, capaz de conectar a través de Wi-Fi, cable o cable de red, cualquier ordenador con toda clase de modelos de televisión.

PC2TV permite reproducir en la televisión cualquier aplicación visible en un ordenador.
Este dispositivo cuenta con un mando que permite manejar a distancia el ordenador y visualizar su contenido desde cualquier televisión.

El conversor está diseñado para ofrecer los mejores resultados en televisores LCD o plasma que cuenten con una entrada de vídeo por componentes. Del mismo modo para poder conectar monitores o televisores con entrada de vídeo compuesto, PC2TV incorpora de forma estándar una conexión RCA de vídeo.

Juan Pedro Pérez, Director de Marketing de OKI, señala: “con este equipo hemos ampliado nuestra oferta para el usuario final, ofreciendo un producto tecnológico, que es el complemento ideal de nuestra línea de televisores de LCD”.

1 Comment. Join the Conversation
del.icio.us this! Digg this! Share on Facebook! Share on LinkedIn! Tweet this! RSS 2.0 TOP