IdentityServer4 role based authentication keeps looping back to OpenIdConnectAuthenticationNotifications eventThe definitive guide to form-based website authenticationWhat is token based authentication?Best practice for REST token-based authentication with JAX-RS and JerseyRole based authorization with IdentityServer4Azure rsaKey from KeyVaultKeyResolver is always nullHow to prevent an ASP NET MVC application requesting authorization from Google every hour?IdentityServer4 client redirectURI issueCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 Admin UIIdentityServer4 without HTTPS not working

Should I stop contributing to retirement accounts?

Count the occurrence of each unique word in the file

How much character growth crosses the line into breaking the character

Which one is correct as adjective “protruding” or “protruded”?

What is this called? Old film camera viewer?

Is this toilet slogan correct usage of the English language?

How to explain what's wrong with this application of the chain rule?

It grows, but water kills it

If a character has darkvision, can they see through an area of nonmagical darkness filled with lightly obscuring gas?

C++ debug/print custom type with GDB : the case of nlohmann json library

What does routing an IP address mean?

Did Swami Prabhupada reject Advaita?

Pre-mixing cryogenic fuels and using only one fuel tank

Start making guitar arrangements

Yosemite Fire Rings - What to Expect?

How could a planet have erratic days?

What should you do if you miss a job interview (deliberately)?

The IT department bottlenecks progress. How should I handle this?

What prevents the use of a multi-segment ILS for non-straight approaches?

"Spoil" vs "Ruin"

Added a new user on Ubuntu, set password not working?

A social experiment. What is the worst that can happen?

Aragorn's "guise" in the Orthanc Stone

Removing files under particular conditions (number of files, file age)



IdentityServer4 role based authentication keeps looping back to OpenIdConnectAuthenticationNotifications event


The definitive guide to form-based website authenticationWhat is token based authentication?Best practice for REST token-based authentication with JAX-RS and JerseyRole based authorization with IdentityServer4Azure rsaKey from KeyVaultKeyResolver is always nullHow to prevent an ASP NET MVC application requesting authorization from Google every hour?IdentityServer4 client redirectURI issueCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 Admin UIIdentityServer4 without HTTPS not working













0















I have a IdentityServer4 with clients,scopes and resources.



This works perfectly when I mark my controller with Authorize attribute.



But this fails when I try to work with role based authentication.



I am using Hybridflow , all scopes are there on server and client.



From client side , I am using MVC5 with UseOpenIdConnectAuthentication.



Server Code:

public static IEnumerable<Client> Clients()

return new[]
new Client

ClientId = "TestWebApp_Hybrid",
ClientName = "TestWebApp",
ClientSecrets = new List<Secret>

new Secret("secret".Sha256())
,
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = new List<string>

"http://localhost:57014/signin-oidc",
"http://localhost:57014",
,
PostLogoutRedirectUris = new List<string>

"http://localhost:57014/signout-callback-oidc",
,
AllowedScopes = new List<string> StandardScopes.OpenId, StandardScopes.Profile, "roles",
Enabled = true,
AccessTokenType = AccessTokenType.Jwt,
IdentityTokenLifetime = 3600,
AccessTokenLifetime = 3600

;

public static IEnumerable<IdentityResource> IdentityResources()

return new IdentityResource[]
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResource("roles","Your roles",new List<string> "role")
;



For the users, I am adding roles using role manager,



public async Task EnsureSeedData()

foreach (var user in InMemoryConfiguration.Users())

if (await _userManager.FindByEmailAsync(user.Username) == null)

// Find User and Create, removed code for brevity

await _userManager.AddClaimAsync(user, new Claim("role","Admin"));







On Asp.NET MVC startup file , I have following code:



app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions

ClientId = "TestWebApp_Hybrid",
ClientSecret= "secret",
AuthenticationType = "oidc",
Authority = ConfigurationManager.AppSettings["Authority"],
RedirectUri = $"ConfigurationManager.AppSettings["RedirectUri"]/signin-oidc",
Scope = "openid profile roles",
ResponseType = "code id_token",
UseTokenLifetime = false,
SignInAsAuthenticationType = "Cookies",
PostLogoutRedirectUri = $"ConfigurationManager.AppSettings["RedirectUri"]/signout-callback-oidc",

Notifications = new OpenIdConnectAuthenticationNotifications

SecurityTokenValidated = notification =>

var identity = notification.AuthenticationTicket.Identity;

identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));

notification.AuthenticationTicket = new AuthenticationTicket(identity, notification.AuthenticationTicket.Properties);

return Task.FromResult(0);
,
RedirectToIdentityProvider = notification =>

if (notification.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest)

return Task.FromResult(0);


var idTokenHint = notification.OwinContext.Authentication.User.FindFirst("id_token");

if (idTokenHint != null)

notification.ProtocolMessage.IdTokenHint = idTokenHint.Value;


return Task.FromResult(0);


);
}









share|improve this question
























  • Is the controller you want to bring role based authorization to on the client application? Also elaborate on how you expect the behavior of the login code to look like (step by step), how the behavior of your code looks like (step by step), and how they differ.

    – Randy
    Mar 9 at 12:11















0















I have a IdentityServer4 with clients,scopes and resources.



This works perfectly when I mark my controller with Authorize attribute.



But this fails when I try to work with role based authentication.



I am using Hybridflow , all scopes are there on server and client.



From client side , I am using MVC5 with UseOpenIdConnectAuthentication.



Server Code:

public static IEnumerable<Client> Clients()

return new[]
new Client

ClientId = "TestWebApp_Hybrid",
ClientName = "TestWebApp",
ClientSecrets = new List<Secret>

new Secret("secret".Sha256())
,
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = new List<string>

"http://localhost:57014/signin-oidc",
"http://localhost:57014",
,
PostLogoutRedirectUris = new List<string>

"http://localhost:57014/signout-callback-oidc",
,
AllowedScopes = new List<string> StandardScopes.OpenId, StandardScopes.Profile, "roles",
Enabled = true,
AccessTokenType = AccessTokenType.Jwt,
IdentityTokenLifetime = 3600,
AccessTokenLifetime = 3600

;

public static IEnumerable<IdentityResource> IdentityResources()

return new IdentityResource[]
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResource("roles","Your roles",new List<string> "role")
;



For the users, I am adding roles using role manager,



public async Task EnsureSeedData()

foreach (var user in InMemoryConfiguration.Users())

if (await _userManager.FindByEmailAsync(user.Username) == null)

// Find User and Create, removed code for brevity

await _userManager.AddClaimAsync(user, new Claim("role","Admin"));







On Asp.NET MVC startup file , I have following code:



app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions

ClientId = "TestWebApp_Hybrid",
ClientSecret= "secret",
AuthenticationType = "oidc",
Authority = ConfigurationManager.AppSettings["Authority"],
RedirectUri = $"ConfigurationManager.AppSettings["RedirectUri"]/signin-oidc",
Scope = "openid profile roles",
ResponseType = "code id_token",
UseTokenLifetime = false,
SignInAsAuthenticationType = "Cookies",
PostLogoutRedirectUri = $"ConfigurationManager.AppSettings["RedirectUri"]/signout-callback-oidc",

Notifications = new OpenIdConnectAuthenticationNotifications

SecurityTokenValidated = notification =>

var identity = notification.AuthenticationTicket.Identity;

identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));

notification.AuthenticationTicket = new AuthenticationTicket(identity, notification.AuthenticationTicket.Properties);

return Task.FromResult(0);
,
RedirectToIdentityProvider = notification =>

if (notification.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest)

return Task.FromResult(0);


var idTokenHint = notification.OwinContext.Authentication.User.FindFirst("id_token");

if (idTokenHint != null)

notification.ProtocolMessage.IdTokenHint = idTokenHint.Value;


return Task.FromResult(0);


);
}









share|improve this question
























  • Is the controller you want to bring role based authorization to on the client application? Also elaborate on how you expect the behavior of the login code to look like (step by step), how the behavior of your code looks like (step by step), and how they differ.

    – Randy
    Mar 9 at 12:11













0












0








0








I have a IdentityServer4 with clients,scopes and resources.



This works perfectly when I mark my controller with Authorize attribute.



But this fails when I try to work with role based authentication.



I am using Hybridflow , all scopes are there on server and client.



From client side , I am using MVC5 with UseOpenIdConnectAuthentication.



Server Code:

public static IEnumerable<Client> Clients()

return new[]
new Client

ClientId = "TestWebApp_Hybrid",
ClientName = "TestWebApp",
ClientSecrets = new List<Secret>

new Secret("secret".Sha256())
,
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = new List<string>

"http://localhost:57014/signin-oidc",
"http://localhost:57014",
,
PostLogoutRedirectUris = new List<string>

"http://localhost:57014/signout-callback-oidc",
,
AllowedScopes = new List<string> StandardScopes.OpenId, StandardScopes.Profile, "roles",
Enabled = true,
AccessTokenType = AccessTokenType.Jwt,
IdentityTokenLifetime = 3600,
AccessTokenLifetime = 3600

;

public static IEnumerable<IdentityResource> IdentityResources()

return new IdentityResource[]
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResource("roles","Your roles",new List<string> "role")
;



For the users, I am adding roles using role manager,



public async Task EnsureSeedData()

foreach (var user in InMemoryConfiguration.Users())

if (await _userManager.FindByEmailAsync(user.Username) == null)

// Find User and Create, removed code for brevity

await _userManager.AddClaimAsync(user, new Claim("role","Admin"));







On Asp.NET MVC startup file , I have following code:



app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions

ClientId = "TestWebApp_Hybrid",
ClientSecret= "secret",
AuthenticationType = "oidc",
Authority = ConfigurationManager.AppSettings["Authority"],
RedirectUri = $"ConfigurationManager.AppSettings["RedirectUri"]/signin-oidc",
Scope = "openid profile roles",
ResponseType = "code id_token",
UseTokenLifetime = false,
SignInAsAuthenticationType = "Cookies",
PostLogoutRedirectUri = $"ConfigurationManager.AppSettings["RedirectUri"]/signout-callback-oidc",

Notifications = new OpenIdConnectAuthenticationNotifications

SecurityTokenValidated = notification =>

var identity = notification.AuthenticationTicket.Identity;

identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));

notification.AuthenticationTicket = new AuthenticationTicket(identity, notification.AuthenticationTicket.Properties);

return Task.FromResult(0);
,
RedirectToIdentityProvider = notification =>

if (notification.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest)

return Task.FromResult(0);


var idTokenHint = notification.OwinContext.Authentication.User.FindFirst("id_token");

if (idTokenHint != null)

notification.ProtocolMessage.IdTokenHint = idTokenHint.Value;


return Task.FromResult(0);


);
}









share|improve this question
















I have a IdentityServer4 with clients,scopes and resources.



This works perfectly when I mark my controller with Authorize attribute.



But this fails when I try to work with role based authentication.



I am using Hybridflow , all scopes are there on server and client.



From client side , I am using MVC5 with UseOpenIdConnectAuthentication.



Server Code:

public static IEnumerable<Client> Clients()

return new[]
new Client

ClientId = "TestWebApp_Hybrid",
ClientName = "TestWebApp",
ClientSecrets = new List<Secret>

new Secret("secret".Sha256())
,
AllowedGrantTypes = GrantTypes.Hybrid,
RedirectUris = new List<string>

"http://localhost:57014/signin-oidc",
"http://localhost:57014",
,
PostLogoutRedirectUris = new List<string>

"http://localhost:57014/signout-callback-oidc",
,
AllowedScopes = new List<string> StandardScopes.OpenId, StandardScopes.Profile, "roles",
Enabled = true,
AccessTokenType = AccessTokenType.Jwt,
IdentityTokenLifetime = 3600,
AccessTokenLifetime = 3600

;

public static IEnumerable<IdentityResource> IdentityResources()

return new IdentityResource[]
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResource("roles","Your roles",new List<string> "role")
;



For the users, I am adding roles using role manager,



public async Task EnsureSeedData()

foreach (var user in InMemoryConfiguration.Users())

if (await _userManager.FindByEmailAsync(user.Username) == null)

// Find User and Create, removed code for brevity

await _userManager.AddClaimAsync(user, new Claim("role","Admin"));







On Asp.NET MVC startup file , I have following code:



app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions

ClientId = "TestWebApp_Hybrid",
ClientSecret= "secret",
AuthenticationType = "oidc",
Authority = ConfigurationManager.AppSettings["Authority"],
RedirectUri = $"ConfigurationManager.AppSettings["RedirectUri"]/signin-oidc",
Scope = "openid profile roles",
ResponseType = "code id_token",
UseTokenLifetime = false,
SignInAsAuthenticationType = "Cookies",
PostLogoutRedirectUri = $"ConfigurationManager.AppSettings["RedirectUri"]/signout-callback-oidc",

Notifications = new OpenIdConnectAuthenticationNotifications

SecurityTokenValidated = notification =>

var identity = notification.AuthenticationTicket.Identity;

identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));

notification.AuthenticationTicket = new AuthenticationTicket(identity, notification.AuthenticationTicket.Properties);

return Task.FromResult(0);
,
RedirectToIdentityProvider = notification =>

if (notification.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest)

return Task.FromResult(0);


var idTokenHint = notification.OwinContext.Authentication.User.FindFirst("id_token");

if (idTokenHint != null)

notification.ProtocolMessage.IdTokenHint = idTokenHint.Value;


return Task.FromResult(0);


);
}






c# asp.net-mvc asp.net-mvc-4 authentication identityserver4






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 13:14







Simsons

















asked Mar 8 at 4:21









SimsonsSimsons

5,19830106207




5,19830106207












  • Is the controller you want to bring role based authorization to on the client application? Also elaborate on how you expect the behavior of the login code to look like (step by step), how the behavior of your code looks like (step by step), and how they differ.

    – Randy
    Mar 9 at 12:11

















  • Is the controller you want to bring role based authorization to on the client application? Also elaborate on how you expect the behavior of the login code to look like (step by step), how the behavior of your code looks like (step by step), and how they differ.

    – Randy
    Mar 9 at 12:11
















Is the controller you want to bring role based authorization to on the client application? Also elaborate on how you expect the behavior of the login code to look like (step by step), how the behavior of your code looks like (step by step), and how they differ.

– Randy
Mar 9 at 12:11





Is the controller you want to bring role based authorization to on the client application? Also elaborate on how you expect the behavior of the login code to look like (step by step), how the behavior of your code looks like (step by step), and how they differ.

– Randy
Mar 9 at 12:11












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056678%2fidentityserver4-role-based-authentication-keeps-looping-back-to-openidconnectaut%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55056678%2fidentityserver4-role-based-authentication-keeps-looping-back-to-openidconnectaut%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme