gpt4 book ai didi

c# - 如何在 WebApi 中使用 AuthorizationFilterAttribute 与 WebClient 库?

转载 作者:行者123 更新时间:2023-11-30 14:10:35 26 4
gpt4 key购买 nike

我使用以下代码进行授权(我在网上找到它并更改它以供我使用)

当我调用我的 url 时,授权似乎有效 enter image description here

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class ClientAuthorizationAttribute : AuthorizationFilterAttribute
{
private bool _active = true;

public ClientAuthorizationAttribute()
{

}

public ClientAuthorizationAttribute(bool active)
{
_active = active;
}

public override void OnAuthorization(HttpActionContext actionContext)
{
if (_active)
{
var identity = ParseAuthorizationHeader(actionContext);
if (identity == null)
{
Challenge(actionContext);
return;
}


if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext))
{
Challenge(actionContext);
return;
}

var principal = new GenericPrincipal(identity, null);

Thread.CurrentPrincipal = principal;
base.OnAuthorization(actionContext);
}
}

protected virtual bool OnAuthorizeUser(string clientId, string authId, HttpActionContext actionContext)
{
return false;
}
protected virtual ClientAuthenticationIdentity ParseAuthorizationHeader(HttpActionContext actionContext)
{
string authHeader = null;
var auth = actionContext.Request.Headers.Authorization;
if (auth != null && auth.Scheme == "Basic")
authHeader = auth.Parameter;

if (string.IsNullOrEmpty(authHeader))
return null;

authHeader = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader));

var tokens = authHeader.Split(':');
if (tokens.Length < 2)
return null;

return new ClientAuthenticationIdentity(tokens[0], tokens[1]);
}

void Challenge(HttpActionContext actionContext)
{
var host = actionContext.Request.RequestUri.DnsSafeHost;
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", host));
}
}

public class ClientAuthenticationIdentity : GenericIdentity
{
public ClientAuthenticationIdentity(string name, string password)
: base(name, "Basic")
{
Password = password;
}
public string Password { get; set; }
}

public class BasicAuthorizationAttribute : ClientAuthorizationAttribute
{

public BasicAuthorizationAttribute()
{ }

public BasicAuthorizationAttribute(bool active)
: base(active)
{ }


protected override bool OnAuthorizeUser(string clientId, string authId, HttpActionContext actionContext)
{
var businness = new WebServiceAuthBusiness();
return businness.Count(x => x.ClientID == clientId && x.AuthenticateID == authId) > 0;
}
}
}

在客户端中,我使用 WebClient 获取应用程序数据(不起作用)

    [BasicAuthorization]
public IList<Application> Get()
{
using (var client = new WebClient())
{

client.BaseAddress = _baseAddress;
client.Encoding = Encoding.UTF8;
client.UseDefaultCredentials = true; ???
client.Credentials = new NetworkCredential(clientId, authId); ???
var str = client.DownloadString("api/application/get");
return JsonConvert.DeserializeObject<List<Application>>(str);
}
}

我如何使用 webClient 为 AuthorizationFilter 发送用户名和密码???

最佳答案

c# corner 所述:

在您的解决方案中添加 BasicAuthenticationAttribute.cs 类。

使用以下代码

public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
try
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
// Gets header parameters
string authenticationString = actionContext.Request.Headers.Authorization.Parameter;
string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));

// Gets username and password
string usrename = originalString.Split(':')[0];
string password = originalString.Split(':')[1];

AuthsController auth = new AuthsController();
// Validate username and password
if (!auth.ValidateUser(usrename, password))
{
// returns unauthorized error
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}

base.OnAuthorization(actionContext);
}
// Handling Authorize: Basic <base64(username:password)> format.
catch(Exception e)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}

在AuthsController.cs( Entity Framework )中

添加

[NonAction]
public bool ValidateUser(string userName, string password)
{
// Check if it is valid credential
var queryable = db.Auths
.Where(x => x.Name == userName)
.Where(x => x.Password == password);
if (queryable != null)
{
return true;
}
else
{
return false;
}
}

在WebApiConfig.cs中

添加

config.Filters.Add(new BasicAuthenticationAttribute());

在需要基本授权的 Controller 中。

添加

[BasicAuthentication]
public class YourController : ApiController{.......}

关于c# - 如何在 WebApi 中使用 AuthorizationFilterAttribute 与 WebClient 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23336204/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com