Asp.net web api 如何在Asp.NET WebAPI中验证收到的令牌?

Asp.net web api 如何在Asp.NET WebAPI中验证收到的令牌?,asp.net-web-api,asp.net-identity,owin,bearer-token,authorize-attribute,Asp.net Web Api,Asp.net Identity,Owin,Bearer Token,Authorize Attribute,我的项目包含一个ASP.NET MVC应用程序(没有身份验证)和两个Web API 第一个API(Account API)构建在Owin中间件之上,使用ASP.NET标识,以便对ASP.NET MVC进行基于令牌的身份验证 这对于ASP.NET MVC非常有效 但第二个API是数据处理程序API(data API) 问题是我需要授权数据API上的传入请求。从ASP.NET MVC应用程序中,我有以下请求 开始编辑1 // The MVC controller makes a request in

我的项目包含一个ASP.NET MVC应用程序(没有身份验证)和两个Web API

第一个API(Account API)构建在Owin中间件之上,使用ASP.NET标识,以便对ASP.NET MVC进行基于令牌的身份验证

这对于ASP.NET MVC非常有效

但第二个API是数据处理程序API(data API)

问题是我需要授权数据API上的传入请求。从ASP.NET MVC应用程序中,我有以下请求

开始编辑1

// The MVC controller makes a request in order to authenticate the user.
// If the authentication succeeds, an access token is returned.

var authorizationUrl = "my.authorization.api";
HttpResponseMessage result = httpClient.PostAsync(authorizationUrl, content).Result;


// In the Home controller I have these lines of code.

var user = ((ClaimsPrincipal) HttpContext.Current.User);
var token = x.Claims.First(t => t.Type == "AccessToken").Value;


// Now I just need to call the Data API.

var dataUrl = "my.data.api/home";
var request = WebRequest.Create(dataUrl) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + accessToken);
var response = (HttpWebResponse) request.GetResponse();
数据API在HomeController上具有[Authorize]属性,每次调用任何方法时,我都会收到401个未经授权的消息

结束编辑1

// The MVC controller makes a request in order to authenticate the user.
// If the authentication succeeds, an access token is returned.

var authorizationUrl = "my.authorization.api";
HttpResponseMessage result = httpClient.PostAsync(authorizationUrl, content).Result;


// In the Home controller I have these lines of code.

var user = ((ClaimsPrincipal) HttpContext.Current.User);
var token = x.Claims.First(t => t.Type == "AccessToken").Value;


// Now I just need to call the Data API.

var dataUrl = "my.data.api/home";
var request = WebRequest.Create(dataUrl) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + accessToken);
var response = (HttpWebResponse) request.GetResponse();
问题是:如何使用来自请求头(从MVC应用程序发送)的accessToken验证传入请求(在数据API上)


谢谢大家!

您正在尝试在两个API之间实现单点登录(SSO)吗?因为只有MVC应用程序在调用另一个API,是的。编辑1:如果我有其他多个互不交互的API,我认为应该以相同的方式处理请求。是否要在数据API中提取从ASP.NET MVC发送的承载令牌?你从API收到未经授权的消息吗?@Damith,是的,我从API收到未经授权的消息。我不知道如何使用不记名令牌来授权随附的请求。@PianoSong您能与我们共享您的代码吗?至少是样品。