public static void RegisterUserAndRole(object user, List <string> roles) { string ticket = Tools.ToShortMD5(Guid.NewGuid().ToString("N")); DateTime expired = DateTime.Now.AddSeconds(AuthenticationConfig.GetTicketExpire()); HttpContext.Current.Response.Headers.Add(AuthenticationConfig.AuthenticationString, ticket); if (user != null) { MemCache.Add(AuthenticationConfig.TicketKeyPrefix + ticket, user, expired); } if (roles != null && roles.Count > 0) { AuthorizationConfig.AddRoles(ticket, roles); } }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { try { var actionAuthentication = context.ActionContext.ActionDescriptor.GetCustomAttributes <AuthenticationAttribute>(); //验证 if ( (actionAuthentication.Count > 0 && actionAuthentication.Last().Authenticate == true) || (actionAuthentication.Count == 0 && AuthenticationConfig.GetAuthenticateNoAttribute() == true) ) { var ticket = context.Request.Headers.GetValues(AuthenticationConfig.AuthenticationString).FirstOrDefault(); if (ticket == null) { throw new AuthenticationException("can not get ticket !"); } object obj = MemCache.Get(AuthenticationConfig.TicketKeyPrefix + ticket); if (obj == null) { AuthorizationConfig.RemoveRoles(ticket); throw new AuthenticationException("Ticket has Expired !"); } if (AuthenticationConfig.GetRefreshTicket()) { MemCache.Add(AuthenticationConfig.TicketKeyPrefix + ticket, obj, DateTime.Now.AddSeconds(AuthenticationConfig.GetTicketExpire())); } } } catch (Exception ex) { throw ex; } }