How to extend life of JWT Token Issued from IdentityServer 3 - c#

I am trying to setup an IdentityServer 3 web application not hardware, this is a software development related question. I am trying to learn how to use the technology and produce JWT token's that my api can consume. The problem is I cannot for the life of me find where to set the token expiration. It always produces a 401 after about an hour. Ideally for testing purposes I would like to extend this to a very long time so I do not have to keep copy and pasting my JWT token into fiddler thus dramatically slowing down my development and learning process.
My Client
new Client
{
ClientId = "scheduling"
,ClientSecrets = new List<Secret>
{
new Secret("65A6A6C3-A764-41D9-9D10-FC09E0DBB046".Sha256())
},
ClientName = "Patient Scheduling",
Flow = Flows.ResourceOwner,
AllowedScopes = new List<string>
{
Constants.StandardScopes.OpenId,
Constants.StandardScopes.Profile,
Constants.StandardScopes.OfflineAccess,
"read",
"adprofile",
"scheduling"
},
Enabled = true
}
My Scope
new Scope
{
Name = "scheduling",
Claims = new List<ScopeClaim>
{
new ScopeClaim(Constants.ClaimTypes.Role,true),
new ScopeClaim("scheduling_id",true),
new ScopeClaim("expires_at",true) //I have tried "expires_in" and [Constants.ClaimTypes.Expiration] also with no luck
}
}
Method used for client specific claims:
private IEnumerable<Claim> GetClaimByClientId(string client_id)
{
List<Claim> claims = new List<Claim>();
switch(client_id.ToLower())
{
case "scheduling":
claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Role,"administrator"));
claims.Add(new Claim("scheduling_id", "2"));
//claims.Add(new Claim("expires_in", "2082758400")); //01/01/2036
//claims.Add(new Claim(Constants.ClaimTypes.Expiration, "2082758400")); //01/01/2036
claims.Add(new Claim("expires_at", "2082758400")); //01/01/2036
break;
default:
throw new Exception("Client not found with provided client id.");
}
return claims;
}
Code actually validating Credentials:
if (ActiveDirectoryHelper.ValidateCredentials(context.UserName, context.Password, adName))
{
List<Claim> lstClaims = new List<Claim>
{
new Claim("obj_id",user.UserID.ToUpper()),
new Claim(Constants.ClaimTypes.Email, string.IsNullOrEmpty(user.Email) ? string.Empty : user.Email.ToLower()),
new Claim(Constants.ClaimTypes.GivenName,user.FirstName),
new Claim(Constants.ClaimTypes.FamilyName,user.LastName),
new Claim("EmployeeNumber",user.EmployeeNumber),
};
lstClaims.AddRange(GetClaimByClientId("scheduling"));
context.AuthenticateResult = new AuthenticateResult(user.UserID,user.Username, lstClaims);
}
else
{
context.AuthenticateResult = new AuthenticateResult("Invalid Login.");
}

Access Token lifetime (I assume this is what you mean by JWT token) can be set for a client application using the Client property AccessTokenLifetime.
By default this is set to 3600 seconds (1 hour).

Related

Using Identity with token and cookie authentication

Im trying to setup Token authentication with cookie authentication on same time in my application.
I created a MVC project in asp.net core 2.0, with individual user accounts to auth. Setup roles to the users too.
If i follow this tutorial of Shawn Wildermuth Two-AuthorizationSchemes-in-ASP-NET-Core-2
Everything works fine to get the Token of the registered user. But if i use the Role attribute on authorize [Authorize(Roles="Admin")] im getting a 403 response.
I think that is because the Token is not receiving the Role on auth.
How to setup this? Is any way to pass the Roles on the Token process?
To generate the token he is using this piece of code:
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> GenerateToken([FromBody] LoginViewModel model) { if (ModelState.IsValid) {
var user = await _userManager.FindByEmailAsync(model.Email);
if (user != null)
{
var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (result.Succeeded)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Tokens:Issuer"],
_config["Tokens:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
} }
return BadRequest("Could not create token"); }
You guys have any idea?
Thanks
If you add the following using and code, that should help.
using System.Security.Claims;
...
var userRoles = await _userManager.GetRolesAsync(user);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
}.Union(userRoles.Select(m => new Claim(ClaimTypes.Role, m)));
You can see the Union that adds the roles in with the type of ClaimTypes.Role, this will enable them to be used in the AuthorizeAttribute
HTH

How to C# Core OAuth without external login panel

I'm making an API for Exact Online for a website with a form. The visitor will fill in his information and after that the visitor sends it. It need to be send to the Exact online account from my client. But before that I need a accesstoken. The problem is that I don't want to give the user the login page that Exact gives me. I'm searching already for days to find a way to skip the login or to enter the login information by backend (there is always 1 login, and that is the login from my client).
Now this authorization thing is something new for me. So far I know I can call my authorization settings from the startup with this:
HttpContext.Authentication.GetAuthenticateInfoAsync("ExactOnline");
But then I get that loginscreen that I don't want. The only thing that Exact is telling me to do:
Create an app registration that supports an automated connection wizard (your provisioning process).
Is there a way to send them the login information and the visitor doesn't see a loginpage.
In my Startup.cs
var s = new OAuthOptions{
AuthenticationScheme = "ExactOnline",
ClientId = "CLIENTID",
ClientSecret = "CLIENTSECRET",
CallbackPath = new PathString("/callback"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
AuthorizationEndpoint = new Uri(string.Format("{0}/api/oauth2/auth", "https://start.exactonline.nl")).ToString(),
TokenEndpoint = new Uri(string.Format("{0}/api/oauth2/token", "https://start.exactonline.nl")).ToString(),
//Scope = { "identity", "roles" },
Events = new OAuthEvents
{
OnCreatingTicket = context =>
{
context.Identity.AddClaim(new Claim("urn:token:exactonline", context.AccessToken));
return Task.FromResult(true);
}
}
};
app.UseOAuthAuthentication(s);
First i had this code, but that gives me a null exception when i put the identity in the claimprincipal, probably because my claimsprincipal is null and i don't know why.
HttpContext.Authentication.AuthenticateAsync("ExactOnline");
var identity = new ClaimsIdentity("ExactOnline",ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
identity.Label = "Authentication";
identity.AddClaim(new Claim(ClaimTypes.Name, "USERNAME?"));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "PASSWORD?"));
claimsPrincipal.AddIdentity(identity);
var test = HttpContext.Authentication.SignInAsync("ExactOnline", claimsPrincipal, new AuthenticationProperties() { IsPersistent = false }));
After that i tried following code, but that also didn't work. My code will continue, but the test variable will be filled with this message: The name 'InnerExceptionCount' does not exist in the current context.
var identity = new ClaimsIdentity("ExactOnline", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
identity.Label = "Authentication";
identity.AddClaim(new Claim("username", "USERNAME"));
identity.AddClaim(new Claim("password", "PASSWORD"));
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
var test = HttpContext.Authentication.SignInAsync("ExactOnline", claimsPrincipal, new AuthenticationProperties() { IsPersistent = false });
Someone know how to solve this problem?

How to get user id from IdentityServer in client app when including access token?

I have implemented an authentication service based on IdentityServer3 and a simple MVC client app and a Shopper API secured by the authentication service. I've implemented a IdentityServer custom UserService so that the authentication service authenticates against our existing user data store. My Shopper API expects a userid in the Shopper Get request. Currently the response from authentication service includes the identity token and the access token, but no user id. I tried adding a user_id claim in the AuthenticationResult from my custom UserService.AuthenticateLocalAsync method, but I'm not seeing it in my client app code.
UserService.AuthenticateLocalAsync looks like this:
try
{
var user = new shopper(_dbConnLib, context.UserName, context.Password);
var claims = new List<Claim> { new Claim("user_id", user.shopperid) };
context.AuthenticateResult = new AuthenticateResult(user.shopperid, user.MemberDetail.billToAddress.FirstName, claims);
}
catch(shopperInitFromException ex)
{
context.AuthenticateResult = null; // Indicates username/password failure
}
return Task.FromResult(0);
And my client app SecurityTokenValidated handler looks like this:
SecurityTokenValidated = async n =>
{
var nid = new ClaimsIdentity(
n.AuthenticationTicket.Identity.AuthenticationType,
Constants.ClaimTypes.GivenName,
Constants.ClaimTypes.Role);
var userInfoClient = new UserInfoClient(
new Uri(n.Options.Authority + "/connect/userinfo").ToString());
var userInfo = await userInfoClient.GetAsync(n.ProtocolMessage.AccessToken);
userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Type, ui.Value)));
nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
//nid.AddClaim(new Claim("user_id", n.ProtocolMessage.UserId));
nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));
n.AuthenticationTicket = new AuthenticationTicket(
nid,
n.AuthenticationTicket.Properties);
}
If I step through that in the debugger, userInfo.Claims always has a count of 0. How can I get back a claim with the unique identifier of the user? Or can I get it from the identity or access token? Or should I just pass the tokens to the Shopper API and let it determine the id from the tokens?
I think I may have the answer. So far, as far as I can tell, the claims I include in the AuthenticateResult constructor in my override of AuthenticateLocalAsync don't seem to go anywhere. But the claims I include in my override of GetProfileDataAsync appear in the token. My GetProfileDataAsync code, which appears to set the claims properly, looks like this:
public override Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var user = new shopper(_dbConnLib, context.Subject.FindFirst("sub").Value);
var claims = new List<Claim> { new Claim("sub", user.shopperid), new Claim("acr_level", "level 0"), new Claim("amr", "anonymous") };
context.IssuedClaims = claims;
return Task.FromResult(0);
}
My AuthenticateLocalAsync code that sets claims in the AuthenticateResult that I never see in my client app code looks like this:
public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
{
// TODO: Handle AddshopperToBasketException in UserService.AuthenticateLocalAsync
try
{
var user = new shopper(_dbConnLib, context.UserName, context.Password);
var claims = new List<Claim> { new Claim("acr_level", "level 0"), new Claim("amr", "anonymous") };
context.AuthenticateResult = new AuthenticateResult(user.shopperid, user.MemberDetail.billToAddress.FirstName, claims);
}
catch(shopperInitFromException ex)
{
context.AuthenticateResult = null; // Indicates username/password failure
}
return Task.FromResult(0);
}

How to use access token in identityserver4?

The scenario is my client's possibility to grab data about my users. There is the code for config server:
Startup.cs
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryIdentityResources(ApiConfiguration.GetIdentityResources()) .AddInMemoryApiResources(ApiConfiguration.GetAllResources())
.AddInMemoryClients(ApiConfiguration.GetAllClients())
.AddTestUsers(ApiConfiguration.GetUsers())
ApiConfiguration
public static IEnumerable<ApiResource> GetAllResources()
{
yield return new ApiResource
{
Name = "customAPI",
Description = "Custom API Access",
UserClaims = new List<string> { "role" },
ApiSecrets = new List<Secret> { new Secret("scopeSecret".Sha256()) },
Scopes = new List<Scope> {
new Scope("customAPI"),
}
};
}
public static IEnumerable<Client> GetAllClients()
{
yield return new Client
{
ClientId = "oauthClient",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = new List<Secret> {
new Secret("Password".Sha256())},
AllowedScopes = new List<string> { "customAPI" }
};
}
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
};
}
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "2",
Username = "bob",
Password = "psw",
Claims = new List<Claim> {
new Claim(ClaimTypes.Email, "1#1.com"),
new Claim(ClaimTypes.Role, "admin")
}
}
};
}
With this request:
POST /connect/token
Headers:
Content-Type: application/x-www-form-urlencoded
Body:
grant_type=client_credentials&scope=customAPI&client_id=oauthClient&client_secret=Password
the client got the access token. So my question is how can I use the token? What I need http-request to grab data about bob (test user)?
And there is another related question: how to config api to my client could access token for specific user only?
Looking at the configuration above, the client you have setup is using the ClientCredentials grant, this is an OAuth grant type. If you wish to add identity you should look to use an OpenID Connect grant type, this will provide you with identity and tokens specific to the user you authenticate as.
More information on using OpenID Connect with Identity Server can be found in the docs at http://docs.identityserver.io/en/release/quickstarts/3_interactive_login.html
If you work through the following quickstart tutorials, you will see it come together.
Setup and Overview
Protecting an API using Client Credentials
Protecting an API using Passwords
Adding User Authentication with OpenID Connect
Switching to Hybrid Flow and adding API Access back
(You can skip the one on External Authentication.)
https://identityserver4.readthedocs.io/en/release/quickstarts/0_overview.html

Generate token in controller

I'm using Owin and ASP.NET Identity to use OAuth tokens for securing my Web API methods. The token subsystem is set up as such:
var oauthOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/Token"),
Provider = new SimpleAuthorizationServerProvider(),
AccessTokenFormat = new TicketDataFormat(app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1")),
RefreshTokenFormat = new TicketDataFormat(app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Refresh_Token", "v1")),
AccessTokenProvider = new AuthenticationTokenProvider(),
RefreshTokenProvider = new AuthenticationTokenProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
app.UseOAuthAuthorizationServer(oauthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
It works great for requesting tokens based on username/password and then consuming those tokens. However, since the user is already authenticated when hitting the controller that renders the SPA, I would like to generate the token in my view and pass it on to the Javascript code, instead of having to log in again in the SPA.
So my question is: how do I manually generate my token so I can include it in my SPA view?
You can generate access token inside a controller by calling OAuthBearerOptions.AccessTokenFormat.Protect(ticket) and the code will look as the below:
private JObject GenerateLocalAccessTokenResponse(string userName)
{
var tokenExpiration = TimeSpan.FromDays(1);
ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, userName));
var props = new AuthenticationProperties()
{
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
};
var ticket = new AuthenticationTicket(identity, props);
var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
JObject tokenResponse = new JObject(
new JProperty("userName", userName),
new JProperty("access_token", accessToken),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
);
return tokenResponse;
}
And you need to declare you OAuthBearerOptions as static property in class Startup.cs
But if you are looking to implement silent refresh for access token without requesting the user to login again, then you should consider implementing refresh token grant, do not do it like the way you suggested. You can read my detailed blog post on how to generate refresh tokens in SPA built with AngularJS.
Hope this answers your question.

Categories