I have many applications and I'm switching the authentication to ADFS, and I need to add custom data, lets say an array of roles from a database after the successful login.
Scenario Explained:
Each application has its own roles in DB,
during a user authentication after an authorization request was sent, Application_AuthenticateRequest(object sender, EventArgs e)
will be invoked, so I can add roles as claims like this
((ClaimsIdentity)((ClaimsPrincipal)currentUser).Identity)
.AddClaim(new Claim(ClaimTypes.Role, "role1FromDataBase"));
HttpContext.Current.User = currentUser;
But the Application_AuthenticateRequest()
method will be invoked for each request and I don't want to request the roles from DB every time.
So, I need to add those roles somewhere to then be able to call them. Of course, Sessions and Cookies are not the best practice when I deal with API role based authorization.
Applications have Controllers and APIs and my ADFS on Windows server 2012
My OWIN Startup is
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = adfsMetadata,
Notifications = new WsFederationAuthenticationNotifications()
{
RedirectToIdentityProvider = context =>
{
context.ProtocolMessage.Wreply = "https://localhost:44329/";
return Task.FromResult(0);
}
},
});
app.UseStageMarker(PipelineStage.Authenticate);
What can I do ?
after many hours i solved the problem
in Startup
Class and public void Configuration(IAppBuilder app)
method
we have to add claims with roles to WsFederationAuthenticationOptions
like this
app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = adfsMetadata,
Notifications = new WsFederationAuthenticationNotifications()
{
// this method will be invoked after login succes
SecurityTokenValidated = notification =>
{
ClaimsIdentity identity = notification.AuthenticationTicket.Identity;
// here we can add claims and specify the type, in my case i want to add Role Claim
identity.AddClaim(new Claim(ClaimTypes.Role, "student"));
return Task.FromResult(0);
},
RedirectToIdentityProvider = context =>
{
context.ProtocolMessage.Wreply = "https://localhost:44329/";
return Task.FromResult(0);
}
},
});