【发布时间】:2015-03-11 05:42:27
【问题描述】:
我使用 webapi 项目作为我的身份验证服务器和资源服务器。目的是从 Android 应用程序访问服务。我还想要一个用 MVC 应用程序编写的 Web 前端。我最初使用默认的 MVC 身份验证,但已经转移到 web pai 分发令牌。我可以从 webapi 服务接收身份验证令牌,并且我将令牌发送到 cookie 中的客户端,尽管我可能只是缓存客户端。我目前正在运行以下 OAuthBearerAuthenticationProvider:
public class CookieOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
base.RequestToken(context);
var value = context.Request.Cookies["AuthToken"];
if (!string.IsNullOrEmpty(value))
{
context.Token = value;
}
return Task.FromResult<object>(null);
}
}
在我的启动课程中,我有这个方法:
private void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new CookieOAuthBearerProvider(),
});
}
我在配置方法中调用它。
我似乎缺少的一点是如何利用将我的令牌转换为登录用户。我似乎无法弄清楚反序列化发生在哪里。我尝试将我的 configueAuth 更改为:
private void ConfigureAuth(IAppBuilder app)
{
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new CookieOAuthBearerProvider(),
AccessTokenProvider = new AuthenticationTokenProvider()
{
OnReceive = receive
}
});
}
public static Action<AuthenticationTokenReceiveContext> receive = new Action<AuthenticationTokenReceiveContext>(c =>
{
c.DeserializeTicket(c.Token);
c.OwinContext.Environment["Properties"] = c.Ticket.Properties;
});
我的接收方法正在被调用。 AuthenticationTokenReceiveContext 附加了我的令牌,但 DeserializeTicket 返回 null。任何人都可以建议我从这个令牌中获取用户详细信息吗?
按照以下建议的答案进行更新。 Statrup 代码和 OAuthBearerAuthenticationOptions 现在如下所示:
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
private void ConfigureAuth(IAppBuilder app)
{
OAuthOpt = new OAuthBearerAuthenticationOptions()
{
Provider = new CookieOAuthBearerProvider(),
AccessTokenProvider = new AuthenticationTokenProvider()
{
OnReceive = receive
}
};
app.UseOAuthBearerAuthentication(OAuthOpt);
}
public static Action<AuthenticationTokenReceiveContext> receive = new Action<AuthenticationTokenReceiveContext>(c =>
{
var ticket = OAuthOpt.AccessTokenFormat.Unprotect(c.Token);
});
public static OAuthBearerAuthenticationOptions OAuthOpt { get; private set; }
}
但我仍然得到一个空值。我是否会遗漏 OAuthBearerAuthenticationOptions 上的一些相关选项?
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-web-api oauth-2.0