ASP.NET Web API 通过Authentication特性来实现身份认证

时间:2025-04-24 15:04:07
 using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;
using System.Web.Http.Results; namespace WebApi
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthenticateAttribute : FilterAttribute, IAuthenticationFilter
{
private static readonly Dictionary<string, string> UserAccounts; static AuthenticateAttribute()
{
UserAccounts = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{"Foo", "Password"},
{"Bar", "Password"},
{"Baz", "Password"}
};
} public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
IPrincipal user = null;
var headerValue = context.Request.Headers.Authorization;
if (null != headerValue && headerValue.Scheme == "Basic")
{
var credential = Encoding.Default.GetString(Convert.FromBase64String(headerValue.Parameter));
var split = credential.Split(':');
if (split.Length == )
{
var userName = split[];
string password;
if (UserAccounts.TryGetValue(userName, out password))
{
if (password == split[])
{
var identity = new GenericIdentity(userName);
user = new GenericPrincipal(identity, new string[]);
}
}
}
}
context.Principal = user;
return Task.FromResult<object>(null);
} public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
var user = context.ActionContext.ControllerContext.RequestContext.Principal;
if (null != user && user.Identity.IsAuthenticated) return Task.FromResult<object>(null);
var parameter = $"realm={context.Request.RequestUri.DnsSafeHost}";
var challenge = new AuthenticationHeaderValue("Basic", parameter);
context.Result = new UnauthorizedResult(new[] {challenge}, context.Request);
return Task.FromResult<object>(null);
}
}
}