public TokenProviderOptions()
        {
            Path = "/api/token";
            Issuer = "ExampleIssuer";
            Audience = "ExampleAudience";
            Expiration = TimeSpan.FromDays(1);
            var secretKey = "mysupersecret_secretkey!123";
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
            SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            TokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = "ExampleIssuer",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = Audience,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };
        }
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            AuthenticationTicket ticket = _ticketDataFormat.Unprotect(securityToken);

            validatedToken = null;

            return ticket?.Principal;
        }
Beispiel #3
0
        // 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)
        {
            var audienceConfig = Configuration.GetSection("Audience");
            var symmetricKeyAsBase64 = audienceConfig["Secret"];
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);

            var options = new TokenProviderOptions
            {
                Audience = "ExampleAudience",
                Issuer = "ExampleIssuer",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
            };

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = options.Issuer,

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = options.Audience,

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters,

            });

            app.UseMiddleware<CustomTokenProviderMiddleware>(Options.Create(options));

            app.UseMvc();
        }
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken = null;

            var claims = new[]
            {
                // Make sure to use a different name identifier
                // than the one defined by CustomTokenValidated.
                new Claim(ClaimTypes.NameIdentifier, "Bob le Tout Puissant"),
                new Claim(ClaimTypes.Email, "[email protected]"),
                new Claim(ClaimsIdentity.DefaultNameClaimType, "bob"),
            };

            return new ClaimsPrincipal(new ClaimsIdentity(claims));
        }
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken = null;

            if (securityToken == DEMO_TOKEN)
            {
                // TODO: Complete all claims and other user data
                var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, DEMO_USERNAME),
                    new Claim(ClaimsIdentity.DefaultNameClaimType, DEMO_USERNAME),
                    new Claim(ClaimTypes.Email, DEMO_EMAIL)
                };
                return new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer") { BootstrapContext = securityToken });
            }
            else
            {
                throw new ApiException(new InvalidTokenProblem());
            }
        }
Beispiel #6
0
        public bool IsValidToken(string token) {

            var validationParameters = new TokenValidationParameters {
                ValidateLifetime = true,
                ValidateAudience = true,
                ValidateIssuer = true,
                ValidateIssuerSigningKey = true,
                ValidAudience = _tokenAuthOption.Audience,
                ValidIssuer = _tokenAuthOption.Issuer,
                IssuerSigningKey = _tokenAuthOption.Key
            };

            SecurityToken validatedToken;
            try {
                var principal = _jwtSecurityTokenHandler.ValidateToken(token, validationParameters, out validatedToken);
            }
            catch (Exception) {
                return false;
            }
            return validatedToken != null;
        }
        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;
        }
Beispiel #8
0
        private TokenValidationParameters CreateTokenValidationParameters()
        {
            var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _signingKey,

                RequireExpirationTime = true,
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };
            return tokenValidationParameters;
        }
        internal static Lazy<OAuthBearerAuthenticationOptions> ConfigureLocalValidation(IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
        {
            return new Lazy<OAuthBearerAuthenticationOptions>(() =>
            {
                JwtFormat tokenFormat = null;

                // use static configuration
                if (!string.IsNullOrWhiteSpace(options.IssuerName) &&
                    options.SigningCertificate != null)
                {
                    var audience = options.IssuerName.EnsureTrailingSlash();
                    audience += "resources";

                    var valParams = new TokenValidationParameters
                    {
                        ValidIssuer = options.IssuerName,
                        ValidAudience = audience,
                        IssuerSigningToken = new X509SecurityToken(options.SigningCertificate),

                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType,
                    };

                    tokenFormat = new JwtFormat(valParams);
                }
                else
                {
                    // use discovery endpoint
                    if (string.IsNullOrWhiteSpace(options.Authority))
                    {
                        throw new Exception("Either set IssuerName and SigningCertificate - or Authority");
                    }

                    var discoveryEndpoint = options.Authority.EnsureTrailingSlash();
                    discoveryEndpoint += ".well-known/openid-configuration";

                    var issuerProvider = new DiscoveryDocumentIssuerSecurityTokenProvider(
                        discoveryEndpoint,
                        options,
                        loggerFactory);

                    var valParams = new TokenValidationParameters
                    {
                        ValidAudience = issuerProvider.Audience,
                        NameClaimType = options.NameClaimType,
                        RoleClaimType = options.RoleClaimType
                    };

                    tokenFormat = new JwtFormat(valParams, issuerProvider);
                }


                var bearerOptions = new OAuthBearerAuthenticationOptions
                {
                    AccessTokenFormat = tokenFormat,
                    AuthenticationMode = options.AuthenticationMode,
                    AuthenticationType = options.AuthenticationType,
                    Provider = new ContextTokenProvider(options.TokenProvider)
                };

                return bearerOptions;

            }, true);
        }
Beispiel #10
0
        // 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 jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

                ValidateAudience = true,
                ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _signingKey,

                RequireExpirationTime = true,
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero,

            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters,
                RequireHttpsMetadata = !env.IsDevelopment(),
            });

            app.UseDefaultFiles();

            app.UseStaticFiles();

            app.UseIdentity();

            app.UseMvc();

            app.UseWebSockets();

            app.UseSignalR();



            var logger = loggerFactory.CreateLogger("Yiyi" + jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)]);
            logger.LogInformation("IsDev: " + env.IsDevelopment());

            using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var ctx = serviceScope.ServiceProvider.GetService<BrewMaticContext>();
                ctx.Database.Migrate();
                ctx.Seed();
                var ctx2 = serviceScope.ServiceProvider.GetService<IdentityContext>();
                ctx2.Database.Migrate();
                var usrMgr = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
                var rlMgr = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
                ctx2.Seed(usrMgr, rlMgr, Configuration["DefaultPassword"]);
            }
        }
Beispiel #11
0
        // 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, SagaBus sagaBus,
            IOptions<OAuth20Configuration> oauthOptions)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseApplicationInsightsExceptionTelemetry();

            app.UseStaticFiles();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Obsidian.Cookie",
                AutomaticChallenge = false,
                AutomaticAuthenticate = false
            });

            var oauthConfig = oauthOptions.Value;
            var key = oauthConfig.TokenSigningKey;
            var signingKey = new SymmetricSecurityKey(Encoding.Unicode.GetBytes(key));
            var param = new TokenValidationParameters
            {
                AuthenticationType = "Bearer",
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidateIssuer = true,
                ValidIssuer = oauthConfig.TokenIssuer,
                ValidAudience = oauthConfig.TokenAudience
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                TokenValidationParameters = param,
                AutomaticAuthenticate = false,
                AutomaticChallenge = false
            });

            app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });

            MappingConfig.ConfigureQueryModelMapping();
            sagaBus.RegisterSagas();
        }
        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);
            }
        }
 public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
 {
     var constructor = ExceptionType.GetTypeInfo().GetConstructor(new[] { typeof(string) });
     var exception = (Exception)constructor.Invoke(new[] { ExceptionType.Name });
     throw exception;
 }
Beispiel #14
0
 public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
 {
     throw new SecurityTokenException("InvalidToken");
 }