增加BAToken授权模式,支持WebApi授权验证,Header设置Token

This commit is contained in:
Argo-Lenovo 2016-11-30 19:40:57 +08:00
parent cccf42c357
commit 682b14d406
2 changed files with 61 additions and 13 deletions

View File

@ -1,4 +1,6 @@
using Bootstrap.DataAccess;
using Bootstrap.Admin.Controllers;
using Bootstrap.DataAccess;
using Longbow.Caching;
using Longbow.Security.Principal;
using System.Linq;
using System.Security.Principal;
@ -23,10 +25,35 @@ namespace Bootstrap.Admin
if (principal.Identity.IsAuthenticated)
{
if (LgbPrincipal.IsAdmin(principal.Identity.Name)) return true;
var roles = RoleHelper.RetrieveRolesByUserName(principal.Identity.Name).Select(r => r.RoleName);
actionContext.ControllerContext.RequestContext.Principal = new LgbPrincipal(principal.Identity, roles);
SetPrincipal(principal.Identity, actionContext);
}
else
{
if (actionContext.Request.Headers.Contains("Token"))
{
try
{
var token = actionContext.Request.Headers.GetValues("Token").First();
if (!string.IsNullOrEmpty(token))
{
var auth = CacheManager.Get<LoginInfo>(token);
if (auth != null && !string.IsNullOrEmpty(auth.UserName))
{
SetPrincipal(new GenericIdentity(auth.UserName, "BAToken"), actionContext);
return true;
}
}
}
catch { }
}
}
return base.IsAuthorized(actionContext);
}
private static void SetPrincipal(IIdentity identity, HttpActionContext actionContext)
{
var roles = RoleHelper.RetrieveRolesByUserName(identity.Name).Select(r => r.RoleName);
actionContext.ControllerContext.RequestContext.Principal = new LgbPrincipal(identity, roles);
}
}
}

View File

@ -1,4 +1,8 @@
using System.Web.Http;
using Bootstrap.DataAccess;
using Longbow.Caching;
using System;
using System.Web.Http;
using System.Web.Security;
namespace Bootstrap.Admin.Controllers
{
@ -15,16 +19,33 @@ namespace Bootstrap.Admin.Controllers
/// <summary>
///
/// </summary>
public class LoginInfo
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost]
public LoginInfo Post(string userName, string password)
{
/// <summary>
///
/// </summary>
public string UserName { get; set; }
/// <summary>
///
/// </summary>
public string Token { get; set; }
if (UserHelper.Authenticate(userName, password))
{
var token = Guid.NewGuid().ToString();
return CacheManager.AddOrUpdate(token, int.Parse(Math.Round(FormsAuthentication.Timeout.TotalSeconds).ToString()), k => new LoginInfo() { UserName = userName, Token = token }, (k, info) => info, "Token 数据缓存");
}
return new LoginInfo();
}
}
/// <summary>
///
/// </summary>
public class LoginInfo
{
/// <summary>
///
/// </summary>
public string UserName { get; set; }
/// <summary>
///
/// </summary>
public string Token { get; set; }
}
}