HttpConfiguration webapiConfig = new HttpConfiguration();
IIocBuilder iocBuilder = new OwinAutofacIocBuilder(services, app, webapiConfig); HelpPageConfig.Register(webapiConfig);
//webapiConfig.EnsureInitialized(); app.UseCanDoo(iocBuilder);
ConfigureAuth(app, iocBuilder.ServiceProvider); //这一行代码必须放在ConfiureOAuth(app)之后 ,就这一点,花我两天+一个通宵啊
//app.UseWebApi(config); webapiConfig.MapHttpAttributeRoutes();

        //当webapi作为一owin一部分运行时,下面这两句不能有,不然除了webapi,其它程序验证不了
        //webapiConfig.SuppressDefaultHostAuthentication();
        //webapiConfig.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));


            webapiConfig.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); app.UseAutofacWebApi(webapiConfig);
app.UseWebApi(webapiConfig);
app.UseAutofacMvc();
webapiConfig.EnsureInitialized();
//这一行代码必须放在ConfiureOAuth(app)之后 ,操,就这一点,花我两天+一个通宵啊
//app.UseWebApi(config);
如果不放这之后,access_token正常获取与提交,但还是会不能认证,返回401 另外IAuthenticationManager注入方式要改成如下方式,webapi中没有 HttpContext
//HttpContext.Current.GetOwinContext().Authentication
builder.Register(c => c.Resolve<IOwinContext>().Authentication).InstancePerLifetimeScope();

客户端测试代码

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks; namespace ResourceOwnerPasswordCredentialGrantDemo
{ class Program
{
static void Main(string[] args)
{
OauthTest oauthTest = new OauthTest();
oauthTest.Test();
oauthTest.Test1();
Console.ReadKey();
}
} public class OauthTest
{
private string clientId = "";
private string clientSecret = "abcdef";
private HttpClient _httpClient; //private string AuthorizationServerBaseAddress= "http://localhost:44246/";
//private string myPath = "api/Values"; private string AuthorizationServerBaseAddress = "http://localhost:23426/";
private string myPath = "api/Hello/";
private string myPath1 = "api/Hello/1"; public OauthTest()
{
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri(AuthorizationServerBaseAddress);
} private async Task<string> GetAccessToken()
{
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret))); var parameters = new Dictionary<string, string>();
//parameters.Add("client_id", clientId);
//parameters.Add("client_secret", clientSecret);
parameters.Add("grant_type", "client_credentials"); var response = await _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters));
var responseValue = await response.Content.ReadAsStringAsync(); //Console.WriteLine(responseValue); return JObject.Parse(responseValue)["access_token"].Value<string>();
}
public async Task Test()
{
Console.WriteLine(); var token = GetAccessToken().Result;
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token); Console.WriteLine(await (await _httpClient.GetAsync(myPath)).Content.ReadAsStringAsync());
} private async Task<string> GetAccessToken1()
{
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret))); var parameters = new Dictionary<string, string>();
parameters.Add("grant_type", "password");
parameters.Add("username", "你的账号");
parameters.Add("password", "你的密码"); var response = await _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters));
var responseValue = await response.Content.ReadAsStringAsync(); //Console.WriteLine(JObject.Parse(responseValue)["access_token"].Value<string>()); return JObject.Parse(responseValue)["access_token"].Value<string>();
}
public async Task Test1()
{
var token = GetAccessToken1().Result;
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);//bearer
Console.WriteLine(_httpClient.DefaultRequestHeaders);
Console.WriteLine(await (await _httpClient.GetAsync(myPath1)).Content.ReadAsStringAsync());
}
} }
fiddler申请token
发内容client_id=12456&client_secret=abcdef&grant_type=client_credentials
账号模式:
发内容:client_id=12456&client_secret=abcdef&grant_type=password&username=用户名&password=密码
请求头带token
User-Agent: Fiddler
Content-Type: application/json
Authorization: bearer QeI39h-vuEEVfNAOzt2bnXC9gkByLo0GvN-J64w72KJuocC42pZrZ0AB6vIYPkSUGb5tZCWd5KZ58cY-9pwaR69u1TR5j6Ek_7OJxd-KWPVeXR-rECo0lJpZFI9xVAMKIbXgpj5hFulJJpD1rGCaVbsFNp68pnAb_qPN-tBe8NIHzjdHstP30wUp6BNpHOaIsjlgbr-BxsIno55tvkimMQ
bearer后与token之间必需要有一个空格

webapi集成owin使用Oauth认证时能获取accee_token仍无法登录的解决办法的更多相关文章

  1. 关于jquery html()方法获取带有OBJECT标签的元素内容时,出现“类型不匹配。”的解决办法

    关于jquery html()方法获取带有OBJECT标签的元素内容时,出现“类型不匹配.”的解决办法 解决办法: $("selector").clone().html()

  2. PLSQL往Oracle数据库插入中文后变为问号 和 启动PLSQL时提示NLS_LANG在客户端不能确定的解决办法

    PLSQL往Oracle数据库插入中文后变为问号 和 启动PLSQL时提示NLS_LANG在客户端不能确定的解决办法 1.检查服务器的字符编码 Select * from V$NLS_PARAMETE ...

  3. excel双击文件打开时空白,使用菜单打开正常的解决办法

    excel双击文件打开时空白,使用菜单打开正常的解决办法 打开 excel的选项 找到高级->常规 取消“忽略使用动态数据交换...”的勾,确定. 问题解决.

  4. WPF 在TextBox失去焦点时检测数据,出错重新获得焦点解决办法

    WPF 在TextBox失去焦点时检测数据,出错重新获得焦点解决办法 在WPF的TextBox的LostFocus事件中直接使用Focus()方法会出现死循环的问题 正确的使用方式有2中方法: 方法一 ...

  5. Vue微信自定义分享时安卓系统config:ok,ios系统config:invalid signature签名错误,或者安卓和ios二次分享时均config:ok但是分享无效的解决办法

    简述需求:要求指定页面可以进行微信自定义分享(自定义标题,描述,图片,链接),剩下的页面隐藏所有基础接口.二次分享依然可以正常使用,切换至其他页面也可以正常进行自定义分享. 这两天在做微信自定义分享的 ...

  6. 添加Chrome插件时出现“程序包无效”等问题的解决办法

    相较之各大浏览器,我最喜欢的便是Chrome了,不只因为Chrome搜索,也因为Google Chrome强大的插件功能. 而这一切的东风,就是"谷歌访问助手". 谷歌访问助手的下 ...

  7. ASP.NET WebAPI 集成 Swagger 启用 OAuth 2.0 配置问题

    在 ASP.NET WebAPI 集成 Swagger 后,由于接口使用了 IdentityServer 做的认证,调试起来很不方便:看了下 Swashbuckle 的文档 ,是支持 OAuth2.0 ...

  8. 编译linux内核前用make menuconfig设置时 Unable to find the ncurses ibraries的解决办法

    今天在更新CentOS或者Ubuntu的内核时,执行make menuconfig可能看如这样的错误: *** Unable to find the ncurses libraries or the ...

  9. 在Pycharm中使用Pandas时输出结果中列被省略的解决办法

    在使用pycharm学习pandas的过程中我发现好多时候会发生不能输出所有列的情况,上网搜了一下,发现解决的办法是使用一个输出控制的函数. 在下面的代码中我们只是输出starbucks_store_ ...

随机推荐

  1. SQL Server 2012 新特性:新增和修改函数

    转换函数      1.PARSE      Parse是把字符串类型转化为想要的类型,看看和convert和cast的区别         SELECT PARSE ('2.111111' AS f ...

  2. ZooKeeper:第三方客户端 ZKClient

    ZKClient ZKClient的设计 ZKClient组件说明 重要的处理流程说明 启动ZKClient 为节点注册Watcher ZooKeeper的变更操作 客户端处理变更 序列化处理 ZKC ...

  3. Oracle死锁

    当两个或多个用户相互等待锁定的数据时就会发生死锁,这时这些用户被卡在不能继续处理业务,oracle可以自动检测死锁并解决他们,通过回滚一个死锁中的语句,释放锁定的数据,回滚的话会遇到ora-00060 ...

  4. Java 修饰符

    Java语言提供了很多修饰符,主要分为以下两类: 访问修饰符 非访问修饰符 修饰符用来定义类.方法或者变量,通常放在语句的最前端.我们通过下面的例子来说明: public class classNam ...

  5. Markdown 新手指南

    Markdown 新手指南   「简书」作为一款「写作软件」在诞生之初就支持了 Markdown,Markdown 是一种「电子邮件」风格的「标记语言」,我们强烈推荐所有写作者学习和掌握该语言.为什么 ...

  6. 萌新笔记——Cardinality Estimation算法学习(一)(了解基数计算的基本概念及回顾求字符串中不重复元素的个数的问题)

    最近在菜鸟教程上自学redis.看到Redis HyperLogLog的时候,对"基数"以及其它一些没接触过(或者是忘了)的东西产生了好奇. 于是就去搜了"HyperLo ...

  7. 创建docker私人仓库

    关于创建docker私人仓库 1.1.           安装步骤 1.1.1.            直接从公共库上面下载register镜像在本地执行 1.1.1.1.             ...

  8. Mysql5.5升级到5.7后MySQLdb不能正常使用的问题解决

    ubuntu系统 报错信息1 Type "help", "copyright", "credits" or "license&qu ...

  9. [LeetCode] 3Sum Smaller 三数之和较小值

    Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...

  10. [LeetCode] Delete Node in a Linked List 删除链表的节点

    Write a function to delete a node (except the tail) in a singly linked list, given only access to th ...