/// <summary> /// Generate Token from user information /// </summary> /// <param name="Id">User id</param> /// <param name="username">UserName</param> /// <returns>TokenResponse</returns> public TokenResponse GenerateUserToken(long Id, string username) { var now = DateTime.UtcNow; var claims = new Claim[] { new Claim("id", Id.ToString()), new Claim("name", username), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64) }; // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: this.options.Issuer, audience: this.options.Audience, claims: claims, notBefore: now, expires: now.Add(this.options.Expiration), signingCredentials: this.options.SigningCredentials ?? TokenProvider.DefaultSigningCredentials()); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return new TokenResponse { access_token = encodedJwt, expires_in = (ulong)this.options.Expiration.TotalSeconds }; }
private async Task GenerateToken(HttpContext context) { var username = context.Request.Form["username"]; var password = context.Request.Form["password"]; var identity = await GetIdentity(username, password); if (identity == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Invalid username or password."); return; } var now = DateTime.UtcNow; // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims. // You can add other claims here, if you want: var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64), new Claim(JwtRegisteredClaimNames.Email, "*****@*****.**", ClaimValueTypes.String) }; // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: _options.Issuer, audience: _options.Audience, claims: claims, notBefore: now, expires: now.Add(_options.Expiration), signingCredentials: _options.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, expires_in = (int) _options.Expiration.TotalSeconds }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {Formatting = Formatting.Indented})); }
//[Authorize(Policy = "RefreshTokenPolicy")] Should probably make this work public async Task<IActionResult> PostRefreshAccessToken() { var userName = User.FindFirst(ClaimTypes.NameIdentifier).Value; _logger.LogInformation("Fetching new access token for " + userName); var identity = await GetClaimsIdentity(userName); var claims = await GetClaims(userName); var claimsForAccessToken = claims.ToList(); claimsForAccessToken.Add(identity.FindFirst("role")); // Create the JWT security token and encode it. var jwtAccessToken = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claimsForAccessToken.ToArray(), notBefore: _jwtOptions.NotBefore, expires: DateTime.UtcNow.Add(_jwtOptions.ValidFor), signingCredentials: _jwtOptions.SigningCredentials); var encodedJwtAccess = new JwtSecurityTokenHandler().WriteToken(jwtAccessToken); // Serialize and return the response var response = new { access_token = encodedJwtAccess, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return new OkObjectResult(json); }
public MobileSecondHandChatHub(IChatHubCacheService chatHubCacheService, TokenAuthorizationOptions tokenAuthorizationOptions, IConversationService conversationService) { this.chatHubCacheService = chatHubCacheService; this.tokenAuthorizationOptions = tokenAuthorizationOptions; this.handler = new JwtSecurityTokenHandler(); this.conversationService = conversationService; }
private string GetToken(ClaimsIdentity identity, DateTime? expires) { var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken( issuer: tokenOptions.Issuer, audience: tokenOptions.Audience, signingCredentials: tokenOptions.SigningCredentials, subject: identity, expires: expires ); return handler.WriteToken(securityToken); }
private async Task<string> GetToken(string username, DateTime? expires) { var handler = new JwtSecurityTokenHandler(); var user = await _userManager.FindByNameAsync(username); var principal = await _signInManager.CreateUserPrincipalAsync(user); var claimsIdentity = new ClaimsIdentity(principal.Identity, principal.Claims); var securityToken = handler.CreateToken( issuer: _tokenOptions.Issuer, audience: _tokenOptions.Audience, signingCredentials: _tokenOptions.SigningCredentials, subject: claimsIdentity, expires: expires ); return handler.WriteToken(securityToken); }
private string GetToken(User user, DateTime? expires) { var handler = new JwtSecurityTokenHandler(); ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user.Email, "TokenAuth"), new[] { new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", user.Id.ToString()) }); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = _tokenOptions.Issuer, Audience = _tokenOptions.Audience, SigningCredentials = _tokenOptions.SigningCredentials, Subject = identity, Expires = expires }); return handler.WriteToken(securityToken); }
public long? ValidateToken(string accessToken) { var handler = new JwtSecurityTokenHandler(); if (!handler.CanValidateToken) return null; var signedCredentials = this.options.SigningCredentials ?? TokenProvider.DefaultSigningCredentials(); var validationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = this.options.Issuer, ValidateAudience = true, ValidAudience = this.options.Audience, ValidateLifetime = true, IssuerSigningKey = signedCredentials.Key }; long? result = null; try { SecurityToken validatedToken; var claimsPrincipal = handler.ValidateToken(accessToken, validationParameters, out validatedToken); foreach (var claim in claimsPrincipal.Claims) { if (claim.Type != "id") continue; long id; if (long.TryParse(claim.Value, out id)) result = id; break; } } catch(Exception e) { InColUn.Logger.Instance.Log(InColUn.LogLevel.Exception, string.Format("Token validation exception for: {0}", accessToken), e); } return result; }
public async Task <IActionResult> Login([FromBody] LoginVM model) { if (ModelState.IsValid) { // Retrieve user by email or username User currentUser = await userManager.FindByEmailAsync(model.EmailOrUsername) ?? await userManager.FindByNameAsync(model.EmailOrUsername); // If no user is found by email or username, just return unauthorized and give nothing away of existing user info if (currentUser == null) { return(Unauthorized("invalid")); } // Log the user in by password var result = await signInManager.PasswordSignInAsync(currentUser, model.Password, model.RememberMe, lockoutOnFailure : true); if (result.Succeeded) { logger.LogInformation("User " + currentUser.Id + " logged in."); // Retrieve roles of user currentUser.Roles = (List <string>) await userManager.GetRolesAsync(currentUser); // Set claims of user List <Claim> claims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.NameId, currentUser.Id.ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, currentUser.UserName), new Claim(JwtRegisteredClaimNames.Email, currentUser.Email), new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture)) }; if (!string.IsNullOrEmpty(currentUser.FirstName)) { claims.Add(new Claim(JwtRegisteredClaimNames.GivenName, currentUser.FirstName)); } if (!string.IsNullOrEmpty(currentUser.LastName)) { claims.Add(new Claim(JwtRegisteredClaimNames.FamilyName, currentUser.LastName)); } // Add roles as claims foreach (var role in currentUser.Roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } // Retrieve player if player type user if (currentUser.PlayerId != null) { currentUser.Player = await playerRepository.GetByIdAsync((Guid)currentUser.PlayerId); } // Authentication successful => Generate jwt token // TODO: This code could be moved to another layer var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(configuration.GetSection("Authentication").GetValue <string>("Secret")); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddMinutes(double.Parse(configuration.GetSection("Authentication").GetValue <string>("TokenExpiresInMinutes"))), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; // Return user with token return(Ok(new AuthenticatedVM() { User = mapper.Map <User, UserVM>(currentUser), Token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)), RememberMe = model.RememberMe })); } //if (result.RequiresTwoFactor) //{ // logger.LogInformation("Requires two factor."); // return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }); //} if (result.IsLockedOut) { // INFO: This is possible to split some code //return RedirectToAction(nameof(Lockout)); logger.LogWarning("User is locked out."); return(Unauthorized("locked-out")); } if (result.IsNotAllowed) { logger.LogWarning("User is not allowed to login."); return(Unauthorized("not-allowed")); } else { logger.LogWarning("Invalid login attempt."); return(Unauthorized("invalid")); } } // If we got this far, something failed return(BadRequest()); }
public PortalJwtSecurityTokenHandler() { _tokenHandler = new JwtSecurityTokenHandler(); }
private RequestParametersList PopulateResultsConsumer(Uri requestUri, List <SpineList> providerSpineMessages, List <OrganisationList> providerOrganisationDetails, int spineMessageTypeId, SpineList consumerSpineMessage, SpineMessageType spineMessageType, string userGuid, JwtSecurityTokenHandler tokenHandler, string consumerOrganisationType = "") { var tokenIssuer = _spineOptionsDelegate.CurrentValue.SpineFqdn; var tokenAudience = providerSpineMessages.FirstOrDefault()?.Spine?.EndpointAddress; var tokenIssuedAt = DateTimeOffset.Now; var tokenExpiration = DateTimeOffset.Now.AddMinutes(5); var tokenDescriptor = BuildSecurityTokenDescriptor(tokenIssuer, tokenAudience, userGuid, tokenIssuedAt, tokenExpiration); AddRequestingDeviceClaim(requestUri, tokenDescriptor); AddRequestingOrganisationClaim(providerOrganisationDetails.FirstOrDefault()?.Organisation, tokenDescriptor); AddRequestingPractitionerClaim(requestUri, tokenDescriptor, userGuid); var token = AddTokenHeader(tokenHandler, tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); var requestParameters = new RequestParameters { BearerToken = tokenString, SspFrom = _spineOptionsDelegate.CurrentValue.AsId, SspTo = providerSpineMessages.FirstOrDefault()?.Spine?.AsId, UseSSP = _spineOptionsDelegate.CurrentValue.UseSSP, SspHostname = _spineOptionsDelegate.CurrentValue.SspHostname, ProviderODSCode = providerSpineMessages.FirstOrDefault()?.OdsCode, ConsumerODSCode = consumerSpineMessage?.OdsCode, InteractionId = spineMessageType?.InteractionId, SpineMessageTypeId = spineMessageTypeId, GPConnectConsumerOrganisationType = consumerOrganisationType, EndpointAddress = providerSpineMessages.FirstOrDefault()?.Spine?.EndpointAddress }; return(new RequestParametersList { RequestParameters = requestParameters, OdsCode = consumerSpineMessage.OdsCode }); }
public void ConfigureServices(IServiceCollection services) { // Mette i nomi degli scope in modo compatto JwtSecurityTokenHandler.DefaultMapInboundClaims = false; services.AddControllersWithViews(); services.AddAuthentication(options => { options.DefaultScheme = "cookie"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("cookie", options => { options.Cookie.Name = "CorsoMvc"; options.Events.OnSigningOut = async e => { await e.HttpContext.RevokeUserRefreshTokenAsync(); }; }) .AddOpenIdConnect("oidc", options => { options.Authority = IdentityUrl; options.RequireHttpsMetadata = true; options.ClientId = "client-hybrid-mvc"; options.ClientSecret = "2C59A271-87C0-4B7D-8583-9B7CA7954E6F"; // code flow + PKCE (PKCE is turned on by default) options.ResponseType = "code id_token"; options.UsePkce = false; options.Scope.Clear(); options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("email"); options.Scope.Add("offline_access"); options.Scope.Add("webdemo"); options.Scope.Add("webapi"); // Capire come prendere la sezione scope jwt // not mapped by default //options.ClaimActions.MapJsonKey(System.Security.Claims.ClaimTypes.Email, "email"); //options.ClaimActions.MapJsonKey("permessi", "scope"); //options.ClaimActions.MapJsonKey("scope", "scope", "webdemo"); // keeps id_token smaller options.GetClaimsFromUserInfoEndpoint = true; options.SaveTokens = true; options.ClaimActions.DeleteClaim("s_hash"); options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role", RoleClaimTypeRetriever = (token, s) => s, }; options.Events = new OpenIdConnectEvents { OnUserInformationReceived = context => { string rawAccessToken = context.ProtocolMessage.AccessToken; string rawIdToken = context.ProtocolMessage.IdToken; var handler = new JwtSecurityTokenHandler(); var accessToken = handler.ReadJwtToken(rawAccessToken); var idToken = handler.ReadJwtToken(rawIdToken); // do something with the JWTs return Task.CompletedTask; } }; }); // adds global authorization policy to require authenticated users services.AddAuthorization(options => { options.FallbackPolicy = options.DefaultPolicy; }); // adds user and client access token management services.AddAccessTokenManagement(options => { // client config is inferred from OpenID Connect settings // if you want to specify scopes explicitly, do it here, otherwise the scope parameter will not be sent options.Client.Scope = "webapi"; }) .ConfigureBackchannelHttpClient() .AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3) })); }
public override void Verify() { // Verify that attStmt is valid CBOR conforming to the syntax defined above and perform // CBOR decoding on it to extract the contained fields if ((CBORType.TextString != attStmt["ver"].Type) || (0 == attStmt["ver"].AsString().Length)) { throw new Fido2VerificationException("Invalid version in SafetyNet data"); } // Verify that response is a valid SafetyNet response of version ver var ver = attStmt["ver"].AsString(); if ((CBORType.ByteString != attStmt["response"].Type) || (0 == attStmt["response"].GetByteString().Length)) { throw new Fido2VerificationException("Invalid response in SafetyNet data"); } var response = attStmt["response"].GetByteString(); var responseJWT = Encoding.UTF8.GetString(response); if (string.IsNullOrWhiteSpace(responseJWT)) { throw new Fido2VerificationException("SafetyNet response null or whitespace"); } var jwtParts = responseJWT.Split('.'); if (jwtParts.Length != 3) { throw new Fido2VerificationException("SafetyNet response JWT does not have the 3 expected components"); } var jwtHeaderString = jwtParts.First(); var jwtHeaderJSON = JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(jwtHeaderString))); var x5cArray = jwtHeaderJSON["x5c"] as JArray; if (x5cArray == null) { throw new Fido2VerificationException("SafetyNet response JWT header missing x5c"); } var x5cStrings = x5cArray.Values <string>().ToList(); if (x5cStrings.Count == 0) { throw new Fido2VerificationException("No keys were present in the TOC header in SafetyNet response JWT"); } var certs = new List <X509Certificate2>(); var keys = new List <SecurityKey>(); foreach (var certString in x5cStrings) { var cert = GetX509Certificate(certString); certs.Add(cert); var ecdsaPublicKey = cert.GetECDsaPublicKey(); if (ecdsaPublicKey != null) { keys.Add(new ECDsaSecurityKey(ecdsaPublicKey)); } var rsaPublicKey = cert.GetRSAPublicKey(); if (rsaPublicKey != null) { keys.Add(new RsaSecurityKey(rsaPublicKey)); } } var validationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, ValidateIssuerSigningKey = true, IssuerSigningKeys = keys }; var tokenHandler = new JwtSecurityTokenHandler(); SecurityToken validatedToken = null; try { tokenHandler.ValidateToken( responseJWT, validationParameters, out validatedToken); } catch (SecurityTokenException ex) { throw new Fido2VerificationException("SafetyNet response security token validation failed", ex); } var nonce = ""; bool?ctsProfileMatch = null; var timestampMs = DateTimeHelper.UnixEpoch; var jwtToken = validatedToken as JwtSecurityToken; foreach (var claim in jwtToken.Claims) { if (("nonce" == claim.Type) && ("http://www.w3.org/2001/XMLSchema#string" == claim.ValueType) && (0 != claim.Value.Length)) { nonce = claim.Value; } if (("ctsProfileMatch" == claim.Type) && ("http://www.w3.org/2001/XMLSchema#boolean" == claim.ValueType)) { ctsProfileMatch = bool.Parse(claim.Value); } if (("timestampMs" == claim.Type) && ("http://www.w3.org/2001/XMLSchema#integer64" == claim.ValueType)) { timestampMs = DateTimeHelper.UnixEpoch.AddMilliseconds(double.Parse(claim.Value)); } } var notAfter = DateTime.UtcNow.AddMilliseconds(_driftTolerance); var notBefore = DateTime.UtcNow.AddMinutes(-1).AddMilliseconds(-(_driftTolerance)); if ((notAfter < timestampMs) || ((notBefore) > timestampMs)) { throw new Fido2VerificationException(string.Format("SafetyNet timestampMs must be present and between one minute ago and now, got: {0}", timestampMs.ToString())); } // Verify that the nonce in the response is identical to the SHA-256 hash of the concatenation of authenticatorData and clientDataHash if ("" == nonce) { throw new Fido2VerificationException("Nonce value not found in SafetyNet attestation"); } byte[] nonceHash = null; try { nonceHash = Convert.FromBase64String(nonce); } catch (Exception ex) { throw new Fido2VerificationException("Nonce value not base64string in SafetyNet attestation", ex); } using (var hasher = CryptoUtils.GetHasher(HashAlgorithmName.SHA256)) { var dataHash = hasher.ComputeHash(Data); if (false == dataHash.SequenceEqual(nonceHash)) { throw new Fido2VerificationException( string.Format( "SafetyNet response nonce / hash value mismatch, nonce {0}, hash {1}", BitConverter.ToString(nonceHash).Replace("-", ""), BitConverter.ToString(dataHash).Replace("-", "") ) ); } } // Verify that the attestation certificate is issued to the hostname "attest.android.com" var subject = certs[0].GetNameInfo(X509NameType.DnsName, false); if (false == ("attest.android.com").Equals(subject)) { throw new Fido2VerificationException(string.Format("SafetyNet attestation cert DnsName invalid, want {0}, got {1}", "attest.android.com", subject)); } if (null == ctsProfileMatch) { throw new Fido2VerificationException("SafetyNet response ctsProfileMatch missing"); } // Verify that the ctsProfileMatch attribute in the payload of response is true if (true != ctsProfileMatch) { throw new Fido2VerificationException("SafetyNet response ctsProfileMatch false"); } }
/// <summary> /// ConfigureJwtAuthorizationFlowByKey which performs JWT authentication using the private key. /// </summary> /// <param name="clientId"></param> /// <param name="userId"></param> /// <param name="oauthBasePath"></param> /// <param name="privateKey"></param> /// <param name="expiresInHours"></param> /// <param name="scopes"></param> /// <returns>If Successful, returns the OAuthToken object model which consist of an access token and expiration time.</returns> public OAuth.OAuthToken ConfigureJwtAuthorizationFlowByKey(string clientId, string userId, string oauthBasePath, string privateKey, int expiresInHours, List <string> scopes = null) { JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor() { Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(expiresInHours)), }; if (scopes == null) { scopes = new List <string> { OAuth.Scope_SIGNATURE }; } descriptor.Subject = new ClaimsIdentity(); descriptor.Subject.AddClaim(new Claim("scope", String.Join(" ", scopes))); descriptor.Subject.AddClaim(new Claim("aud", oauthBasePath)); descriptor.Subject.AddClaim(new Claim("iss", clientId)); if (!string.IsNullOrEmpty(userId)) { descriptor.Subject.AddClaim(new Claim("sub", userId)); } if (!string.IsNullOrEmpty(privateKey)) { var rsa = CreateRSAKeyFromPem(privateKey); RsaSecurityKey rsaKey = new RsaSecurityKey(rsa); descriptor.SigningCredentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.HmacSha256Signature); } else { throw new ApiException(400, "Private key not supplied or is invalid!"); } var token = handler.CreateToken(descriptor); string jwtToken = handler.WriteToken(token); Uri baseUrl = this.RestClient.BaseUrl; this.RestClient.BaseUrl = new Uri(string.Format("https://{0}", oauthBasePath)); string path = "oauth/token"; string contentType = "application/x-www-form-urlencoded"; Dictionary <string, string> formParams = new Dictionary <string, string>(); formParams.Add("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"); formParams.Add("assertion", jwtToken); Dictionary <string, string> queryParams = new Dictionary <string, string>(); Dictionary <string, string> headerParams = new Dictionary <string, string>(); headerParams.Add("Content-Type", "application/x-www-form-urlencoded"); Dictionary <string, FileParameter> fileParams = new Dictionary <string, FileParameter>(); Dictionary <string, string> pathParams = new Dictionary <string, string>(); object postBody = null; try { var response = CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType); OAuth.OAuthToken tokenInfo = JsonConvert.DeserializeObject <OAuth.OAuthToken>(((RestResponse)response).Content); var config = Configuration.Default; config.AddDefaultHeader("Authorization", string.Format("{0} {1}", tokenInfo.token_type, tokenInfo.access_token)); this.RestClient.BaseUrl = baseUrl; return(tokenInfo); } catch (Exception ex) { throw new Exception(ex.Message); } }
public TokenJWT(String UserId, String UniqueKey) { this.tokenHandler = new JwtSecurityTokenHandler(); this.UserId = UserId; this.UniqueKey = UniqueKey; }
/// <summary> /// DeserializeAndValidateBlob method implementation /// </summary> protected async Task <MetadataBLOBPayload> DeserializeAndValidateBlob(string rawBLOBJwt) { if (string.IsNullOrWhiteSpace(rawBLOBJwt)) { throw new ArgumentNullException(nameof(rawBLOBJwt)); } var jwtParts = rawBLOBJwt.Split('.'); if (jwtParts.Length != 3) { throw new ArgumentException("The JWT does not have the 3 expected components"); } var blobHeader = jwtParts.First(); var tokenHeader = JObject.Parse(System.Text.Encoding.UTF8.GetString(Base64Url.Decode(blobHeader))); var blobAlg = tokenHeader["alg"]?.Value <string>(); if (blobAlg == null) { throw new ArgumentNullException("No alg value was present in the BLOB header."); } var x5cArray = tokenHeader["x5c"] as JArray; if (x5cArray == null) { throw new ArgumentException("No x5c array was present in the BLOB header."); } var rootCert = GetX509Certificate(ROOT_CERT); var blobCertStrings = x5cArray.Values <string>().ToList(); var blobCertificates = new List <X509Certificate2>(); var blobPublicKeys = new List <SecurityKey>(); foreach (var certString in blobCertStrings) { var cert = GetX509Certificate(certString); blobCertificates.Add(cert); var ecdsaPublicKey = cert.GetECDsaPublicKey(); if (ecdsaPublicKey != null) { blobPublicKeys.Add(new ECDsaSecurityKey(ecdsaPublicKey)); } var rsa = cert.GetRSAPublicKey(); if (rsa != null) { blobPublicKeys.Add(new RsaSecurityKey(rsa)); } } var certChain = new X509Chain(); certChain.ChainPolicy.ExtraStore.Add(rootCert); certChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; var validationParameters = new TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, ValidateIssuerSigningKey = true, IssuerSigningKeys = blobPublicKeys, }; var tokenHandler = new JwtSecurityTokenHandler() { // 250k isn't enough bytes for conformance test tool // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1097 MaximumTokenSizeInBytes = rawBLOBJwt.Length }; tokenHandler.ValidateToken( rawBLOBJwt, validationParameters, out var validatedToken); if (blobCertificates.Count > 1) { certChain.ChainPolicy.ExtraStore.AddRange(blobCertificates.Skip(1).ToArray()); } var certChainIsValid = certChain.Build(blobCertificates.First()); // if the root is trusted in the context we are running in, valid should be true here if (!certChainIsValid) { foreach (var element in certChain.ChainElements) { if (element.Certificate.Issuer != element.Certificate.Subject) { var cdp = CryptoUtils.CDPFromCertificateExts(element.Certificate.Extensions); var crlFile = await DownloadDataAsync(cdp); if (true == CryptoUtils.IsCertInCRL(crlFile, element.Certificate)) { throw new VerificationException(string.Format("Cert {0} found in CRL {1}", element.Certificate.Subject, cdp)); } } } // otherwise we have to manually validate that the root in the chain we are testing is the root we downloaded if (rootCert.Thumbprint == certChain.ChainElements[certChain.ChainElements.Count - 1].Certificate.Thumbprint && // and that the number of elements in the chain accounts for what was in x5c plus the root we added certChain.ChainElements.Count == (blobCertStrings.Count + 1) && // and that the root cert has exactly one status listed against it certChain.ChainElements[certChain.ChainElements.Count - 1].ChainElementStatus.Length == 1 && // and that that status is a status of exactly UntrustedRoot certChain.ChainElements[certChain.ChainElements.Count - 1].ChainElementStatus[0].Status == X509ChainStatusFlags.UntrustedRoot) { // if we are good so far, that is a good sign certChainIsValid = true; for (var i = 0; i < certChain.ChainElements.Count - 1; i++) { // check each non-root cert to verify zero status listed against it, otherwise, invalidate chain if (0 != certChain.ChainElements[i].ChainElementStatus.Length) { certChainIsValid = false; } } } } if (!certChainIsValid) { throw new VerificationException("Failed to validate cert chain while parsing BLOB"); } var blobPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson(); var blob = Newtonsoft.Json.JsonConvert.DeserializeObject <MetadataBLOBPayload>(blobPayload); blob.JwtAlg = blobAlg; return(blob); }
public async Task <bool> Authenticate(String jwtToken) { try { // No use if token is empty if (string.IsNullOrWhiteSpace(jwtToken)) { return(false); } await LogoutAsync(); // Setup handler for processing Jwt token var tokenHandler = new JwtSecurityTokenHandler(); var settings = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = _config["Jwt:Issuer"], ValidAudience = _config["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])) }; // Retrieve principal from Jwt token var principal = tokenHandler.ValidateToken(jwtToken, settings, out var validatedToken); // Cast needed for accessing claims property var identity = principal.Identity as ClaimsIdentity; // parse jwt token to get all claims var securityToken = tokenHandler.ReadToken(jwtToken) as JwtSecurityToken; // Search for missed claims, for example claim 'sub' var extraClaims = securityToken.Claims.Where(c => !identity.Claims.Any(x => x.Type == c.Type)).ToList(); // Adding the original Jwt has 2 benefits: // 1) Authenticate REST service calls with orginal Jwt // 2) The original Jwt is available for renewing during sliding expiration extraClaims.Add(new Claim("jwt", jwtToken)); // Merge claims identity.AddClaims(extraClaims); // Setup authenticaties // ExpiresUtc is used in sliding expiration var authenticationProperties = new AuthenticationProperties() { //IssuedUtc = identity.Claims.First(c => c.Type == JwtRegisteredClaimNames.Iat)?.Value.ToInt64().ToUnixEpochDate(), //ExpiresUtc = identity.Claims.First(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value.First()..ToInt64().ToUnixEpochDate(), ExpiresUtc = DateTime.Now.AddMinutes(15), IsPersistent = true }; // The actual Login await _httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authenticationProperties); return(identity.IsAuthenticated); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(false); }
private string ReadJSONWebToken(string jwtToken) { var token = new JwtSecurityTokenHandler().ReadJwtToken(jwtToken); return(token.Payload["sessionId"] as string ?? string.Empty); }
/// <summary> /// Acquires the security token from the authority. /// </summary> /// <param name="context">Context to be used when requesting a security token.</param> /// <param name="debugAction">The action to write debug statements.</param> /// <param name="promptAction">The action to prompt the user for input.</param> /// <returns>The result from the authentication request.</returns> public AuthenticationToken Authenticate(PartnerContext context, Action <string> debugAction, Action <string> promptAction = null) { AuthenticationContext authContext; AuthenticationResult authResult; Claim claim; DateTimeOffset expiration; JwtSecurityToken token; JwtSecurityTokenHandler tokenHandler; PartnerEnvironment environment; environment = PartnerEnvironment.PublicEnvironments[context.Environment]; authContext = new AuthenticationContext( $"{environment.ActiveDirectoryAuthority}{context.Account.Properties[AzureAccountPropertyType.Tenant]}"); if (context.Account.Type == AccountType.AccessToken) { tokenHandler = new JwtSecurityTokenHandler(); token = tokenHandler.ReadJwtToken(context.Account.Properties[AzureAccountPropertyType.AccessToken]); claim = token.Claims.SingleOrDefault(c => c.Type.Equals("oid", StringComparison.InvariantCultureIgnoreCase)); context.Account.Properties[AzureAccountPropertyType.UserIdentifier] = claim?.Value; claim = token.Claims.SingleOrDefault(c => c.Type.Equals("tid", StringComparison.InvariantCultureIgnoreCase)); context.Account.Properties[AzureAccountPropertyType.Tenant] = claim?.Value; claim = token.Claims.SingleOrDefault(c => c.Type.Equals("exp", StringComparison.InvariantCultureIgnoreCase)); expiration = DateTimeOffset.FromUnixTimeSeconds(Convert.ToInt64(claim.Value, CultureInfo.InvariantCulture)); claim = token.Claims.SingleOrDefault(c => c.Type.Equals("unique_name", StringComparison.InvariantCultureIgnoreCase)); context.AuthenticationType = claim == null ? AuthenticationTypes.AppOnly : AuthenticationTypes.AppPlusUser; debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateAccessTokenTrace, expiration.ToString(CultureInfo.CurrentCulture), context.Account.Properties[AzureAccountPropertyType.Tenant], context.Account.Properties[AzureAccountPropertyType.UserIdentifier], claim?.Value)); return(new AuthenticationToken( context.Account.Properties[AzureAccountPropertyType.AccessToken], expiration)); } else if (context.Account.Type == AccountType.ServicePrincipal) { debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateServicePrincipalTrace, environment.ActiveDirectoryAuthority, context.Account.Id, environment.AzureAdGraphEndpoint, context.Account.Properties[AzureAccountPropertyType.Tenant])); authResult = authContext.AcquireTokenAsync( environment.AzureAdGraphEndpoint, new ClientCredential( context.Account.Id, context.Account.Properties[AzureAccountPropertyType.ServicePrincipalSecret])).ConfigureAwait(false).GetAwaiter().GetResult(); context.AuthenticationType = Authentication.AuthenticationTypes.AppOnly; } else if (!context.Account.Properties.ContainsKey(AzureAccountPropertyType.UserIdentifier)) { #if NETSTANDARD debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateDeviceCodeTrace, context.ApplicationId, environment.PartnerCenterEndpoint)); DeviceCodeResult deviceCodeResult = authContext.AcquireDeviceCodeAsync( environment.PartnerCenterEndpoint, context.ApplicationId).ConfigureAwait(false).GetAwaiter().GetResult(); promptAction(deviceCodeResult.Message); authResult = authContext.AcquireTokenByDeviceCodeAsync(deviceCodeResult).ConfigureAwait(false).GetAwaiter().GetResult(); #else debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateAuthorizationCodeTrace, context.ApplicationId, environment.ActiveDirectoryAuthority, AuthenticationConstants.RedirectUriValue, environment.PartnerCenterEndpoint)); authResult = authContext.AcquireTokenAsync( environment.PartnerCenterEndpoint, context.ApplicationId, new Uri(AuthenticationConstants.RedirectUriValue), new PlatformParameters(PromptBehavior.Always), UserIdentifier.AnyUser).ConfigureAwait(false).GetAwaiter().GetResult(); #endif context.Account.Id = authResult.UserInfo.DisplayableId; context.Account.Properties[AzureAccountPropertyType.Tenant] = authResult.TenantId; context.Account.Properties[AzureAccountPropertyType.UserIdentifier] = authResult.UserInfo.UniqueId; context.AuthenticationType = Authentication.AuthenticationTypes.AppPlusUser; } else { debugAction( string.Format( CultureInfo.CurrentCulture, Resources.AuthenticateSilentTrace, context.ApplicationId, environment.ActiveDirectoryAuthority, environment.PartnerCenterEndpoint, context.Account.Id)); authResult = authContext.AcquireTokenSilentAsync( environment.PartnerCenterEndpoint, context.ApplicationId, new UserIdentifier(context.Account.Id, UserIdentifierType.RequiredDisplayableId)).ConfigureAwait(false).GetAwaiter().GetResult(); context.Account.Id = authResult.UserInfo.DisplayableId; context.Account.Properties[AzureAccountPropertyType.Tenant] = authResult.TenantId; context.Account.Properties[AzureAccountPropertyType.UserIdentifier] = authResult.UserInfo.UniqueId; context.AuthenticationType = Authentication.AuthenticationTypes.AppPlusUser; } return(new AuthenticationToken(authResult.AccessToken, authResult.ExpiresOn)); }
public ActionResult <LoginModel> LoginPost(decimal CPF, string Pass, #pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) #pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) { User user = _context.User.Where(x => x.CPF.Equals(CPF)).FirstOrDefault(); LoginModel loginModel = new LoginModel(); if (user == null) { return(NotFound("User not found with this CPF!")); } try { var passCript = HashMd5Generator.Generate(Pass); if (user.Password != passCript) { return(BadRequest("Passoword is invalid!")); } bool validCredentials = false; validCredentials = (user != null); if (validCredentials) { ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(user.CPF.ToString(), "Login"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), new Claim(JwtRegisteredClaimNames.UniqueName, user.CPF.ToString()) } ); DateTime creationDate = DateTime.Now; DateTime expirationDate = creationDate + TimeSpan.FromSeconds(tokenConfigurations.Seconds); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = tokenConfigurations.Issuer, Audience = tokenConfigurations.Audience, SigningCredentials = signingConfigurations.SigningCredentials, Subject = identity, NotBefore = creationDate, Expires = expirationDate }); var token = handler.WriteToken(securityToken); loginModel.authenticated = true; loginModel.created = creationDate.ToString("yyyy-MM-dd HH:mm:ss"); loginModel.expiration = expirationDate.ToString("yyyy-MM-dd HH:mm:ss"); loginModel.accessToken = token; loginModel.message = "OK"; return(Ok(loginModel)); } else { loginModel.authenticated = false; loginModel.message = "Failed to authenticate!"; return(BadRequest(loginModel)); } } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
/// <summary> /// This method generating JWT token /// </summary> /// <param name="context"></param> /// <returns></returns> private async Task GenerateToken(HttpContext context) { try { var username = context.Request.Form["username"]; var password = context.Request.Form["password"]; #region additional values for data migration //var modal = context.Request.Form["modal"]; //var version = context.Request.Form["version"]; //var apiVersion = context.Request.Form["apiVersion"]; #endregion string role = string.Empty; string userId = string.Empty; var identity = await _options.IdentityResolver(username, password); if (identity == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Invalid username or password."); return; } var users = await _userService.GeteUserByUsername(username); if (users != null) { role = users.Role; userId = users.UserId; } var now = DateTime.UtcNow; // Specifically add the jti (nonce), iat (issued timestamp), and sub (subject/user) claims. // You can add other claims here, if you want: var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(JwtRegisteredClaimNames.Jti, await _options.NonceGenerator()) , new Claim(ClaimTypes.Role, role.ToString()) , new Claim(ClaimTypes.Name, username.ToString()) }; // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: _options.Issuer, audience: _options.Audience, claims: claims, notBefore: now, expires: now.Add(_options.Expiration), signingCredentials: _options.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, expires_in = (int)_options.Expiration.TotalSeconds, username = claims[0].Value, userId = userId, issued = now, expires = _options.Expiration }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings)); } catch (Exception ex) { throw ex; } }
public async Task<IActionResult> Post(string userName, string password, bool rememberMe) { //todo: Ensure that these input values are not logged. var identity = await GetClaimsIdentity(userName, password, rememberMe); if (identity == null) { _logger.LogInformation($"Invalid username ({userName}))"); return BadRequest("Invalid credentials"); } var claims = await GetClaims(userName); var claimsForAccessToken = claims.ToList(); claimsForAccessToken.Add(identity.FindFirst("role")); var claimsForRefreshToken = claims.ToList(); claimsForRefreshToken.Add(new Claim("RefreshToken", "RefreshToken")); // Create the JWT security token and encode it. var jwtAccessToken = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claimsForAccessToken.ToArray(), notBefore: _jwtOptions.NotBefore, expires: DateTime.UtcNow.Add(_jwtOptions.ValidFor), signingCredentials: _jwtOptions.SigningCredentials); var jwtRefreshToken = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claimsForRefreshToken.ToArray(), notBefore: _jwtOptions.NotBefore, expires: DateTime.UtcNow.AddMonths(3), signingCredentials: _jwtOptions.SigningCredentials); var encodedJwtAccess = new JwtSecurityTokenHandler().WriteToken(jwtAccessToken); var encodedJwtRefresh = new JwtSecurityTokenHandler().WriteToken(jwtRefreshToken); //todo: Save refresh-token i database. So that it can be revoked. // Serialize and return the response var response = new { access_token = encodedJwtAccess, refresh_token = encodedJwtRefresh, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return new OkObjectResult(json); }
public async Task <IActionResult> Login([FromForm] LoginViewModel user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } User _userDb = _userRepository.GetSingle(u => u.UserName == user.UserName, u => u.Roles); if (_userDb == null) { _logger.LogInformation($"Nombre de usuario ({user.UserName}) o contraseña ({user.Password}) inválidos"); return(NotFound()); } string passwordHashed = Extensions.EncryptPassword(user.Password, _userDb.Salt); if (_userDb.PasswordHash != passwordHashed) { _logger.LogInformation("La contraseña proporcionada es incorrecta"); return(BadRequest("Credenciales inválidas")); } Role _roleDb = null; foreach (var role in _userDb.Roles) { _roleDb = _roleRepository.GetSingle(r => r.Id == role.RoleId); } if (_roleDb == null) { _logger.LogInformation($"El usuario ({user.UserName}) no tiene un rol asignado"); return(BadRequest("Credenciales inválidas")); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, (_userDb.Id).ToString()), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), new Claim(ClaimTypes.Role, _roleDb.Name), new Claim(ClaimTypes.Name, _userDb.UserName) }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); // Serialize and return the response var response = new { access_token = encodedJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); }
public AccessTokenGenerator() { _jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); }
public IActionResult Login([FromBody] LoginQuery user) { if (user == null) { return(BadRequest("Invalid client request")); } var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var claims = new List <Claim>(); var tokeOptions = new JwtSecurityToken( issuer: "http://localhost:4200", audience: "https://localhost:44361", claims: claims, expires: DateTime.Now.AddMinutes(5), signingCredentials: signinCredentials ); var tokenString = ""; LoginResult loginResult = new LoginResult(); if (user.UserName == "superman" && user.Password == "superman") { claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, "Editor"), new Claim(ClaimTypes.Role, "Manager") }; tokeOptions = new JwtSecurityToken( issuer: "http://localhost:4200", audience: "https://localhost:44361", claims: claims, expires: DateTime.Now.AddMinutes(5), signingCredentials: signinCredentials ); tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); loginResult = new LoginResult { Success = true, ErrorMessage = null, Token = tokenString, Permissions = GetPermissionsFromClaims(claims) }; return(Ok(loginResult)); } if (user.UserName == "editor" && user.Password == "editor") { claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, "Editor") }; tokeOptions = new JwtSecurityToken( issuer: "http://localhost:4200", audience: "https://localhost:44361", claims: claims, expires: DateTime.Now.AddMinutes(5), signingCredentials: signinCredentials ); tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); loginResult = new LoginResult { Success = true, ErrorMessage = null, Token = tokenString, Permissions = GetPermissionsFromClaims(claims) }; return(Ok(loginResult)); } if (user.UserName == "manager" && user.Password == "manager") { claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Role, "Manager") }; tokeOptions = new JwtSecurityToken( issuer: "http://localhost:4200", audience: "https://localhost:44361", claims: claims, expires: DateTime.Now.AddMinutes(5), signingCredentials: signinCredentials ); tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); loginResult = new LoginResult { Success = true, ErrorMessage = null, Token = tokenString, Permissions = GetPermissionsFromClaims(claims) }; return(Ok(loginResult)); } if (user.UserName == "user" && user.Password == "user") { claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName) }; tokeOptions = new JwtSecurityToken( issuer: "http://localhost:4200", audience: "https://localhost:44361", claims: claims, expires: DateTime.Now.AddMinutes(5), signingCredentials: signinCredentials ); tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); loginResult = new LoginResult { Success = true, ErrorMessage = null, Token = tokenString, Permissions = GetPermissionsFromClaims(claims) }; return(Ok(loginResult)); } loginResult = new LoginResult { Success = false, ErrorMessage = "Неверный логин или пароль (server)", Token = null, Permissions = null }; return(Ok(loginResult)); }
/// <summary> /// Returns login from actually logged in user /// </summary> /// <returns>Users login</returns> protected string GetAuthorizedUserLogin() { var jwt = new JwtSecurityTokenHandler().ReadJwtToken(Token); return(jwt.Id); }
public LoginResponseDTO GetToken(ApplicationUser user, RefreshToken refreshToken = null) { var options = GetOptions(); var now = DateTime.UtcNow; var claims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.NameId, user.Id), new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64), new Claim(JwtRegisteredClaimNames.Sub, user.UserName), }; var userClaims = _kookifyDbContext.UserClaims.Where(i => i.UserId == user.Id); foreach (var userClaim in userClaims) { claims.Add(new Claim(userClaim.ClaimType, userClaim.ClaimValue)); } var userRoles = _kookifyDbContext.UserRoles.Where(i => i.UserId == user.Id); foreach (var userRole in userRoles) { var role = _kookifyDbContext.Roles.Single(i => i.Id == userRole.RoleId); claims.Add(new Claim(Extensions.RoleClaimType, role.Name)); } if (refreshToken == null) { refreshToken = new RefreshToken() { UserId = user.Id, Token = Guid.NewGuid().ToString("N"), }; Insert(refreshToken); } refreshToken.IssuedUtc = now; refreshToken.ExpiresUtc = now.Add(options.Expiration); _kookifyDbContext.SaveChanges(); var jwt = new JwtSecurityToken( issuer: options.Issuer, audience: options.Audience, claims: claims.ToArray(), notBefore: now, expires: now.Add(options.Expiration), signingCredentials: options.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new LoginResponseDTO { access_token = encodedJwt, refresh_token = refreshToken.Token, expires_in = (int)options.Expiration.TotalSeconds, user_name = user.UserName, first_name = user.FirstName, last_name = user.LastName, is_admin = claims.Any(i => i.Type == Extensions.RoleClaimType && i.Value == Extensions.AdminRole) }; return(response); }
internal static string CreateAndWriteToken(this JwtSecurityTokenHandler handler, SecurityTokenDescriptor descriptor) { SecurityToken token = handler.CreateToken(descriptor); return(handler.WriteToken(token)); }
private string GetToken(string user, DateTime? expires) { var handler = new JwtSecurityTokenHandler(); // Here, you should create or look up an identity for the user which is being authenticated. // For now, just creating a simple generic identity. ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user, "TokenAuth"), new[] { new Claim("EntityID", "1", ClaimValueTypes.Integer) }); var securityToken = handler.CreateToken( issuer: tokenOptions.Issuer, audience: tokenOptions.Audience, signingCredentials: tokenOptions.SigningCredentials, subject: identity, expires: expires ); return handler.WriteToken(securityToken); }
public async Task JwtAccessTokenIssuer_SignsAccessToken() { // Arrange var expectedDateTime = new DateTimeOffset(2000, 01, 01, 0, 0, 0, TimeSpan.FromHours(1)); var now = DateTimeOffset.UtcNow; var expires = new DateTimeOffset(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, TimeSpan.Zero); var timeManager = GetTimeManager(expectedDateTime, expires, expectedDateTime); var options = GetOptions(); var handler = new JwtSecurityTokenHandler(); var tokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = options.Value.SigningKeys[0].Key, ValidAudiences = new[] { "resourceId" }, ValidIssuers = new[] { options.Value.Issuer } }; var issuer = new JwtAccessTokenIssuer( GetClaimsManager(timeManager), GetSigningPolicy(options, timeManager), new JwtSecurityTokenHandler(), options); var context = GetTokenGenerationContext( new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "user") })), new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(IdentityServiceClaimTypes.ClientId, "clientId") }))); context.InitializeForToken(TokenTypes.AccessToken); // Act await issuer.IssueAccessTokenAsync(context); // Assert Assert.NotNull(context.AccessToken); Assert.NotNull(context.AccessToken.SerializedValue); SecurityToken validatedToken; Assert.NotNull(handler.ValidateToken(context.AccessToken.SerializedValue, tokenValidationParameters, out validatedToken)); Assert.NotNull(validatedToken); var jwtToken = Assert.IsType <JwtSecurityToken>(validatedToken); var accessToken = Assert.IsType <AccessToken>(context.AccessToken.Token); Assert.Equal("http://www.example.com/issuer", jwtToken.Issuer); var tokenAudience = Assert.Single(jwtToken.Audiences); Assert.Equal("resourceId", tokenAudience); var tokenAuthorizedParty = Assert.Single(jwtToken.Claims, c => c.Type.Equals("azp")).Value; Assert.Equal("clientId", tokenAuthorizedParty); Assert.Equal("user", jwtToken.Subject); Assert.Equal(expires, jwtToken.ValidTo); Assert.Equal(expectedDateTime.UtcDateTime, jwtToken.ValidFrom); var tokenScopes = jwtToken.Claims .Where(c => c.Type == IdentityServiceClaimTypes.Scope) .Select(c => c.Value).OrderBy(c => c) .ToArray(); Assert.Equal(new[] { "all" }, tokenScopes); }
private string CreateToken(ClaimsIdentity identity, DateTime createDate, DateTime expirationDate, JwtSecurityTokenHandler handler) { var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = _tokenConfigurations.Issuer, Audience = _tokenConfigurations.Audience, SigningCredentials = _signingConfigurations.SigningCredentials, Subject = identity, NotBefore = createDate, Expires = expirationDate, }); var token = handler.WriteToken(securityToken); return(token); }
public SecurityToken CreateTokenFromClaims(IEnumerable <Claim> claims, string tokenKey, JwtSecurityTokenHandler tokenHandler) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenKey)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = credentials }; return(tokenHandler.CreateToken(tokenDescriptor)); }
public ApiAuthenticationStateProvider(ILocalStorageService localStorage, JwtSecurityTokenHandler jwt) { _localStorage = localStorage; _jwt = jwt; }
public async Task <IActionResult> IssueToken() { var pemFileName = Environment.GetEnvironmentVariable(Defines.PrivateKeyFileEnvironmentVariableName) ?? throw new ApplicationException( $"\"{Defines.PrivateKeyFileEnvironmentVariableName}\" environment variable is not set or empty"); logger.LogInformation($"Reading private key from file: {pemFileName}"); var pemDataBytes = await System.IO.File.ReadAllBytesAsync(pemFileName); var pemDataString = Encoding.UTF8.GetString(pemDataBytes); // Use "-----BEGIN PRIVATE KEY-----" and "-----END PRIVATE KEY-----" headers for PKCS8 var b64 = pemDataString.Replace("-----BEGIN RSA PRIVATE KEY-----", string.Empty) .Replace("-----END RSA PRIVATE KEY-----", string.Empty) .Replace("\n", string.Empty) .Trim(); var privateKey = Convert.FromBase64String(b64); var rsa = System.Security.Cryptography.RSA.Create(); // Use rsa.ImportPkcs8PrivateKey(privateKey, out var bytesRead) for PKCS8 keys rsa.ImportRSAPrivateKey(privateKey, out var bytesRead); logger.LogInformation($"RSA private key bytes read: {bytesRead}"); var securityKey = new RsaSecurityKey(rsa); logger.LogInformation($"RSA security key size: {securityKey.KeySize} bits"); // Use preferred sign algorithm var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256); var jwtHeader = new JwtHeader(signingCredentials); const string jti = "TokenIndex"; var jwtPayload = new JwtPayload { { JwtRegisteredClaimNames.Jti, jti }, { JwtRegisteredClaimNames.Sub, "TokenSubject" }, { JwtRegisteredClaimNames.Aud, "TokenAudience" }, { "CustomClaim", "SomeData" }, }; var i = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var e = i + Defines.TokenTtl; var iat = new Claim(JwtRegisteredClaimNames.Iat, i.ToString(), ClaimValueTypes.Integer64); var exp = new Claim(JwtRegisteredClaimNames.Exp, e.ToString(), ClaimValueTypes.Integer64); jwtPayload.AddClaim(iat); jwtPayload.AddClaim(exp); var token = new JwtSecurityToken(jwtHeader, jwtPayload); var tokenHandler = new JwtSecurityTokenHandler(); var accessToken = tokenHandler.WriteToken(token); return(Ok(new { accessToken })); }
protected string JWTConstructAssertionOld() { byte[] randomNumber = new byte[64]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(randomNumber); } var claims = new List<Claim> { new Claim("sub", _config.EntityId), new Claim("box_sub_type", _config.EntityType), new Claim("jti", Convert.ToBase64String(randomNumber)), }; var token = new JwtSecurityToken(issuer: _cpnfig.clientId, audience: _config.BoxApiDeveloperEditionTokenUri, claims: claims, expires: DateTime.UtcNow.AddSeconds(30), signingCredentials: this.credentials); var tokenHandler = new JwtSecurityTokenHandler(); return tokenHandler.WriteToken(token); }
public async Task InvokeAsync(HttpContext context, IUnitOfWork uow) { context.Request.EnableBuffering(); using (var reader = new StreamReader(context.Request.Body)) { string path = context.Request.Path; if (path.Contains("api")) { var body = await reader.ReadToEndAsync(); var ControllerRoute = path.Remove(path.IndexOf('/'), path.LastIndexOf('/') + 1); RequestDTOBase request = Newtonsoft.Json.JsonConvert.DeserializeObject <RequestDTOBase>(body); if (request == null || request.RequestInfo == null || request.RequestInfo.ApplicationId < 1 || String.IsNullOrEmpty(request.RequestInfo.ClientCode) || String.IsNullOrEmpty(request.RequestInfo.ClientPassword)) { throw new BusinessException(ResponseCode.ApplicationNotAuthorized); } if (!String.IsNullOrEmpty(request.RequestInfo.ClientCode) && request.RequestInfo.ApplicationId > 0) { var app = uow.Application.GetApplicationByClientCode(request.RequestInfo.ApplicationId); if (app == null) { throw new BusinessException(ResponseCode.ApplicationNotAuthorized); } var user = await uow.User.GetAsync(x => x.UserName == request.RequestInfo.ClientCode && x.UserType == UserType.Application); if (user == null) { throw new BusinessException(ResponseCode.ApplicationNotAuthorized); } var userApp = await uow.UserApplication.GetAsync(x => x.UserId == user.Id && x.ApplicationId == app.Id); if (userApp == null) { throw new BusinessException(ResponseCode.ApplicationNotAuthorized); } if (!String.IsNullOrEmpty(request.RequestInfo.ClientPassword) && !String.IsNullOrEmpty(user.PasswordSalt) && HashHelper.GetDecryptedString(user.Password, user.PasswordSalt) != request.RequestInfo.ClientPassword) { throw new BusinessException(ResponseCode.ApplicationNotAuthorized); } if (!String.IsNullOrEmpty(context.Request.Headers["Authorization"])) { var accesstoken = context.Request.Headers["Authorization"].ToString().Remove(0, 7); var handler = new JwtSecurityTokenHandler(); var tokenreaded = handler.ReadJwtToken(accesstoken); var userid = Convert.ToInt64(tokenreaded.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value); var userName = tokenreaded.Claims.First(x => x.Type == ClaimTypes.Name).Value; var userPermission = uow.UserRole.HasPermission(userid, ControllerRoute); if (!userPermission) { throw new BusinessException(ResponseCode.PermissionNotFound); } UserManager.ActiveUserId = userid; UserManager.ActiveUserName = userName; } } else { throw new BusinessException(ResponseCode.ApplicationNotAuthorized); } context.Request.Body.Position = 0; } await next(context); } }
private TokenModel GetToken(ApplicationUser user) { var handler = new JwtSecurityTokenHandler(); ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user.Email, "TokenAuth"), new[] { new Claim("UserId", user.Id, ClaimValueTypes.String) }); var securityToken = handler.CreateToken(GetTokenOptions(identity)); return new TokenModel { Token = handler.WriteToken(securityToken) }; }
private async Task <AuthenticationResult> GenerateAuthenticationResultForUserAsync(IdentityUser user) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim("id", user.Id) }; var userClaims = await _userManager.GetClaimsAsync(user); claims.AddRange(userClaims); var userRoles = await _userManager.GetRolesAsync(user); foreach (var userRole in userRoles) { claims.Add(new Claim(ClaimTypes.Role, userRole)); var role = await _roleManager.FindByNameAsync(userRole); if (role == null) { continue; } var roleClaims = await _roleManager.GetClaimsAsync(role); foreach (var roleClaim in roleClaims) { if (claims.Contains(roleClaim)) { continue; } claims.Add(roleClaim); } } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.Add(_jwtSettings.TokenLifetime), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var refreshToken = new RefreshToken { JwtId = token.Id, UserId = user.Id, CreationDate = DateTime.UtcNow, ExpiryDate = DateTime.UtcNow.AddMonths(6) }; await _context.RefreshTokens.AddAsync(refreshToken); await _context.SaveChangesAsync(); return(new AuthenticationResult { Success = true, Token = tokenHandler.WriteToken(token), RefreshToken = refreshToken.Token }); }
public Authenticator(TokenAuthOption tokenAuthOption) { _tokenAuthOption = tokenAuthOption; _jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); }
public async Task Invoke(HttpContext context) { // If the request path doesn't match, skip if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal)) { await _next(context); return; } _logger.LogInformation("Handling request: " + context.Request.Path); // Request must be POST with Content-Type: application/x-www-form-urlencoded if (!context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase) || !context.Request.HasFormContentType) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Bad request."); return; } var username = context.Request.Form["username"]; var password = context.Request.Form["password"]; var identity = _options.IdentityResolver(username, password); if (identity == null) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Invalid username or password."); return; } var now = DateTime.UtcNow; var claims = new Claim[] { // new Claim(JwtRegisteredClaimNames.Jti, _options.NonceGenerator(identity)), new Claim(JwtRegisteredClaimNames.Sub, username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64) }; var jwt = new JwtSecurityToken( issuer: _options.Issuer, audience: _options.Audience, claims: claims, notBefore: now, expires: now.Add(_options.Expiration), signingCredentials: _options.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, expires_in = (int)_options.Expiration.TotalSeconds }; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings)); }
private async Task<TokenValidationResult> ValidateJwtAsync(string jwt, string audience, IEnumerable<SymmetricSecurityKey> symmetricKeys, bool validateLifetime = true) { var handler = new JwtSecurityTokenHandler(); handler.InboundClaimTypeMap.Clear(); var parameters = new TokenValidationParameters { ValidIssuer = _context.GetIssuerUri(), IssuerSigningKeys = symmetricKeys, ValidateLifetime = validateLifetime, ValidAudience = audience }; try { SecurityToken jwtToken; var id = handler.ValidateToken(jwt, parameters, out jwtToken); // load the client that belongs to the client_id claim Client client = null; var clientId = id.FindFirst(JwtClaimTypes.ClientId); if (clientId != null) { client = await _clients.FindClientByIdAsync(clientId.Value); if (client == null) { throw new InvalidOperationException("Client does not exist anymore."); } } return new TokenValidationResult { IsError = false, Claims = id.Claims, Client = client, Jwt = jwt }; } catch (Exception ex) { _logger.LogError("JWT token validation error", ex); return Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken); } }
protected virtual Task<string> SignAsync(JwtSecurityToken jwt) { var handler = new JwtSecurityTokenHandler(); return Task.FromResult(handler.WriteToken(jwt)); }
/// <summary> /// Applies the signature to the JWT /// </summary> /// <param name="jwt">The JWT object.</param> /// <returns>The signed JWT</returns> protected virtual Task <string> CreateJwtAsync(JwtSecurityToken jwt) { var handler = new JwtSecurityTokenHandler(); return(Task.FromResult(handler.WriteToken(jwt))); }
public async Task <IActionResult> Logins([FromBody] Login model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _userManager.FindByNameAsync(model.Username); if (user == null) { user = await _userManager.FindByEmailAsync(model.Username);//.Include(b => b.User); if (user == null) { return(BadRequest("Invalid Username: user doesn't Exist")); } } var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true); if (!result.Succeeded) { return(BadRequest($"Incorrect Password for {model.Username}")); } await _signInManager.SignInAsync(user, true, "Bearer"); var userClaims = await _userManager.GetClaimsAsync(user); userClaims.Add(new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)); userClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("wertyuiopasdfghjklzxcvbnm123456")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var com = _companyRepository.Query().LastOrDefault(); var name = "Acyst Tech"; var image = "logo.png"; var company = "Acyst Technology Company"; if (user.EmployeeId != null) { var emp = _employeeRepository.Query().FirstOrDefault(e => e.EmployeeId == user.EmployeeId); if (emp != null) { name = emp.FullName; } image = emp.Image; } if (com != null) { company = com.Name; } userClaims.Add(new Claim("Id", user.Id)); userClaims.Add(new Claim("FullName", name)); userClaims.Add(new Claim("Company", company)); userClaims.Add(new Claim("Image", image)); userClaims.Add(new Claim("Mobile", user.PhoneNumber)); userClaims.Add(new Claim("Email", user.Email)); userClaims.Add(new Claim("UserType", user.UserType)); userClaims.Add(new Claim("LoginTime", DateTime.Now.ToString())); var token = new JwtSecurityToken( issuer: _configuration.GetSection("AppSettings")["Url"], audience: "http://localhost:53720", claims: userClaims, expires: DateTime.Now.AddHours(12), signingCredentials: creds); user.Login = DateTime.UtcNow; user.IsLoggedIn = true; await _userManager.UpdateAsync(user); var auth = new JwtSecurityTokenHandler().WriteToken(token); await _userManager.SetAuthenticationTokenAsync(user, "Server", user.UserName, auth); var tok = await _userManager.CreateSecurityTokenAsync(user); //await _signInManager.CanSignInAsync(user); return(Ok(new { Access_Token = auth, Expires_In_Hours = 12, Date = DateTime.UtcNow })); }
public IActionResult Login([FromBody] UserDto userDto) { try { this.logger.LogDebug("Login"); // Verify input if (userDto == null) { return(BadRequest(new BadInputResponse())); } // Change to DI service? Seems overkill var chatty = new ChattyWrapper(); var isValid = chatty.VerifyCredentials(userDto.Username, userDto.Password); if (!isValid) { return(BadRequest(new ErrorResponse("Username or password is incorrect."))); } var user = this.dbContext.Users.FirstOrDefault(u => u.Username == userDto.Username); if (user == null) { // New user, create a user record user = new User { Username = userDto.Username }; this.dbContext.Users.Add(user); this.dbContext.SaveChanges(); } // Send back a token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Username) }), Expires = DateTime.UtcNow.AddDays(30), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new { result = "success", username = user.Username, token = tokenString })); } catch (Exception e) { // Log error this.logger.LogError("Message: {0}" + Environment.NewLine + "{1}", e.Message, e.StackTrace); return(BadRequest(new CriticalErrorResponse())); } }
private void Configure(IApplicationBuilder app) { var tokenhander = new JwtSecurityTokenHandler(); tokenhander.InboundClaimTypeMap.Add("name", ClaimTypes.Name); #if DNX451 ServicePointManager.ServerCertificateValidationCallback += EasyCertCheck; #endif app.UseCookieAuthentication(options => { options.AutomaticAuthenticate = true; options.AuthenticationScheme = "Cookies"; options.CookieName = "Cookies"; // options.CookieDomain = ".localhost.me"; options.ExpireTimeSpan = TimeSpan.FromMinutes(5); options.LoginPath = new PathString("/login"); }); app.UseOpenIdConnectAuthentication(options => { options.ProtocolValidator = new OpenIdConnectProtocolValidator { RequireState = false }; options.AutomaticAuthenticate = true; options.AuthenticationScheme = "Cookies"; options.SignInScheme = "Cookies"; options.ResponseType = "code id_token token"; options.ClientId = "myclient"; options.Authority = "https://idnsrv.localhost.me/core"; options.CallbackPath = "/signinopid"; options.PostLogoutRedirectUri = "http://localhost:49100"; options.Scope.Add("myscope"); options.Scope.Add("roles"); options.Scope.Add("read"); options.Scope.Add("write"); options.Scope.Add("offline_access"); }); app.UseStatusCodePages(); app.UseStaticFiles(); app.Map("/login", signoutApp => { signoutApp.Run(async context => { await context.Authentication.ChallengeAsync("Cookies"); }); }); app.Map("/logout", signoutApp => { signoutApp.Run(async context => { await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); }); }); // Add MVC app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new {controller = "Home", action = "Index"} ); }); }
public async Task<IActionResult> Login([FromBody] UserLoginModel user) { if (!ModelState.IsValid) { return BadRequest($"{this.GetModelStateAllErrors()}"); } string userId; try { userId = await GetUserIdByEmailAndPassword(user); if (userId == null) { return BadRequest("Invalid email address and/or password"); } } catch (Exception ex) { _logger.LogError(LoggingEvents.ACCOUNT_LOGIN, ex, $"Login exception for user with email - '{user.Email}'"); return this.InternalServerError(); } var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userId), new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim( JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64 ) }; // Create the JWT security token and encode it. var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials); try { var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); // Serialize and return the response var response = new { access_token = encodedJwt, expires_in = (int)_jwtOptions.ValidFor.TotalSeconds }; //var json = JsonConvert.SerializeObject(response, _serializerSettings); return Ok(response); } catch (Exception ex) { _logger.LogError(LoggingEvents.ACCOUNT_LOGIN ,ex, "Could not generate JWT Token"); return this.InternalServerError(); // TODO: add the following error message - "There was an issue with login. Please try again later!" } }