I have two main projects in my Web application:
- WebApi project as back-end to serve authentication and authorization for the Web project,using OWIN 2 with bearer tokens.
- Web project uses Angularjs.
The Web project works as expected(authentication and authorization are working)
Method: store token to localstorage, and send it using interceptors each request.
Now I want to add authentication and authorization to the the WebApi project,which would serve other modules like Hangfire,Elmah and Help pages. I added the same login logic, which works(Authorizing) and then redirect to Dashboard page(using Angularjs) which works.
But going to any other page(one of the mentioned modules) don't work.By not working: The user from the Owin context always null/empty.(see code)
For my understanding, I need somehow to send the token with each request which doesn't happen here.
Questions:
How can I achieve that(sending/getting the token)?
If cookie is the only/better approach ↴
How can I integrate cookie for project 1 and token for project 2?(Tried to use cookies, but it seems I'm doing it wrong, or does it work simultaneously with bearer tokens?)
Code:
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();
});
}
I tried for testing purposes:
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");
}
}
and in Configuration:
app.UseHangfire(hangfireConfig =>
{
hangfireConfig.UseAuthorizationFilters(
new HFAuthorizationFilter()
);
hangfireConfig.UseSqlServerStorage("Context");
hangfireConfig.UseServer();
});
Potential duplicate: Passing and verifying the OWIN Bearer token in Query String in WebAPI