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_ ...
随机推荐
- web.xml 配置中classpath: 与classpath*:的区别
首先 classpath是指 WEB-INF文件夹下的classes目录 解释classes含义: 1.存放各种资源配置文件 eg.init.properties log4j.properties s ...
- 编译安装zabbix3.2
1.1 环境准备 系统环境准备:redhat 6.6 64位mysql-5.6.34php-5.6.28zabbix-3.2.1配置前先关闭iptables和SELINUX,避免安装过程中报错. # ...
- 前端少侠的ps故事
前端少侠的ps故事 正所谓,码在江湖,身不由己.自21世纪前后端分离,代码分工细化以来,前端与设计的合作也变得越来越重要.有人说,如果前端懂设计的话,工作会更快一点.倘若说我入前端半年能算半个前端少侠 ...
- SSH整合
首先,SSH不是一个框架,而是多个框架(struts+spring+hibernate)的集成,是目前较流行的一种Web应用程序开源集成框架,用于构建灵活.易于扩展的多层Web应用程序. 集成SSH框 ...
- 数据库 数据库SQL语句一
字符和日期 --字符和日期都要包含在单引号中 --字符大小写敏感,日期格式敏感 --默认的日期格式是DD-MON-RR --查询当前系统时间 SQL> select sysdate from d ...
- [LeetCode] Concatenated Words 连接的单词
Given a list of words (without duplicates), please write a program that returns all concatenated wor ...
- 写出将字符串中的数字转换为整型的方法,如:“as31d2v”->312,并写出相应的单元测试,正则去掉非数值、小数点及正负号外的字符串
写出将字符串中的数字转换为整型的方法,如:"as31d2v"->312,并写出相应的单元测试,输入超过int范围时提示不合法输入. public struct Convert ...
- C#工程引用自定义目录的DLL
在App.config里配置: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-mi ...
- 虚拟机下Centos7如何设置静态IP地址
最近在学习linux环境部署~~~~ 首先,将网络适配设置成为桥接模式 查看本机IP地址,ipconfig,记住ipv4地址和默认网关地址,等会配置的时候要用 启动Centos,进入终端模式,设置IP ...
- Javascript自执行匿名函数(function() { })()的原理分析
匿名函数指没有指定函数名或指针的函数,自执行匿名函数只是其中一种,下文中称这种函数为:自执行函数 下面是一个最常见的自执行函数: // 传统匿名函数 (function() { alert('hell ...