Skip to content

Instantly share code, notes, and snippets.

@cleytonferrari
Created September 21, 2014 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cleytonferrari/730ae2c47a2a0ef3dde3 to your computer and use it in GitHub Desktop.
Save cleytonferrari/730ae2c47a2a0ef3dde3 to your computer and use it in GitHub Desktop.
Exemplo de uso de roles através das Claims
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security;
namespace ClaimsLogin.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
/// <summary>
/// Exemplo para destruir a sessão do usuário
/// </summary>
/// <returns></returns>
public ActionResult Sair()
{
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignOut();
return RedirectToAction("Index");
}
/// <summary>
/// Loga no sistema, no exemplo uso o SignIn e adiciona claim do tipo Role
/// </summary>
/// <returns></returns>
public ActionResult Entrar()
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "Cleyton"),
new Claim(ClaimTypes.Email, "cleyton@email.com"),
new Claim(ClaimTypes.Role, "Admin"),
new Claim(ClaimTypes.Role, "Master"),
};
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
return RedirectToAction("Index");
}
/// <summary>
/// Exibe os dados do usuario, para usuarios logados
/// </summary>
/// <returns></returns>
[Authorize]
public String Dados()
{
OwinContext ctx = (OwinContext)Request.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
//var admin = user.IsInRole("Admin");
//IEnumerable<Claim> claims = user.Claims;
return string.Format("Nome: {0} - É admin: {1} - É master: {2}", user.FindFirst(ClaimTypes.Name).Value, user.IsInRole("Admin"), user.IsInRole("Master"));
}
/// <summary>
/// Somente usuarios com a claim Admin
/// </summary>
/// <returns></returns>
[Authorize(Roles = "Admin")]
public String SoAdmin()
{
return "Você é um admin";
}
/// <summary>
/// Somente usuarios com a claim User. Neste exemplo ele sera redirecionado para o login
/// </summary>
/// <returns></returns>
[Authorize(Roles = "User")]
public String SoUser()
{
return "Você é um user";
}
}
}
@cleytonferrari
Copy link
Author

Install-Package Microsoft.Owin.Security.Cookies

Install-Package Microsoft.AspNet.Identity.Core

Install-Package Microsoft.AspNet.Identity.Owin

Install-Package Microsoft.Owin.Host.SystemWeb

Update-Package Newtonsoft.Json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment