身份验证的Web API [英] Authentication in Web API

查看:222
本文介绍了身份验证的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是很普遍的问题。但我真的不知道如何整合它。
我想验证添加到我的Web API服务。现在,我已经创建了一个控制台应用程序来调用服务的方法。



我已经经历了这样的博客。我只是想实现在这篇文章中提到的认证过滤器。



我想知道我怎么能传递凭据了HTTPClient一起从我的控制台应用程序,获取这些东西对Web API并验证它们。



我已经创建了验证过滤器,但它不调用验证过滤器的AuthenticateAsync方法。



要通过HTTP客户端我已经做到了这一点:

 公共无效的GetData()
{
HttpClient的利弊=新的HttpClient();
cons.BaseAddress =新的URI(HTTP://本地主机:50524 /);
cons.DefaultRequestHeaders.Accept.Clear();
cons.DefaultRequestHeaders.Accept.Add(新MediaTypeWithQualityHeaderValue(应用/ JSON));
VAR数据= Encoding.ASCII.GetBytes(安基塔:ankita123);
变种头=新AuthenticationHeaderValue(基本,Convert.ToBase64String(数据));
cons.DefaultRequestHeaders.Authorization =头;

// MyAPIPost(缺点).Wait();
MyAPIGet(缺点).Wait();
}


解决方案

我已经成功地使用实施认证文章。在该过滤器属性来实现。


I know this is very common question. But I really do not know how to integrate it. I want to add authentication to my web api services. Right now I have created one console application to call service's method.

I have gone through this blog. I just want to implement authentication filter as mentioned in this article.

I want to know how can I pass credentials along with HTTPClient from my console application, fetch those things to web API and authenticate them.

I have created authentication filter but it does not invoke AuthenticateAsync method of authentication filter.

To pass http client I have done this:

 public void GetData()
    {
        HttpClient cons = new HttpClient();
        cons.BaseAddress = new Uri("http://localhost:50524/");
        cons.DefaultRequestHeaders.Accept.Clear();
        cons.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var data = Encoding.ASCII.GetBytes("Ankita:ankita123");
        var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(data));
        cons.DefaultRequestHeaders.Authorization = header;

        //MyAPIPost(cons).Wait();
        MyAPIGet(cons).Wait();
    }

解决方案

I have successfully implemented authentication using this article. In that filter attribute is implemented.

这篇关于身份验证的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆