+-

我正在将webapi项目用作我的身份验证服务器和资源服务器.目的是通过 Android应用程序访问服务.我还想要在MVC应用程序中编写的Web前端.我最初使用默认的MVC身份验证,但已移至Web Pai分发令牌.我可以从webapi服务中接收auth令牌,尽管我可能只是缓存在客户端,但仍将令牌以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(),
});
}
我在Configuration方法中调用它.
我似乎缺少的一点是如何利用将令牌转换为登录用户的方法.我似乎无法弄清楚反序列化发生的位置.我尝试将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.谁能告诉我我缺少从此令牌获取用户详细信息的信息吗?
按照下面的建议答案进行更新.现在,状态代码和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上缺少一些相关选项吗?
最佳答案
尝试这个.
将要内联实例化的OAuthBearerAuthenticationOptions保存到Startup.Auth中名为OAuthOpt(或您喜欢的任何东西)的静态变量中,并在要检索用户信息的任何位置使用下面的代码.
Microsoft.Owin.Security.AuthenticationTicket ticket = Startup.OAuthOpt.AccessTokenFormat.Unprotect(token);`
我建议您使用Json Web令牌(JWT)并使用CustomOAuthProvider自定义令牌生成.泰瑟·朱德(Taiseer Joudeh)的Here是一个很好的参考资料.您将必须使用此nuget package来解码承载令牌.
点击查看更多相关文章
转载注明原文:c#-从MVC中的Web api身份验证令牌中提取用户详细信息 - 乐贴网