Autorizacion con ASP.NET

Páginas: 10 (2477 palabras) Publicado: 29 de abril de 2014
Forms Authentication
To enable forms authentication we need to perform following steps in our application.
1. Configure the application to use Forms Authentication.
2. Create a login page.
3. Whenever a user tries to access the restricted area, push him to the Login page.
4. When the user tries to login, verify his credentials using the database.
5. If the login is successful, keep theusername and his Roles in a Session variable to use it further.
6. Create an authentication ticket for the user (an encrypted cookie). We can have this persistent or non persistent.
7. Facilitate the User/Roles extraction using the authentication ticket.
8. Use the user/Roles found in the last step and create a Principal using that so that the ASP.NET Forms Authentication mechanism can use thisdata.

public ActionResult Login(){return View();}

[HttpPost]
public ActionResult Login(User model, string returnUrl){
if (ModelState.IsValid){
using (userDbEntities entities = new userDbEntities()){
string username = model.username;
string password = model.password;

bool userValid = entities.Users.Any(user => user.username == username&& user.password == password);

if (userValid){

FormsAuthentication.SetAuthCookie(username, false);
return Redirect(returnUrl);
}else{return RedirectToAction("Index", "Home");}
}else{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}}}
returnView(model);}

public ActionResult LogOff(){
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");}
Now in the above code when the user tries to login we will check if the user with the given user credentials exist in the user database or not. If it exist we set the authentication ticket and move forward. Now if our password was encrypted or hashed we would have done the sameoperation on the user entered password before checking in database, but since the password is in plain text lets just authenticate directly.
Now before moving ahead let us look at the view that will take the user credentials and perform the authentication.


Let us now create a simple Controller which will contain two actions. One action that can be performed by any authenticated user and otherthat can be performed by the users in "admin" role only.

public class HomeController : Controller{

[Authorize]
public ActionResult Index(){
ViewBag.Message = "viewed only by authenticated users only";
return View(); }

[Authorize(Roles="admin")]
public ActionResult AdminIndex(){
ViewBag.Message = "viewed only by users in Admin role only";return View();
}}
Autentificación y Autorización ASP.NET
Política restrictiva: "Todo lo que no está expresamente permitido, está prohibido"
Primero se deniega el acceso a todos los usuarios anónimos

Luego se da acceso a los recursos que no necesitan
autenticación
Política permisiva: "Todo lo que no está expresamente prohibido, está permitido"
Primero se permite el acceso a todos losrecursos

Luego se indican aquellos recursos que necesitan
Autenticación
Autorización de URLs con la section Location
Consiste en la autorización de acceso a determinados recursos de la aplicación Web (páginas ASPX, carpetas, archivos...) refriéndose a ellos a través de su ruta relativa en el archivo de configuración de la aplicación.
Se especifica el nivel de acceso requerido mediante unao varias entradas en el nodo raíz de web.config (nodo ) que tienen un aspecto análogo al siguiente:





o con lo cual no necesitamos user o roles



- El nodo location especifica la ruta relativa al directorio actual cuyo acceso se desea controlar.
- Los nodos allow y deny se emplean para permitir o denegar el acceso a determinados...
Leer documento completo

Regístrate para leer el documento completo.

Estos documentos también te pueden resultar útiles

  • Autenticación y autorización ASP.Net
  • Asp.Net
  • Asp.Net
  • Asp.net
  • Asp.Net
  • Asp.net
  • Asp.net
  • Sin Autorizacion

Conviértase en miembro formal de Buenas Tareas

INSCRÍBETE - ES GRATIS