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. git-入门

    一.简介 Git是目前世界上最先进的分布式版本控制系统,Git中绝大部分操作都是访问本地资源,不需要网络,其中有三个概念比较重要:1. 工作目录 2. 暂存区域 3.本地仓库. 简单说明一下,工作目录 ...

  2. 从Sql Server表中随机获取一些记录最简单的方法

    * FROM test ORDER BY NewID() 注意,使用时,请将‘test’改为真实的表名.

  3. Java 根据经纬度计算两点之间的距离

    package xxx.driver.business.utils; /** * <p>Represents a point on the surface of a sphere. (Th ...

  4. [游戏开发-学习笔记]菜鸟慢慢飞(九)- NGUI- UIWidget(官方说明翻译)

  5. Hexo静态博客搭建教程

    Hexo是一个快速.简洁且高效的博客框架.Hexo 使用 Markdown(或其他渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页.生成静态网页可以托管在github.下面简单介绍一下he ...

  6. AC日记——最小的N个和 codevs 1245

    1245 最小的N个和  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 钻石 Diamond 题解  查看运行结果     题目描述 Description 有两个长度为 N ...

  7. 【IScroll深入学习】解决IScroll疑难杂症

    前言 在去年,我们对IScroll的源码进行了学习,并且分离出了一段代码自己使用,在使用学习过程中发现几个致命问题: ① 光标移位 ② 文本框找不到(先让文本框获取焦点,再滑动一下,输入文字便可重现) ...

  8. [LeetCode] Arithmetic Slices II - Subsequence 算数切片之二 - 子序列

    A sequence of numbers is called arithmetic if it consists of at least three elements and if the diff ...

  9. [LeetCode] Find Median from Data Stream 找出数据流的中位数

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no ...

  10. ie6、7、8兼容部分css3

    做法很简单下载一个ie-css3,然后有css3的样式里加入behavior: url(js/ie-css3.htc)就可以了(js/ie-css3.htc是文件地址) <!DOCTYPE ht ...