c# – 如何使用Web Api中的Api密钥进行使用表单身份验证的服务身份验证

c# – 如何使用Web Api中的Api密钥进行使用表单身份验证的服务身份验证,第1张

概述我正在使用MVC 4 Web Api,我希望在使用我的服务之前对用户进行身份验证. 我已经实现了一个授权消息处理程序,它运行得很好. public class AuthorizationHandler : DelegatingHandler{ private readonly AuthenticationService _authenticationService = new Authe 我正在使用MVC 4 Web API,我希望在使用我的服务之前对用户进行身份验证.

我已经实现了一个授权消息处理程序,它运行得很好.

public class AuthorizationHandler : DelegatingHandler{    private Readonly AuthenticationService _authenticationService = new AuthenticationService();    protected overrIDe Task<httpResponseMessage> SendAsync(httpRequestMessage request,CancellationToken cancellationToken)    {        IEnumerable<string> APIKeyheaderValues = null;        if (request.headers.TryGetValues("X-APIKey",out APIKeyheaderValues))        {            var APIKeyheaderValue = APIKeyheaderValues.First();            // ... your authentication logic here ...            var user = _authenticationService.GetUserByKey(new GuID(APIKeyheaderValue));            if (user != null)            {                var userID = user.ID;                var userIDClaim = new Claim(ClaimTypes.SerialNumber,userID.ToString());                var IDentity = new ClaimsIDentity(new[] { userIDClaim },"APIKey");                var principal = new ClaimsPrincipal(IDentity);                Thread.CurrentPrincipal = principal;            }        }        return base.SendAsync(request,cancellationToken);    }}

问题是,我使用表单身份验证.

[httpPost]    public ActionResult Login(usermodel model)    {        if (ModelState.IsValID)        {            var user = _authenticationService.Login(model);            if (user != null)            {                // Add the API key to the httpResponse???            }            return VIEw(model);        }        return VIEw(model);    }

当我打电话给我的时候:

[Authorize]public class TestController : APIController{    public string GetLists()    {        return "Weee";    }}

处理程序找不到X-APIKey标头.

有没有办法将用户的API密钥添加到http响应头并保持密钥,只要用户登录?
有没有其他方法来实现此功能?

解决方法 我找到了以下文章 http://www.asp.net/web-api/overview/working-with-http/http-cookies
使用它我配置我的AuthorizationHandler使用cookie:
public class AuthorizationHandler : DelegatingHandler{    private Readonly IAuthenticationService _authenticationService = new AuthenticationService();    protected overrIDe Task<httpResponseMessage> SendAsync(httpRequestMessage request,CancellationToken cancellationToken)    {        var cookie = request.headers.Getcookies(Constants.APIKey).FirstOrDefault();        if (cookie != null)        {            var APIKey = cookie[Constants.APIKey].Value;            try            {                var guIDKey = GuID.Parse(APIKey);                var user = _authenticationService.GetUserByKey(guIDKey);                if (user != null)                {                    var userIDClaim = new Claim(ClaimTypes.name,APIKey);                    var IDentity = new ClaimsIDentity(new[] { userIDClaim },"APIKey");                    var principal = new ClaimsPrincipal(IDentity);                    Thread.CurrentPrincipal = principal;                }            }            catch (FormatException)            {            }        }        return base.SendAsync(request,cancellationToken);    }}

我配置了我的登录 *** 作结果:

[httpPost]    public ActionResult Login(LoginModel model)    {        if (ModelState.IsValID)        {            var user = _authenticationService.Login(model);            if (user != null)            {                _cookieHelper.setcookie(user);                return RedirectToAction("Index","Home");            }            ModelState.AddModelError("","Incorrect username or password");            return VIEw(model);        }        return VIEw(model);    }

在里面,我使用的是我创建的cookieHelper.它由一个界面组成:

public interface IcookieHelper{    voID setcookie(User user);    voID Removecookie();    GuID GetUserID();}

以及实现接口的类:

public class cookieHelper : IcookieHelper{    private Readonly httpContextBase _httpContext;    public cookieHelper(httpContextBase httpContext)    {        _httpContext = httpContext;    }    public voID setcookie(User user)    {        var cookie = new httpcookie(Constants.APIKey,user.UserID.ToString())        {            Expires = DateTime.UtcNow.AddDays(1)        };        _httpContext.Response.cookies.Add(cookie);    }    public voID Removecookie()    {        var cookie = _httpContext.Response.cookies[Constants.APIKey];        if (cookie != null)        {            cookie.Expires = DateTime.UtcNow.AddDays(-1);            _httpContext.Response.cookies.Add(cookie);        }    }    public GuID GetUserID()    {        var cookie = _httpContext.Request.cookies[Constants.APIKey];        if (cookie != null && cookie.Value != null)        {            return GuID.Parse(cookie.Value);        }        return GuID.Empty;    }}

通过这个配置,现在我可以使用我的APIControllers的Authorize属性:

[Authorize]public class TestController : APIController{    public string Get()    {        return String.Empty;    }}

这意味着,如果用户没有登录.他无法访问我的API并收到401错误.此外,我可以在我的代码中的任何位置检索API密钥,我将其用作用户ID,这使得它非常干净和可读.

我不认为使用cookie是最好的解决方案,因为有些用户可能已经在浏览器中禁用了它们,但目前我还没有找到更好的方法来进行授权.

总结

以上是内存溢出为你收集整理的c# – 如何使用Web Api中的Api密钥进行使用表单身份验证的服务身份验证全部内容,希望文章能够帮你解决c# – 如何使用Web Api中的Api密钥进行使用表单身份验证的服务身份验证所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1244959.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存