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

Is it possible to have a strip of cold climate in the middle of a planet?

Non-trope happy ending?

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

Does a 'pending' US visa application constitute a denial?

If magnesium reacts with oxygen to produce magnesium oxide only on the application of heat, then why isn't it categorised as an endothermic reaction?

Why can Carol Danvers change her suit colours in the first place?

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

What was this official D&D 3.5e Lovecraft-flavored rulebook?

2.8 Why are collections grayed out? How can I open them?

Lowest total scrabble score

is this legal and f i dont come up with extra money is the deal off

Store Credit Card Information in Password Manager?

Is it better practice to read straight from sheet music rather than memorize it?

copy and scale one figure (wheel)

Creepy dinosaur pc game identification

lightning-datatable row number error

Is there any references on the tensor product of presentable (1-)categories?

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

How to follow the Halacha?

Biological Blimps: Propulsion

What does routing an IP address mean?

Why should universal income be universal?

Why does the Sun have different day lengths, but not the gas giants?

Why Shazam when there is already Superman?



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

Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page