Skip to content

Instantly share code, notes, and snippets.

@cleytonferrari
Last active January 23, 2018 20:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cleytonferrari/11257470 to your computer and use it in GitHub Desktop.
Save cleytonferrari/11257470 to your computer and use it in GitHub Desktop.
Exemplo de uso de Claims com ASP .Net identity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
//http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/
//http://stackoverflow.com/questions/21404935/mvc-5-access-claims-identity-user-data
namespace LoginClaims.Controllers
{
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
public ActionResult Login(LoginViewModel usuario)
{
ViewBag.erro = "";
usuario.Permissao = "Admin";//quando buscar no banco trazer as permissoes dele, aqui so um exemplo
if (usuario.Login == "cleyton")
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,usuario.Login),
new Claim(ClaimTypes.Role,usuario.Permissao)
};
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var ctx = Request.GetOwinContext();
var auth = ctx.Authentication;
auth.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
return RedirectToAction("Index");
}
if (Request.HttpMethod == "POST")
{
ViewBag.erro = "Usuario e senha invalidos";
}
return View(usuario);
}
public ActionResult Sair()
{
var ctx = Request.GetOwinContext();
var auth = ctx.Authentication;
auth.SignOut();
return RedirectToAction("Login");
}
[Authorize(Roles = "Admin")]
public string SoAdmin()
{
return "Voce é admin";
}
}
public class LoginViewModel
{
public string Login { get; set; }
public string Senha { get; set; }
public string Permissao { get; set; }
}
}
@model LoginClaims.Controllers.LoginViewModel
@{
ViewBag.Title = "Login";
}
<h2>Login</h2>
<p>@ViewBag.erro</p>
<form action="" method="POST">
<input type="text" name="Login" id="Login" value="@Model.Login" placeholder="Login" />
<br />
<br />
<input type="password" name="Senha" id="Senha" value="@Model.Senha" placeholder="Senha" />
<br />
<br />
<input type="submit" value="Acessar" />
</form>
Instalar os pacotes do nuget
Install-Package Microsoft.AspNet.Identity.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
[assembly: OwinStartup(typeof(LoginClaims.Startup))]
namespace LoginClaims
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/")
});
}
}
}
//Deve ser adicionado essa classe na raiz do projeto
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<!--
Adicionar isto para redirecionar os logins
-->
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880" />
</authentication>
</system.web>
</configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment