我的 Web 应用程序中有两个主要项目:
- WebApi 项目作为后端为 Web 项目提供身份验证和授权,使用带有不记名令牌的 OWIN 2。
- Web 项目使用 Angularjs。
Web 项目按预期工作(身份验证和授权工作)
方法:将token存储到localstorage,每次请求使用拦截器发送。
现在我想为 WebApi 项目添加身份验证和授权,该项目将为 Hangfire、Elmah 和帮助页面等其他模块提供服务。我添加了相同的登录逻辑,该逻辑有效(授权),然后重定向到有效的仪表板页面(使用 Angularjs)。
但是转到任何其他页面(提到的模块之一)都不起作用。由于不起作用:Owin 上下文中的用户始终为空/空。(请参阅代码)
就我的理解而言,我需要以某种方式将令牌与此处未发生的每个请求一起发送。
问题:
我该如何实现(发送/获取令牌)?
如果 cookie 是唯一/更好的方法 ↴</p>
如何集成项目 1 的 cookie 和项目 2 的令牌?(尝试使用 cookie,但似乎我做错了,或者它是否与不记名令牌同时工作?)
代码:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new SimpleAuthorizationServerProvider(),
RefreshTokenProvider = new SimpleRefreshTokenProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
GlobalConfiguration.Configure(WebApiConfig.Register);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
AreaRegistration.RegisterAllAreas();
app.UseHangfire(hangfireConfig =>
{
config.UseAuthorizationFilters(
new AuthorizationFilter { Users = "admin, superuser", Roles = "advanced" },
new ClaimsBasedAuthorizationFilter("name", "value")
);
hangfireConfig.UseSqlServerStorage("Context");
hangfireConfig.UseServer();
});
}
我尝试用于测试目的:
public class HFAuthorizationFilter : Hangfire.Dashboard.IAuthorizationFilter
{
public bool Authorize(IDictionary<string, object> owinEnvironment)
{
var context = new OwinContext(owinEnvironment);
if (context.Authentication.User == null)
return false;//Always null
return context.Authentication.User.HasClaim(ClaimTypes.Role, "SuperAdmin")
|| context.Authentication.User.HasClaim(ClaimTypes.Role, "Admin");
}
}
并在配置中:
app.UseHangfire(hangfireConfig =>
{
hangfireConfig.UseAuthorizationFilters(
new HFAuthorizationFilter()
);
hangfireConfig.UseSqlServerStorage("Context");
hangfireConfig.UseServer();
});