Skip to content

Instantly share code, notes, and snippets.

@cleytonferrari
Created November 1, 2014 19:16
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/9c8e74de15fd3cd67829 to your computer and use it in GitHub Desktop.
Save cleytonferrari/9c8e74de15fd3cd67829 to your computer and use it in GitHub Desktop.
Exemplo de Login com Claims
public ActionResult Index(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid) return View();
var usuario = autenticacaoAplicacao.UsuarioInformadoPodeLogarNoSistema(model.Login, model.Pass);
if (usuario != null)
{
Seguranca.SignInCookie(usuario);
if (!string.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
return RedirectToAction("Index", "Home", new { area = "" });
}
this.MensagemNaTela("Dados de acesso invalidos. Verifique-os e tente novamente.", MensagemEnum.Error);
return View();
}
<package id="Microsoft.AspNet.Cors" version="5.2.2" targetFramework="net45" />
<package id="Microsoft.AspNet.Identity.Core" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin" version="3.0.0" targetFramework="net45" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security" version="3.0.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.Cookies" version="3.0.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security.OAuth" version="3.0.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.6" targetFramework="net45" />
<package id="Owin" version="1.0" targetFramework="net45" />
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using W7Gestao.Dominio.Configuracao;
using Microsoft.Owin.Infrastructure;
namespace W7Gestao.UI.Helper.Acesso
{
public static class Seguranca
{
public static void SignInCookie(Usuario usuario)
{
var identity = ClaimsIdentity(usuario, DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.Current.Request.GetOwinContext().Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);
}
public static dynamic SignInBearer(Usuario usuario)
{
var identity = ClaimsIdentity(usuario, Startup.OAuthBearerOptions.AuthenticationType);
var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
var token = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return new { usuario=new
{
usuario.Id,
usuario.UnidadeId,
usuario.Nome,
usuario.ArquivoId,
usuario.Permissoes
}, token};
}
private static ClaimsIdentity ClaimsIdentity(Usuario usuario, string authenticationType)
{
var claims = new List<Claim>
{
new Claim("Nome", usuario.Nome),
new Claim("UnidadeId", usuario.UnidadeId),
new Claim("UsuarioId", usuario.Id),
new Claim("ArquivoId", usuario.ArquivoId),
};
claims.AddRange(usuario.Permissoes.Select(permissao => new Claim(ClaimTypes.Role, permissao)));
var identity = new ClaimsIdentity(claims, authenticationType);
return identity;
}
public static void SignOut()
{
HttpContext.Current.Request.GetOwinContext().Authentication.SignOut();
}
public static bool UserIsInRole(string role)
{
var ctx = (OwinContext)HttpContext.Current.Request.GetOwinContext();
return ctx.Authentication.User.IsInRole(role);
}
public static Usuario GetUser()
{
var ctx = (OwinContext)HttpContext.Current.Request.GetOwinContext();
var user = ctx.Authentication.User;
var usuario = new Usuario
{
Nome = GetUserValue("Nome"),
UnidadeId = GetUserValue("UnidadeId"),
Id = GetUserValue("UsuarioId"),
ArquivoId = GetUserValue("ArquivoId")
};
var permissoes = new List<string>();
foreach (var claim in user.Claims)
{
if (claim.Type == ClaimTypes.Role)
{
permissoes.Add(claim.Value);
}
}
usuario.Permissoes = permissoes.ToArray();
return usuario;
}
public static string GetUserId()
{
return GetUserValue("UsuarioId");
}
public static string GetUserUnidadeId()
{
return GetUserValue("UnidadeId");
}
private static string GetUserValue(string key)
{
var ctx = (OwinContext)HttpContext.Current.Request.GetOwinContext();
var user = ctx.Authentication.User;
if (user == null)
return string.Empty;
return user.FindFirst(key) == null ? string.Empty : user.FindFirst(key).Value;
}
}
}
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Owin;
[assembly: OwinStartup(typeof(W7Gestao.UI.Startup))]
namespace W7Gestao.UI
{
public class Startup
{
static Startup()
{
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
}
public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/acesso"),
Provider = new CookieAuthenticationProvider
{
OnApplyRedirect = ctx =>
{
/*if (IsAjaxRequest(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}*/
}
}
});
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment