Authentication 使用Authorize属性的asp.net web api 2自定义owin身份验证中间件
我正在构建一个WebAPI,在这里我想使用内置的基础设施来处理角色,如果用户没有所需的角色,则拒绝用户访问。api将作为应用程序在现有站点上运行,使用站点cookie进行身份验证 为了进行身份验证,我创建了一个简单的自定义中间件,在其中验证cookie,如果发现cookie有效,则创建一个具有适当角色的标识 当请求到达控制器时会出现问题,在控制器中访问被拒绝。因为我在自定义中间件中创建的标识位于owin上下文中,而不是HttpContext.Current.User.identity中,我认为它应该位于此处,以便Authorize属性能够正常工作 当身份处于“错误”的环境中时,如何解决这个问题 为了简单起见,cookie逻辑已经简化Authentication 使用Authorize属性的asp.net web api 2自定义owin身份验证中间件,authentication,asp.net-web-api,owin,claims-based-identity,Authentication,Asp.net Web Api,Owin,Claims Based Identity,我正在构建一个WebAPI,在这里我想使用内置的基础设施来处理角色,如果用户没有所需的角色,则拒绝用户访问。api将作为应用程序在现有站点上运行,使用站点cookie进行身份验证 为了进行身份验证,我创建了一个简单的自定义中间件,在其中验证cookie,如果发现cookie有效,则创建一个具有适当角色的标识 当请求到达控制器时会出现问题,在控制器中访问被拒绝。因为我在自定义中间件中创建的标识位于owin上下文中,而不是HttpContext.Current.User.identity中,我认为它
public class ApiCookieAuthMiddleware : OwinMiddleware
{
public ApiCookieAuthMiddleware(OwinMiddleware next) : base(next)
{
}
public override async Task Invoke(IOwinContext context)
{
if (context.Request.Cookies.Any(x => x.Key == "c"))
{
var identity = new ClaimsIdentity();
identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
context.Authentication.SignIn(identity);
await Next.Invoke(context);
}
else
{
context.Response.StatusCode = 401;
context.Response.ReasonPhrase = "some error";
return;
}
}
}
控制器
[Authorize(Roles = "User")]
public class TestController : ApiController
{
[HttpGet]
public IHttpActionResult GetHello()
{
return Ok("Hello World!!!");
}
}
将创建的标识传递给当前线程将创建的标识传递给当前线程
[Authorize(Roles = "User")]
public class TestController : ApiController
{
[HttpGet]
public IHttpActionResult GetHello()
{
return Ok("Hello World!!!");
}
}