webapi集成owin使用Oauth认证时能获取accee_token仍无法登录的解决办法
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仍无法登录的解决办法的更多相关文章
- 关于jquery html()方法获取带有OBJECT标签的元素内容时,出现“类型不匹配。”的解决办法
关于jquery html()方法获取带有OBJECT标签的元素内容时,出现“类型不匹配.”的解决办法 解决办法: $("selector").clone().html()
- PLSQL往Oracle数据库插入中文后变为问号 和 启动PLSQL时提示NLS_LANG在客户端不能确定的解决办法
PLSQL往Oracle数据库插入中文后变为问号 和 启动PLSQL时提示NLS_LANG在客户端不能确定的解决办法 1.检查服务器的字符编码 Select * from V$NLS_PARAMETE ...
- excel双击文件打开时空白,使用菜单打开正常的解决办法
excel双击文件打开时空白,使用菜单打开正常的解决办法 打开 excel的选项 找到高级->常规 取消“忽略使用动态数据交换...”的勾,确定. 问题解决.
- WPF 在TextBox失去焦点时检测数据,出错重新获得焦点解决办法
WPF 在TextBox失去焦点时检测数据,出错重新获得焦点解决办法 在WPF的TextBox的LostFocus事件中直接使用Focus()方法会出现死循环的问题 正确的使用方式有2中方法: 方法一 ...
- Vue微信自定义分享时安卓系统config:ok,ios系统config:invalid signature签名错误,或者安卓和ios二次分享时均config:ok但是分享无效的解决办法
简述需求:要求指定页面可以进行微信自定义分享(自定义标题,描述,图片,链接),剩下的页面隐藏所有基础接口.二次分享依然可以正常使用,切换至其他页面也可以正常进行自定义分享. 这两天在做微信自定义分享的 ...
- 添加Chrome插件时出现“程序包无效”等问题的解决办法
相较之各大浏览器,我最喜欢的便是Chrome了,不只因为Chrome搜索,也因为Google Chrome强大的插件功能. 而这一切的东风,就是"谷歌访问助手". 谷歌访问助手的下 ...
- ASP.NET WebAPI 集成 Swagger 启用 OAuth 2.0 配置问题
在 ASP.NET WebAPI 集成 Swagger 后,由于接口使用了 IdentityServer 做的认证,调试起来很不方便:看了下 Swashbuckle 的文档 ,是支持 OAuth2.0 ...
- 编译linux内核前用make menuconfig设置时 Unable to find the ncurses ibraries的解决办法
今天在更新CentOS或者Ubuntu的内核时,执行make menuconfig可能看如这样的错误: *** Unable to find the ncurses libraries or the ...
- 在Pycharm中使用Pandas时输出结果中列被省略的解决办法
在使用pycharm学习pandas的过程中我发现好多时候会发生不能输出所有列的情况,上网搜了一下,发现解决的办法是使用一个输出控制的函数. 在下面的代码中我们只是输出starbucks_store_ ...
随机推荐
- [转载】——故障排除:Shared Pool优化和Library Cache Latch冲突优化 (文档 ID 1523934.1)
原文链接:https://support.oracle.com/epmos/faces/DocumentDisplay?_adf.ctrlstate=23w4l35u5_4&id=152393 ...
- 使用Java实现单线程模式
我们都知道单例模式,有很多种实现方法.今天我们实现一个单线程实例模式,也就是说只能实例化该类的一个线程来运行,不允许有该类的多个线程实例存在.直接上代码: public class Singleton ...
- centos6.5无法访问网络
1.在network Adapter选中,右侧是否是选中为NAT 2.打开网络和共享中心-->更改适配器设置,VMnet8和VMnet1是否是自动获取了IP,自动获取ip连接上后 3.右击本地连 ...
- Spark运行模式与Standalone模式部署
上节中简单的介绍了Spark的一些概念还有Spark生态圈的一些情况,这里主要是介绍Spark运行模式与Spark Standalone模式的部署: Spark运行模式 在Spark中存在着多种运行模 ...
- linux下安装 oracle 11g
oracle 11g安装 一.环境准备 划分区 / 15000M /tmp 4096M /boot 100M Swap 4096M /u01 剩余空间 2.更改主机名,ip地址 3.安装软件包 那么l ...
- Common Bugs in C Programming
There are some Common Bugs in C Programming. Most of the contents are directly from or modified from ...
- javascript中的闭包
闭包一直是javascript中的难点,也比较不容易被初学者所掌握,"官方"的解释是:所谓"闭包",指的是一个拥有许多变量和绑定了这些变量的环境的表达式(通常是 ...
- 主席树——求静态区间第k大
例题:poj2104 http://poj.org/problem?id=2104 讲解:http://blog.sina.com.cn/s/blog_6022c4720102w03t.html ht ...
- git 修改最后一次提交的用户名 或者 commit的内容
修改git最后一次提交的命令 $ git commit --amend 修改git最后一次提交用户名的相关命令 git config user.name 'wangz' git config user ...
- rxjs5.X系列 —— filter系列 api 笔记
欢迎指导与讨论 :) 前言 本文是笔者翻译 RxJS 5.X 官网各类operation操作系列的的第二篇 -- filter转换.如有错漏,希望大家指出提醒O(∩_∩)O.更详细的资料尽在rxjs官 ...