I'm using identity server 3 with windows authentication and adding claims to user's token. I noticed GetProfileDataAsync is called twice which the callers are "ClaimsProviderAccessToken" which doesn't have any requested claims and "ClaimsProviderIdentityToken" is the caller which does. How do I get the RequestedClaimTypes such as Role, Email, whatever in the "ClaimsProviderAccessToken" ??
public override Task GetProfileDataAsync(ProfileDataRequestContext context)
{
// issue the claims for the user
var user = Users.SingleOrDefault(x => x.Subject == context.Subject.GetSubjectId());
if (user != null && context.RequestedClaimTypes != null)
{
context.IssuedClaims = user.Claims.Where(x => context.RequestedClaimTypes.Contains(x.Type));
}
//NOTE: Uncomment and all the claims I need are in access token ?? Comment out and no claims in Access Token ??
//context.IssuedClaims = user.Claims;
return Task.FromResult(0);
}
Here's my scope claim that is requesting the claims to be in access token:
new Scope
{
Name = "api",
Enabled = true,
DisplayName = "Sample API",
Description = "Access to a simple API",
Type= ScopeType.Resource,
IncludeAllClaimsForUser = true,
Claims = new List<ScopeClaim>
{
new ScopeClaim(Constants.ClaimTypes.Name),
new ScopeClaim(Constants.ClaimTypes.Role),
new ScopeClaim(Constants.ClaimTypes.Email),
},
ScopeSecrets = new List<Secret>
{
new Secret("api-secret".Sha256())
}
}
Am I missing something or is it correct to just set the context.IssuedClaims to the user.Claims or should I file by RequestedClaimTypes?? I'm really lost a little trying to figure how this works and not sure if setting context.IssuedClaims = user.Claims although this seems like the behavior I need ???
I actually found the answer, setting the IncludeAllClaimsForUser = true clears out the claims, once I removed that the context.RequestedClaimsTypes are not null when requesting the access token.
Related
I'm using identityserver4 for single sign-on. For most of the time application function smoothly but intermittently we face a redirect loop issue which becomes a show stopper for us until we restart's our app service. The page goes on loading continuously before finally showing a 'Bad request - Request Too Long' page with message: HTTP Error 400. The size of the request headers is too long. If we check the network tab, we can see that the application is looping between the identity server and client application redirect sign in pages. The application insight tells us that the client app gives a 401 on his home/index page and then a 302 on the signin-oidc url, then goes to the identity server connect/token, then connect/userinfo endpoints to get claims and comes back to the client home/index page to again get a 401. The loop continues (Identity server says user is authenticated while client says it is not). We are unable to find a fix for this since long. Any help is appreciated. Attaching the client side configuration for reference.
Findings
Our client app is an mvc app & we have used Session's & TempData in few area's. This areas are the triggering point of the redirect issue. What we have observed is, when the client initially login the authentication cookie is created (Cookie Name: AudDiscoveryAuth) and I could see it being passed in header for each request made to the controller actions. But once the user visit's any such area where we have used Session/TempData and Log out or any other user tries to login, Identity server successfully authenticates the user also the userendpoint to retrieve the details is being invoked however the cookie itself is not being created and is missing in every request to the Index/Home action method hence the redirect loop. Wondering what could be hampering in issuing cookie when using session variable elsewhere in the application or is their a setting missing.
Also in every redirect the occurrence of OpenIdConnect.nonce.XXX cookie is incremented. Once the count of OpenIdConnect.nonce.XXX reaches more then a certain level we get the bad request error page
public void Configuration(IAppBuilder app)
{
string baseClientAddress = ConfigurationManager.AppSettings["ApplicationUrl"];
int slidingExpiryHrs = Convert.ToInt32(ConfigurationManager.AppSettings["SlidingExpiryHrs"]);
int slidingExpiryMins = Convert.ToInt32(ConfigurationManager.AppSettings["SlidingExpiryMins"]);
TimeSpan expireTimeSpan = new TimeSpan(slidingExpiryHrs, slidingExpiryMins, 0);
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationType,
CookieName = "AudDiscoveryAuth",
ExpireTimeSpan = expireTimeSpan,
SlidingExpiration = true
});
app.UseOpenIdConnectAuthenticationPatched(new OpenIdConnectAuthenticationOptions
{
ClientId = "ratingspro.web",
Authority = IdsvrConstants.BaseAddress,
RedirectUri = baseClientAddress + "signin-oidc/",
PostLogoutRedirectUri = baseClientAddress + "signout-callback-oidc/",
ResponseType = "code id_token",
Scope = "openid api1 ratingspro.webapi offline_access",
UseTokenLifetime = false,
SignInAsAuthenticationType = DefaultAuthenticationType,
RequireHttpsMetadata = true,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = async n =>
{
var client = HttpClientFactory.Create();
var tokenResponse = await client.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
{
Address = IdsvrConstants.TokenEndpoint,
ClientId = "ratingspro.web",
ClientSecret = "secret",
Code = n.Code,
RedirectUri = n.RedirectUri,
});
if (tokenResponse.IsError)
{
LogHelper.LogMessage("RatingsproApp: Startup => tokenResponseError: " + tokenResponse.Error);
throw new AuthenticationException(tokenResponse.Error);
}
var userInfoResponse = await client.GetUserInfoAsync(new UserInfoRequest
{
Address = IdsvrConstants.UserInfoEndpoint,
Token = tokenResponse.AccessToken
});
if (userInfoResponse.IsError)
{
throw new AuthenticationException(userInfoResponse.Error);
}
var claims = userInfoResponse.Claims;
if (claims.Any(c => c.Type == "ApplicationAccessDenied"))
{
throw new AuthenticationException(claims.FirstOrDefault(c => c.Type == "ApplicationAccessDenied").Value);
}
// create new identity
var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
id.AddClaims(claims);
id.AddClaim(new Claim("AccessToken", tokenResponse.AccessToken));
id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString(CultureInfo.InvariantCulture)));
id.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
client.Dispose();
n.AuthenticationTicket = new AuthenticationTicket(
new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"),
n.AuthenticationTicket.Properties);
},
RedirectToIdentityProvider = n =>
{
if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
{
var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
n.ProtocolMessage.IdTokenHint = idTokenHint;
}
return Task.FromResult(0);
},
AuthenticationFailed = x =>
{
x.ProtocolMessage.RedirectUri = "/";
return Task.CompletedTask;
}
}
});
}
}
I'm creating a PWA with React and using Auth0 as my identity provider and JWT Bearer token as authentication. I am injecting roles into my JWT token so that the client-side can limit what options are available to the user and I have this working pretty well.
I want to now limit the server side so that an endpoint can't be called unless the user has the necessary role(s) required to access that endpoint.
Annoyingly, Auth0 doesn't appear to support adding in the roles or role claim that aspnet core seems to handle OOTB; it requires that a domain preface the roles in the claims definition. ie, https://bob.com/roles as the claim.
I'm trying to work out how to get the Authorize(Roles = "Administrator") attribute to honour the domain-prefaced claim for roles.
I have tried updating the Auth0 Rule to set the role or roles property but these never get returned; only the domain-prefaced roles claim seems to return.
I have found other info for more specific Authentication providers and they include a MapJsonKey extension on ClaimActions that look like they would fit the bill, but the standard AuthenticationOptions object in the AddAuthentication extension doesn't appear to have this.
My ConfigureServices in App.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// 1. Add Authentication Services
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = Configuration["Auth0:Authority"];
options.Audience = Configuration["Auth0:ClientId"];
});
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
My Rule for injecting the roles into the JWT in Auth0:
function (user, context, callback) {
const namespace = 'http://bob.com';
const assignedRoles = (context.authorization || {}).roles;
let idTokenClaims = context.idToken || {};
let accessTokenClaims = context.accessToken || {};
idTokenClaims[`roles`] = assignedRoles; // This was an attempt to set the roles in 'roles' but doesn't get returned.
accessTokenClaims[`roles`] = assignedRoles;
idTokenClaims[`${namespace}/roles`] = assignedRoles; // This does get returned
accessTokenClaims[`${namespace}/roles`] = assignedRoles;
context.idToken = idTokenClaims;
context.accessToken = accessTokenClaims;
callback(null, user, context);
}
Example JWT Payload
{
"http://bob.com/roles": [
"Administrator"
],
"given_name": "Name",
"iss": "{issuer}",
"sub": "{subject}",
"aud": "{audience}"
}
asp.net core Action (taken from the example project, but with auth added)
[HttpGet("[action]"), Authorize(Roles = "Administrator")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
});
}
What I would like is to be able to either map the http://bob.com/roles to roles, get the aspnet core Authorize attribute to look at the http://bob.com/roles, or get Auth0 to be able to return the roles in a 'roles' object.
Where I got the MapJsonKey info from:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/additional-claims?view=aspnetcore-2.2
Using Roles with the ASP.NET Core JWT middleware
https://www.jerriepelser.com/blog/using-roles-with-the-jwt-middleware/
For anyone who finds this, I found a solution to this. If you update the JWT claim to be http://schemas.microsoft.com/ws/2008/06/identity/claims/role then it all works straight away.
Updated Auth0 Rule
function (user, context, callback) {
const assignedRoles = (context.authorization || {}).roles;
let idTokenClaims = context.idToken || {};
let accessTokenClaims = context.accessToken || {};
idTokenClaims[`http://schemas.microsoft.com/ws/2008/06/identity/claims/role`] = assignedRoles;
accessTokenClaims[`http://schemas.microsoft.com/ws/2008/06/identity/claims/role`] = assignedRoles;
context.idToken = idTokenClaims;
context.accessToken = accessTokenClaims;
callback(null, user, context);
}
I am using Identity Server 3. I have couple applications ie. Client configured and have few users configured. How do i establish the relationship between User and a Client and also view all applications that the selected User has access to.
Update 1
I am sorry if question was confusing. On IdSvr3 home page, there is a link to revoke application permissions. I am guessing in order to revoke the permission you have to first establish the relationship between user and application.
and i wanted to know how to establish that permission when i add new user?
There's no direct way to limit one or multiple users to a certain client. This is where you should think about implementing your own custom validation. Fortunately, the IdentityServer provides an extensibility point for this kind of requirement.
ICustomRequestValidator
You should implement this interface to further validate users to see if they belong to certain clients and filter them out. You can look into the user details by looking at ValidatedAuthorizeRequest.Subject. This custom validator will start after validating optional parameters such as nonce, prompt, arc_values ( AuthenticationContextReference ), login_hint, and etc. The endpoint is AuthorizeEndPointController and the default implementation of the interface for the tailored job is AuthorizeRequestValidator and its RunValidationAsync. You should take a look at the controller and the class.
Implementation tip
By the time the custom request validation begins, a Client reference will be presented in ValidatedAuthorizeRequest. So all you need to do would be matching the client id or some other identifiers you think you need to verify the client. Probably, you might want to add a Claim key-value pair to your client which you want to allow a few users.
Maybe something like this.
new InMemoryUser{Subject = "870805", Username = "damon", Password = "damon",
Claims = new Claim[]
{
new Claim(Constants.ClaimTypes.Name, "Damon Jeong"),
new Claim(Constants.ClaimTypes.Email, "dmjeong#email.com"),
new Claim(Constants.ClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean)
}
}
Assume you have above user, then add the subject id to the claim of a client like below.
new Client
{
ClientName = "WPF WebView Client Sample",
ClientId = "wpf.webview.client",
Flow = Flows.Implicit,
.
.
.
// Add claim for limiting this client to certain users.
// Since a claim only accepts type and value as string,
// You can add a list of subject id by comma separated values
// eg ( new Claim("BelongsToThisUser", "870805, 870806, 870807") )
Claims = new List<Claim>
{
new Claim("BelongsToThisUser", "870805")
}
},
And then just implement the ICustomRequestValidator and try to match the Claim value with the given user in its ValidateAuthorizeRequestAsync.
public class UserRequestLimitor : ICustomRequestValidator
{
public Task<AuthorizeRequestValidationResult> ValidateAuthorizeRequestAsync(ValidatedAuthorizeRequest request)
{
var clientClaim = request.Client.claims.Where(x => x.Type == "BelongsToThisUser").FirstOrDefault();
// Check is this client has "BelongsToThisUser" claim.
if(clientClaim != null)
{
var subClaim = request.Subject.Claims.Where(x => x.Type == "sub").FirstOrDefault() ?? new Claim(string.Empty, string.Empty);
if(clientClaim.Value == userClaim.Value)
{
return Task.FromResult<AuthorizeRequestValidationResult>(new AuthorizeRequestValidationResult
{
IsError = false
});
}
else
{
return Task.FromResult<AuthorizeRequestValidationResult>(new AuthorizeRequestValidationResult
{
ErrorDescription = "This client doesn't have an authorization to request a token for this user.",
IsError = true
});
}
}
// This client has no access controls over users.
else
{
return Task.FromResult<AuthorizeRequestValidationResult>(new AuthorizeRequestValidationResult
{
IsError = false
});
}
}
public Task<TokenRequestValidationResult> ValidateTokenRequestAsync(ValidatedTokenRequest request)
{
// your implementation
}
}
Time to DI
You need to inject your own dependency when you configure up your IdentityServer. The authorization server uses IdentityServerServiceFactory for registering dependencies.
var factory = new IdentityServerServiceFactory();
factory.Register(new Registration<ICustomRequestValidator>(resolver => new UserRequestLimitor()));
Then Autofac; the IoC container in IdentityServer will do the rest of the DI jobs for you.
In IdentityServer I've added a new scope like this:
new Scope
{
Name = "myscope",
Description = "myscope",
Type=ScopeType.Resource,
ShowInDiscoveryDocument= false,
Emphasize = false,
//AccessTokenType=1, //Reference
AccessTokenType=0, //JWT
Claims = new List<ScopeClaim>
{
new ScopeClaim("location"),
}
I've added a client:
new Client
{
ClientName = "myclient",
Enabled = true,
ClientId = "myclient",
Flow = Flows.Implicit,
AllowedScopes = new List<string> {"myscope"},
Claims = new List<Claim> {new Claim("location", "datacenter")}
}
I've added an implementation of GetProfileData :
public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
await base.GetProfileDataAsync(context);
if (context.AllClaimsRequested)
context.IssuedClaims = context.Subject.Claims;
else if (context.RequestedClaimTypes != null)
context.IssuedClaims = context.Subject.Claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
}
In my webapi, I'm using AccessTokenValidation:
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:5300",
AllowedScopes = { "myscope" },
RequireHttpsMetadata = false,
});
services.AddAuthorization(options =>
{
options.AddPolicy("location", policy => policy.RequireClaim("location"));
});
My controller is prefixed with:
[Authorize(ActiveAuthenticationSchemes = "Bearer", Policy = "location")]
public async Task<IActionResult> Get()
{
...
}
Now, when the accesstoken is set to JWT, this works fine, I'm able to call the endpoint. Now, if I change AccessTokenType to reference token, it fails...
If I inspect the RequestedClaimTypes during the call to the profiledata endpoint, it holds the claims for 'myscope' when using JWT, but not when using Reference Token...
Am I missing some configuration or is this the way it's supposed work?? I would have expected to get the same claims in both setup
Reference Tokens are not self-contained tokens like JWTs are. They provide an ID that can be used to fetch the information that the reference token represents from a backing store.
If you're using IdentityServer3 out of the box, you should be able to request your reference token from the POST /connect/token endpoint and follow that up with a request to the token introspection endpoint:
POST /connect/accesstokenvalidation
token={tokenReceivedFromPreviousRequest}
This will return the information for that reference token that is kept in its backing store, including scopes.
As a note, that introspection endpoint accepts both Reference Tokens and JWTs.
I have setup the Facebook API SDK for ColdFusion - https://github.com/affinitiz/facebook-cf-sdk
I've setup a login process which works successfully but after 10 minutes or so when I return and refresh the page, it shows the following error:
This authorization code has expired. [code=100]
Is there something I am missing with the FB login? Am I meant to be checking against something manually in order to persist the session?
Cheers
Shaun
<cfscript>
import facebook.sdk.FacebookApp;
import facebook.sdk.FacebookGraphAPI;
// Replace this with your appId and secret
APP_ID = "";
SECRET_KEY = "";
SCOPE = "publish_stream";
if (APP_ID is "" or SECRET_KEY is "") {
// App not configured
facebookGraphAPI = new FacebookGraphAPI();
} else {
// Create facebookApp instance
facebookApp = new FacebookApp(appId=APP_ID, secretKey=SECRET_KEY);
// See if there is a user from a cookie or session
userId = facebookApp.getUserId();
if (userId) {
try {
userAccessToken = facebookApp.getUserAccessToken();
facebookGraphAPI = new FacebookGraphAPI(accessToken=userAccessToken, appId=APP_ID);
userObject = facebookGraphAPI.getObject(id=userId);
userFriends = facebookGraphAPI.getConnections(id=userId, type='friends', limit=10);
authenticated = true;
} catch (any exception) {
// Usually an invalid session (OAuthInvalidTokenException), for example if the user logged out from facebook.com
// this is where the error occurs
userId = 0;
facebookGraphAPI = new FacebookGraphAPI();
}
} else {
facebookGraphAPI = new FacebookGraphAPI();
}
// Login or logout url will be needed depending on current user state.
if (userId) {
logoutUrl = facebookApp.getLogoutUrl();
} else {
parameters = {scope=SCOPE};
loginUrl = facebookApp.getLoginUrl(parameters);
}
}
Apparently you're not exchanging the OAuth code to an Access Token. See the docs here how to do that: Manually Build a Login Flow