我正在Web应用程序上使用C#工作。目前(不记名)身份验证和令牌生成都发生在一个地方。
理赔完成后,我们有以下代码来获取工单:-
var ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
稍后,我们使用以下代码检查传回给我们的票证以获取票证:-
OAuthAuthenticationOptions.AccessTokenFormat.Unprotect(token);
当代码全部托管在一台机器上时,这一切都可以正常工作。
当我拆分代码以在不同的机器上工作时,我无法通过调用AccessTokenFormat. Un保护方法取回AuthenticationTicket。
在阅读了这篇文章OWIN承载令牌身份验证-我尝试在新机器的web. config文件中设置MachineKey以匹配现有服务器的MachineKey。
结果是解密过程不再抛出错误,但它为令牌返回null。
(当我没有正确的机器密钥时,我得到了一个解密运行时错误。)
如果我在这里犯了一个明显的错误,有人能告诉我吗?
此外,因为我是OWIN管道的新手;新项目中可能缺少一个配置步骤。
谢谢,大卫:-)
2016-05-23:来自Startup. Configuration的代码
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Build IoC Container
var container = new Container().Initialize();
// Initialize Logging and grab logger.
MyCustomLogger.Configure();
var logger = container.GetInstance<IMyCustomLogger>();
var userIdProvider = container.GetInstance<IUserIdProvider>();
var azureSignalRInterface = new SignalRInterface();
GlobalHost.DependencyResolver.Register(typeof(ITokenService), container.GetInstance<ITokenService>);
GlobalHost.DependencyResolver.Register(typeof(IMyCustomLogger), () => logger);
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => userIdProvider);
GlobalHost.DependencyResolver.Register(typeof(IExternalMessageBus), () => azureSignalRInterface);
GlobalHost.DependencyResolver.Register(typeof(ISerializer<>), () => typeof(JsonSerializer<>));
app.Use<ExceptionHandlerMiddleware>(logger, container);
app.Use<StructureMapMiddleware>(container);
// Setup Authentication
var authConfig = container.GetInstance<OwinAuthConfig>();
authConfig.ConfigureAuth(app);
// Load SignalR
app.MapSignalR("/signalR", new HubConfiguration()
{
EnableDetailedErrors = false,
EnableJSONP = true,
EnableJavaScriptProxies = true
});
}
}
容器()。初始化只是使用以下代码为结构图的依赖注入设置一些注册表:-
public static IContainer Initialize(this IContainer container)
{
container.Configure(x => {
x.AddRegistry<ServiceRegistry>();
x.AddRegistry<AlertsRegistry>();
x.AddRegistry<SignalRRegistry>();
});
return container;
}
此外,我的Global. asax.cs文件如下所示:-
protected void Application_Start()
{
//GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configure(config =>
{
AuthConfig.Register(config);
WebApiConfig.Register(config);
});
}
AuthConfig类看起来像这样:-
public static class AuthConfig
{
/// <summary>
/// Registers authorization configuration with global HttpConfiguration.
/// </summary>
/// <param name="config"></param>
public static void Register(HttpConfiguration config)
{
// Forces WebApi/OAuth to handle authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
}
}
其中OAuthDefault. AuthenticationType
是字符串常量。
最后,我的OwinAuthConfig代码如下:-
public class OwinAuthConfig
{
public static OAuthAuthorizationServerOptions OAuthAuthorizationOptions { get; private set; }
public static OAuthBearerAuthenticationOptions OAuthAuthenticationOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the application for OAuth based flow
PublicClientId = "MyCustom.SignalRMessaging";
OAuthAuthorizationOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Authenticate"), // PathString.FromUriComponent("https://dev.MyCustom-api.com/Authenticate"),
Provider = new MyCustomDbLessAuthorizationProvider(
PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// TODO: change when we go to production.
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthAuthorizationServer(OAuthAuthorizationOptions);
OAuthAuthenticationOptions = new OAuthBearerAuthenticationOptions
{
Provider = new MyCustomDbLessAuthenticationProvider()
};
app.UseOAuthBearerAuthentication(OAuthAuthenticationOptions);
}
public static AuthenticationTicket UnprotectToken(string token)
{
return OAuthAuthenticationOptions.AccessTokenFormat.Unprotect(token);
}
public void ConfigureHttpAuth(HttpConfiguration config)
{
config.Filters.Add(new AuthorizeAttribute());
}
}
2016-05-26:添加了配置文件片段。这是生成令牌的服务器上的配置:-
<system.web>
<machineKey
validationKey="..."
decryptionKey="..." validation="SHA1" decryption="AES" />
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<customErrors mode="Off" />
</system.web>
这是尝试使用令牌的SignalR服务器上的配置:-
<system.web>
<machineKey
validationKey="..."
decryptionKey="..." validation="SHA1" decryption="AES" />
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<customErrors mode="Off" />
</system.web>
在资源服务器中,您应该使用OAuthBearerAuthenticationOptions. AccessTokenFormat
属性而不是OAuthorizationServerOptions.AccessTokenFormat
。请参阅留档链接。
对于IAuthenticationTokenReceiveContext
中的AuthenticationTokenProvider. Recect()
方法,您还可以执行context.DeserializeTicket(context.Token);
。
正如您所指出的,两个服务器中的MachineKey应该相同。
我希望这能有所帮助。
编辑(2016-05-24)
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
// Now you can access to context.Ticket
...
}
另一种可能性是web. config中的机器密钥在部署Web后发生了变化,导致编译的dll中的机器密钥与dll中的机器密钥不匹配。