private bool ValidateMassRoverToken(string token) { var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidAudiences = new string[] { "massrover.client", }, ValidIssuers = new string[] { "massrover.authservice", }, ValidateLifetime = true, IssuerSigningKey = GetTokenSignKey() }; var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); tokenHandler.ValidateToken(token, tokenValidationParameters, out var validatedToken); return(true); }
/// Using the same key used for signing token, user payload is generated back public JwtSecurityToken GenerateUserClaimFromJWT(string authToken) { var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(communicationKey)); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidAudiences = new string[] { "http://www.example.com", }, ValidIssuers = new string[] { "self", }, IssuerSigningKey = signingKey }; var tokenHandler = new JwtSecurityTokenHandler(); Microsoft.IdentityModel.Tokens.SecurityToken validatedToken; try { tokenHandler.ValidateToken(authToken, tokenValidationParameters, out validatedToken); } catch (Exception) { return(null); } return(validatedToken as JwtSecurityToken); }
internal static bool ValidateToken(string token, out System.IdentityModel.Tokens.Jwt.JwtSecurityToken JwtToken) { JwtToken = null; try { var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); JwtToken = tokenHandler.ReadToken(token) as System.IdentityModel.Tokens.Jwt.JwtSecurityToken; if (JwtToken == null) { return(false); } var validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { RequireExpirationTime = true, ValidateIssuer = false, ValidateAudience = false, IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(symmetricKey) }; Microsoft.IdentityModel.Tokens.SecurityToken securityToken; tokenHandler.ValidateToken(token, validationParameters, out securityToken); return(true); } catch (Microsoft.IdentityModel.Tokens.SecurityTokenValidationException e) { Console.WriteLine($"Token Expired!: {e}"); return(false); } }
public static Microsoft.IdentityModel.Tokens.TokenValidationParameters GetTokenValidationParameters() { Microsoft.IdentityModel.Tokens.SecurityKey signingKey = null; // AuthTest.Cryptography.SecurityKeyRepo.GetRsaKey(); //signingKey = AuthTest.Cryptography.SecurityKeyRepo.GetBouncyRsaKey(); // signingKey = AuthTest.Cryptography.SecurityKeyRepo.GetECDsaKey(); // signingKey = AuthTest.Cryptography.SecurityKeyRepo.GetBouncyEcdsaKey(); Microsoft.IdentityModel.Tokens.TokenValidationParameters tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = "ExampleIssuer", // The "iss" (issuer) claim identifies the principal that issued the JWT. // The processing of this claim is generally application specific. // The "iss" value is a case-sensitive string containing a StringOrURI value. // Use of this claim is OPTIONAL. // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = "ExampleAudience", // https://tools.ietf.org/html/rfc7519#section-4.1.3 // In practical use, this tends to be the "client id" or "client key" or "URL" // of the application that the JWT is intended to be used by. // If the principal processing the claim does not identify itself // with a value in the "aud" claim when this claim is present, // then the JWT MUST be rejected. // In the general case, // the "aud" value is an array of case-sensitive strings, // each containing a StringOrURI value. // In the special case when the JWT has one audience, // the "aud" value MAY be a single case-sensitive string // containing a StringOrURI value.The // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here: // ClockSkew = System.TimeSpan.Zero, ClockSkew = new System.TimeSpan(0, 5, 0) // 5 minutes }; // tokenValidationParameters.valid return(tokenValidationParameters); }
public async Task <IActionResult> ImplicitLanding(string accessToken, string idToken) { System.Security.Claims.ClaimsPrincipal claimPrincipal = null; Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuerSigningKey = false, ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false }; System.IdentityModel.Tokens.Jwt.JwtSecurityToken jwtSecurityToken; System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); jwtSecurityToken = handler.ReadJwtToken(idToken); List <System.Security.Claims.Claim> claims = jwtSecurityToken.Claims.ToList(); claims.Add(new Claim("idToken", idToken)); claims.Add(new Claim("accessToken", accessToken)); var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { //AllowRefresh = <bool>, // Refreshing the authentication session should be allowed. //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10), // The time at which the authentication ticket expires. A // value set here overrides the ExpireTimeSpan option of // CookieAuthenticationOptions set with AddCookie. //IsPersistent = true, // Whether the authentication session is persisted across // multiple requests. When used with cookies, controls // whether the cookie's lifetime is absolute (matching the // lifetime of the authentication ticket) or session-based. //IssuedUtc = <DateTimeOffset>, // The time at which the authentication ticket was issued. //RedirectUri = <string> // The full path or absolute URI to be used as an http // redirect response value. }; await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return(View()); }
public SSOAuthenticationOptions() : base("Shibboleth") { this.Caption = "Shibboleth"; this.AuthenticationMode = AuthenticationMode.Active; this._tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters(); this.BackchannelTimeout = TimeSpan.FromMinutes(1.0); this.UseTokenLifetime = true; this.RefreshOnIssuerKeyNotFound = true; this.SPMetadataPath = new PathString("/sp/metadata"); this.SSOPath = new PathString("/account/sso"); }
private async Task <System.Security.Claims.ClaimsPrincipal> ValidateAccessToken(string accessToken, ILogger log) { var audience = _options.Value.Audience; var clientID = _options.Value.ClientId; var tenant = _options.Value.Tenant; var tenantid = _options.Value.TenantId; var authority = string.Format(System.Globalization.CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/v2.0", tenant); var validIssuers = new List <string>() { $"https://login.microsoftonline.com/{tenant}/", $"https://login.microsoftonline.com/{tenant}/v2.0", $"https://login.windows.net/{tenant}/", $"https://login.microsoft.com/{tenant}/", $"https://sts.windows.net/{tenantid}/" }; // Debugging purposes only, set this to false for production Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true; Microsoft.IdentityModel.Protocols.ConfigurationManager <Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration> configManager = new Microsoft.IdentityModel.Protocols.ConfigurationManager <Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration>( $"{authority}/.well-known/openid-configuration", new Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever()); Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration config = null; config = await configManager.GetConfigurationAsync(); Microsoft.IdentityModel.Tokens.ISecurityTokenValidator tokenValidator = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); // Initialize the token validation parameters Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { // App Id URI and AppId of this service application are both valid audiences. ValidAudiences = new[] { audience, clientID }, // Support Azure AD V1 and V2 endpoints. ValidIssuers = validIssuers, IssuerSigningKeys = config.SigningKeys }; try { Microsoft.IdentityModel.Tokens.SecurityToken securityToken; var claimsPrincipal = tokenValidator.ValidateToken(accessToken, validationParameters, out securityToken); return(claimsPrincipal); } catch (Exception ex) { log.LogInformation(ex.Message); } return(null); }
public JwtCookieDataFormat( string algorithm , Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters , int tokenLifetimeMinutes) { this.m_validationParameters = validationParameters; this.m_tokenLifetimeMinutes = tokenLifetimeMinutes; this.m_signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials( this.m_validationParameters.IssuerSigningKey , algorithm ); } // End Constructor
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions jwtBearerOptions = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerOptions(); Microsoft.IdentityModel.Tokens.TokenValidationParameters validation = new Microsoft.IdentityModel.Tokens.TokenValidationParameters(); app.UseMvc(); }
/// <summary> /// /// </summary> /// <param name="tokenString"></param> /// <returns></returns> public static bool IsTokenValid(string tokenString) { JwtSecurityToken token = null; try { var handler = new JwtSecurityTokenHandler(); // Convert to token so that we can read the user to use in the signing key test token = handler.ReadJwtToken(tokenString); // Configure expected validation parameters var parms = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { RequireExpirationTime = true, ValidAudience = "CSET_AUD", ValidIssuer = "CSET_ISS", IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetSecret() + token.Payload[Constants.Token_UserId])) }; Microsoft.IdentityModel.Tokens.SecurityToken validatedToken; var principal = handler.ValidateToken(tokenString, parms, out validatedToken); } catch (ArgumentException argExc) { // the encoded JWT string is not valid because it couldn't be decoded for whatever reason //ElmahWrapper.LogAndReportException(argExc, null, null); return(false); } catch (Exception exc) { // Something failed, likely in the validation. The debugger shows a SecurityTokenInvalidSignatureException // but that class is not found in Microsoft.IdentityModel.Tokens, or anywhere. //ElmahWrapper.LogAndReportException(exc, null, null); return(false); } // see if the token has expired if (token.ValidTo < DateTime.UtcNow) { return(false); } return(true); }
private void ConfigureAutorization(IServiceCollection services) { Security.Configuration.SigningConfigurations signingConfigurations = new Security.Configuration.SigningConfigurations(); services.AddSingleton(signingConfigurations); TokenConfiguration tokenConfigurations = new TokenConfiguration(); new ConfigureFromConfigurationOptions <TokenConfiguration>( Configuration.GetSection("TokenConfigurations") ) .Configure(tokenConfigurations); services.AddSingleton(tokenConfigurations); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { Microsoft.IdentityModel.Tokens.TokenValidationParameters paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = signingConfigurations.Key; paramsValidation.ValidAudience = tokenConfigurations.Audience; paramsValidation.ValidIssuer = tokenConfigurations.Issuer; // Validates the signing of a received token paramsValidation.ValidateIssuerSigningKey = true; // Checks if a received token is still valid paramsValidation.ValidateLifetime = true; // Tolerance time for the expiration of a token (used in case // of time synchronization problems between different // computers involved in the communication process) paramsValidation.ClockSkew = TimeSpan.Zero; }); // Enables the use of the token as a means of // authorizing access to this project's resources services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); }
/// <summary> /// 共通鍵で署名されたトークンを検証するメソッド_test /// トークンの内容は /// aud: 空 /// iss: empno(社員のID) /// exp: 期限切れ /// </summary> /// <param name="empid"></param> /// <returns></returns> public static bool InspectToken(string empid) { //DBよりトークン文字列とトークン生成日付を取得 // ↓はxml内に記述されたSQLの「#」で括られた部分 var param = new { EMP_NO = empid }; var resultModelData = MST_EMP_Repository.FetchAccessToken_Repository(param).First(); // 復号鍵文字列 var keyString = resultModelData.TOKEN_CREATE_DATE.ToString() + FetchTokenPublicKeyString() + empid; // 検証用正解トークン文字列 var tokenString = resultModelData.ACCESS_TOKEN; var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyString)); // トークン操作用のクラス var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); // トークン検証用のパラメータを用意 // Audience, Issuer, Lifetimeに関してはデフォルトで検証が有効になっている // audが空でexpが期限切れなのでValidateAudienceとValidateLifetimeはfalseにしておく var validationParams = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateAudience = false, ValidIssuer = empid, ValidateLifetime = false, IssuerSigningKey = key, }; try { Microsoft.IdentityModel.Tokens.SecurityToken token; // 第三引数にSecurityToken型の変数を参照で渡しておくと、検証済みのトークンが出力される handler.ValidateToken(tokenString, validationParams, out token); return(true); } catch (Exception e) { // ValidateTokenで検証に失敗した場合はここにやってくる return(false); //("トークンが無効です: " + e.Message); } }
public System.Security.Claims.ClaimsPrincipal ValidateIdToken(string idToken, string issuer, string audience) { System.Security.Claims.ClaimsPrincipal claimPrincipal = null; IConfigurationManager <OpenIdConnectConfiguration> configurationManager = new ConfigurationManager <OpenIdConnectConfiguration>($"{issuer}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); //OpenIdConnectConfiguration openIdConfig = RunSync(async () => await configurationManager.GetConfigurationAsync(CancellationToken.None)); OpenIdConnectConfiguration openIdConfig = configurationManager.GetConfigurationAsync(CancellationToken.None).Result; Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidAudience = audience, ValidIssuer = issuer, IssuerSigningKeys = openIdConfig.SigningKeys, ValidateIssuerSigningKey = true, ValidateAudience = true, ValidateIssuer = true, ValidateLifetime = true }; Microsoft.IdentityModel.Tokens.SecurityToken validatedToken; System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); try { claimPrincipal = handler.ValidateToken(idToken, validationParameters, out validatedToken); } catch (Exception ex) { var error = ex.Message; } return(claimPrincipal); }
private void ConfigureAuthentication(IServiceCollection services) { services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { Microsoft.IdentityModel.Tokens.TokenValidationParameters paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = new SigningConfigurations().Key; paramsValidation.ValidateIssuerSigningKey = true; paramsValidation.ValidateLifetime = true; paramsValidation.ClockSkew = TimeSpan.Zero; }); services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); }
/// <summary> /// Validates the JSON Web Token (JWT). /// </summary> /// <param name="encryptedToken">The encrypted token.</param> private void ValidateJsonWebToken(string encryptedToken) { _log.Debug("Validating JSON web token"); try { var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret)); var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature); var parameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidAudience = _audience, ValidIssuer = _issuer, IssuerSigningKey = signingCredentials.Key }; Microsoft.IdentityModel.Tokens.SecurityToken validatedToken; var handler = new JwtSecurityTokenHandler(); var principal = handler.ValidateToken(encryptedToken, parameters, out validatedToken); var token = validatedToken as JwtSecurityToken; if (token == null) { _log.Warn("Invalid JSON web token"); DenyAccess(); } SetPrincipal(principal); _log.DebugFormat("Validated JSON web token for user: {0}", token.Payload.Sub); } catch (Exception ex) { _log.Error("Error validating JSON web token", ex); DenyAccess(); } }
private async Task <System.IdentityModel.Tokens.Jwt.JwtSecurityToken> ValidateAADIdTokenAsync(string idToken) { var stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"; var configRetriever = new Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever(); var configManager = new Microsoft.IdentityModel.Protocols .ConfigurationManager <Microsoft.IdentityModel.Protocols.OpenIdConnect .OpenIdConnectConfiguration>(stsDiscoveryEndpoint, configRetriever); var config = await configManager.GetConfigurationAsync(); var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { IssuerSigningKeys = config.SigningKeys, }; var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); tokenHandler.ValidateToken(idToken, tokenValidationParameters, out var validatedToken); return(validatedToken as System.IdentityModel.Tokens.Jwt.JwtSecurityToken); }
private void Method1() { const string sec = "ProEMLh5e_qnzdNUQrqdHPgp"; const string sec1 = "ProEMLh5e_qnzdNU"; var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.Default.GetBytes(sec)); var securityKey1 = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.Default.GetBytes(sec1)); // This is the input JWT which we want to validate. string tokenString = string.Empty; // If we retrieve the token without decrypting the claims, we woant get any claims // DO not use this jwt variable var jwt = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(tokenString); // Verification var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidAudiences = new string[] { "536481524875-glk7nibpj1q9c4184d4n3gittrt8q3mn.apps.googleusercontent.com" }, ValidIssuers = new string[] { "https://accounts.google.com" }, IssuerSigningKey = securityKey, // This is the decryption key TokenDecryptionKey = securityKey1 }; Microsoft.IdentityModel.Tokens.SecurityToken validatedToken; var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); handler.ValidateToken(tokenString, tokenValidationParameters, out validatedToken); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); SigningConfiguration signingConfiguration = new SigningConfiguration(); TokenConfiguration tokenConfiguration = new TokenConfiguration(); new ConfigureFromConfigurationOptions <TokenConfiguration>(Configuration.GetSection("TokenConfigurations")) .Configure(tokenConfiguration); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { Microsoft.IdentityModel.Tokens.TokenValidationParameters paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = signingConfiguration.Key; paramsValidation.ValidAudience = tokenConfiguration.Audience; paramsValidation.ValidIssuer = tokenConfiguration.Issuer; paramsValidation.ValidateIssuerSigningKey = true; paramsValidation.ValidateLifetime = true; paramsValidation.ClockSkew = TimeSpan.FromSeconds(tokenConfiguration.ClockSkew); }); services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); services.AddSingleton <IUserService, UserService>(); services.AddSingleton(signingConfiguration); services.AddSingleton(tokenConfiguration); }
private void ConfigureAuthentication(IServiceCollection services) { SigningConfigurations signingConfigurations = new SigningConfigurations(); services.AddSingleton(signingConfigurations); TokenConfigurations tokenConfigurations = new TokenConfigurations(); new ConfigureFromConfigurationOptions <TokenConfigurations>( Configuration.GetSection("TokenConfigurations")) .Configure(tokenConfigurations); services.AddSingleton(tokenConfigurations); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { Microsoft.IdentityModel.Tokens.TokenValidationParameters paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = signingConfigurations.Key; paramsValidation.ValidAudience = tokenConfigurations.Audience; paramsValidation.ValidIssuer = tokenConfigurations.Issuer; paramsValidation.ValidateIssuerSigningKey = true; paramsValidation.ValidateLifetime = true; paramsValidation.ClockSkew = TimeSpan.Zero; }); services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); }
private void SetTokenValidationParameters(JwtBearerOptions options) { try { // Both App ID URI and client id are valid audiences in the access token var authority = $"https://login.microsoftonline.com/{_tenantId}/v2.0"; var validAudiences = new string[] { _clientId }; var validateIssuer = true; var tokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidAudiences = validAudiences, ValidateIssuer = validateIssuer, }; options.Authority = authority; options.TokenValidationParameters = tokenValidationParameters; } catch (ArgumentNullException ex) { throw new Exception("Error adding authentication, please check the Web API appsettings.json.", ex); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); var identityServer = Configuration["IdentityServerUrl"]; app.UseCorrelationIdMiddleware(new CorrelationIdMiddlewareOptions()); app.UseSerilogEnricherMiddleware(); app.UseCors("default"); var x = new Microsoft.IdentityModel.Tokens.TokenValidationParameters(); var options = new IdentityServerAuthenticationOptions { Authority = $"{identityServer}", ApiName = "doc-stack-app-api", RequireHttpsMetadata = false, SaveToken = true, JwtBearerEvents = new JwtBearerEvents() { OnTokenValidated = async(context) => { var principal = (ClaimsPrincipal)context.Ticket.Principal; var identity = (ClaimsIdentity)principal.Identity; var accessToken = ((JwtSecurityToken)context.SecurityToken).RawData; identity.AddClaim(new Claim("token", accessToken)); try { var discoveryClient = new DiscoveryClient(context.Options.Authority, null); var doc = await discoveryClient.GetAsync(); var json = Newtonsoft.Json.JsonConvert.SerializeObject(doc, Formatting.Indented); var userInfoClient = new UserInfoClient(doc.UserInfoEndpoint); var response = await userInfoClient.GetAsync(accessToken); json = Newtonsoft.Json.JsonConvert.SerializeObject(response, Formatting.Indented); Console.WriteLine(json); if (response.Claims != null) { identity.AddClaims(response.Claims); } } catch (Exception ex) { Console.WriteLine($"Claims could not be retrieved: {ex}"); } context.Ticket = new AuthenticationTicket(principal, context.Ticket.Properties, context.Ticket.AuthenticationScheme); } } }; var options2 = IdentityServer4.AccessTokenValidation.CombinedAuthenticationOptions.FromIdentityServerAuthenticationOptions(options); options2.JwtBearerOptions.TokenValidationParameters.ValidIssuers = new List <string>() { identityServer }; app.UseIdentityServerAuthentication(options2); app.UsePerformanceLog(new PerformanceLogOptions()); app.UseHealthcheckEndpoint(new HealthCheckOptions() { Message = "Its alive" }); app.UseMvc(); // Enable middleware to serve generated Swagger as a JSON endpoint app.UseSwagger(); // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.) app.UseSwaggerUi(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "doc-stack-app-api"); c.ConfigureOAuth2("doc-stack-app-api-swagger", null, "swagger-ui-realm", "Swagger UI"); }); }
private bool VerifyToken(string token) { var jwtSecurityTokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); // ************************************************** // Symmetric key must be atleast 128 bits long string strSymmetricKey = "This is the Symmetric Key"; var symmetricSecurityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey (System.Text.Encoding.ASCII.GetBytes(strSymmetricKey)); // ************************************************** // validation parameters, JWtValidator requires this object to validate the token. var validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateLifetime = true, RequireExpirationTime = true, ValidateIssuer = true, ValidIssuer = "[Token Issuer Name]", ValidateAudience = true, ValidAudience = "http://www.IranianExperts.com", ValidateIssuerSigningKey = true, IssuerSigningKey = symmetricSecurityKey, }; Microsoft.IdentityModel.Tokens.SecurityToken validatedSecurityToken = null; System.IdentityModel.Tokens.Jwt.JwtSecurityToken validatedJwtSecurityToken = null; try { // If token is valid, it will output the validated token // that contains the JWT information otherwise it will throw an exception var principal = jwtSecurityTokenHandler.ValidateToken (token: token, validationParameters: validationParameters, validatedToken: out validatedSecurityToken); validatedJwtSecurityToken = validatedSecurityToken as System.IdentityModel.Tokens.Jwt.JwtSecurityToken; if (validatedJwtSecurityToken == null) { return(false); } string strType = "Username"; var varName = validatedJwtSecurityToken.Claims .Where(current => string.Compare(current.Type, strType, true) == 0) .FirstOrDefault(); string X = varName.Value; } catch (System.Exception ex) { return(false); } return(true); }
private string ValidateIssuer(string issuer, Microsoft.IdentityModel.Tokens.SecurityToken securityToken, Microsoft.IdentityModel.Tokens.TokenValidationParameters validationParameters) { validationParameters.ValidateIssuer = true; return(issuer); }