// https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/179
        public async Task BearerTokenValidation()
        {
            var options = new JwtBearerOptions
            {
                Authority = "https://login.windows.net/tushartest.onmicrosoft.com",
                Audience = "https://TusharTest.onmicrosoft.com/TodoListService-ManualJwt"
            };
            options.TokenValidationParameters.ValidateLifetime = false;
            var server = CreateServer(options);

            var newBearerToken = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cdng2OHNrVDgtbVBBQjNCc2VlQSJ9.eyJhdWQiOiJodHRwczovL1R1c2hhclRlc3Qub25taWNyb3NvZnQuY29tL1RvZG9MaXN0U2VydmljZS1NYW51YWxKd3QiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9hZmJlY2UwMy1hZWFhLTRmM2YtODVlNy1jZTA4ZGQyMGNlNTAvIiwiaWF0IjoxNDE4MzMwNjE0LCJuYmYiOjE0MTgzMzA2MTQsImV4cCI6MTQxODMzNDUxNCwidmVyIjoiMS4wIiwidGlkIjoiYWZiZWNlMDMtYWVhYS00ZjNmLTg1ZTctY2UwOGRkMjBjZTUwIiwiYW1yIjpbInB3ZCJdLCJvaWQiOiI1Mzk3OTdjMi00MDE5LTQ2NTktOWRiNS03MmM0Yzc3NzhhMzMiLCJ1cG4iOiJWaWN0b3JAVHVzaGFyVGVzdC5vbm1pY3Jvc29mdC5jb20iLCJ1bmlxdWVfbmFtZSI6IlZpY3RvckBUdXNoYXJUZXN0Lm9ubWljcm9zb2Z0LmNvbSIsInN1YiI6IkQyMm9aMW9VTzEzTUFiQXZrdnFyd2REVE80WXZJdjlzMV9GNWlVOVUwYnciLCJmYW1pbHlfbmFtZSI6Ikd1cHRhIiwiZ2l2ZW5fbmFtZSI6IlZpY3RvciIsImFwcGlkIjoiNjEzYjVhZjgtZjJjMy00MWI2LWExZGMtNDE2Yzk3ODAzMGI3IiwiYXBwaWRhY3IiOiIwIiwic2NwIjoidXNlcl9pbXBlcnNvbmF0aW9uIiwiYWNyIjoiMSJ9.N_Kw1EhoVGrHbE6hOcm7ERdZ7paBQiNdObvp2c6T6n5CE8p0fZqmUd-ya_EqwElcD6SiKSiP7gj0gpNUnOJcBl_H2X8GseaeeMxBrZdsnDL8qecc6_ygHruwlPltnLTdka67s1Ow4fDSHaqhVTEk6lzGmNEcbNAyb0CxQxU6o7Fh0yHRiWoLsT8yqYk8nKzsHXfZBNby4aRo3_hXaa4i0SZLYfDGGYPdttG4vT_u54QGGd4Wzbonv2gjDlllOVGOwoJS6kfl1h8mk0qxdiIaT_ChbDWgkWvTB7bTvBE-EgHgV0XmAo0WtJeSxgjsG3KhhEPsONmqrSjhIUV4IVnF2w";
            var response = await SendAsync(server, "http://example.com/oauth", newBearerToken);
            Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
        }
        public async Task BearerTurns401To403IfAuthenticated()
        {
            var options = new JwtBearerOptions();
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
            var server = CreateServer(options);

            var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token");
            Assert.Equal(HttpStatusCode.Forbidden, response.Response.StatusCode);
        }
        public static void SetJwtBearer(this IApplicationBuilder app, Auth0Settings settings, Func<ClaimsIdentity, Task> onTokenValidated)
        {
            var options = new JwtBearerOptions()
            {
                Audience = settings.ClientId,
                Authority = $"https://{settings.Domain}",
                Challenge = $"Bearer realm=\"{settings.Domain}\", scope=\"client_id={settings.ClientId} service=\"",
                Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        logger.LogDebug("Authentication failed.", context.Exception);
                        return Task.FromResult(0);
                    },
                    OnChallenge = context =>
                    {
                        logger.LogDebug("Bearer Auth OnChallenge.");
                        return Task.FromResult(true);
                    },
                    OnMessageReceived = context =>
                    {
                        logger.LogDebug("Bearer Auth OnMessageReceived");
                        return Task.FromResult(true);
                    },
                    OnTokenValidated = async context =>
                    {
                        var claimsIdentity = context.Ticket.Principal.Identity as ClaimsIdentity;
                        logger.LogInformation($"{claimsIdentity?.Name} authenticated using bearer authentication.");

                        await onTokenValidated(claimsIdentity);
                    }
                }
            };
            app.UseJwtBearerAuthentication(options);

            // this is a hack, which hopefully will be solved with RC2 of .net core
            // * The problem has been discussed here: https://github.com/aspnet/Security/issues/555
            // * The workaround got copied from here: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/issues/191
            app.Use(next => async context =>
            {
                try
                {
                    await next(context);
                }
                catch (SecurityTokenException)
                {
                    // If the headers have already been sent, you can't replace the status code.
                    // In this case, throw an exception to close the connection.
                    if (context.Response.HasStarted)
                    {
                        throw;
                    }

                    context.Response.StatusCode = 401;
                }
            });
        }
        // 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();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var jwtBearerOptions = new JwtBearerOptions
                                   {
                                       AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
                                       AutomaticAuthenticate = true
                                   };
            jwtBearerOptions.SecurityTokenValidators.Clear();
            jwtBearerOptions.SecurityTokenValidators.Add(new TicketDataFormatTokenValidator());

            app.UseJwtBearerAuthentication(jwtBearerOptions);

            app.UseMvc(
                          routes =>
                          {
                              routes.MapRoute(
                                                 "WebApi",
                                                 "api/{controller}/{action}/{id?}",
                                                 new { action = "Get" }
                                             );

                          }
                      );
        }
        public BaseJwtBearerContext(HttpContext context, JwtBearerOptions options)
            : base(context)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            Options = options;
        }
        /// <summary>
        /// Adds the <see cref="JwtBearerMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Bearer token processing capabilities.
        /// This middleware understands appropriately
        /// formatted and secured tokens which appear in the request header. If the Options.AuthenticationMode is Active, the
        /// claims within the bearer token are added to the current request's IPrincipal User. If the Options.AuthenticationMode 
        /// is Passive, then the current request is not modified, but IAuthenticationManager AuthenticateAsync may be used at
        /// any time to obtain the claims from the request's bearer token.
        /// See also http://tools.ietf.org/html/rfc6749
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="options">A  <see cref="JwtBearerOptions"/> that specifies options for the middleware.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, JwtBearerOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return app.UseMiddleware<JwtBearerMiddleware>(Options.Create(options));
        }
        public static IApplicationBuilder UseJwtBearerIdentity(this IApplicationBuilder app)
        {
            if(app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            var marker = app.ApplicationServices.GetService<IdentityMarkerService>();
            if(marker == null)
            {
                throw new InvalidOperationException("Must Call AddJwtBearerIdentity");
            }

            var jwtOptions = app.ApplicationServices.GetRequiredService<IOptions<JwtBearerIdentityOptions>>().Value;

            var options = new JwtBearerOptions();

            // Basic settings - signing key to validate with, audience and issuer.
            options.TokenValidationParameters.IssuerSigningKey = jwtOptions.SigningCredentials.Key;
            options.TokenValidationParameters.ValidAudience = jwtOptions.Audience;
            options.TokenValidationParameters.ValidIssuer = jwtOptions.Issuer;

            options.TokenValidationParameters.RequireExpirationTime = true;
            options.TokenValidationParameters.RequireSignedTokens = false;

            // When receiving a token, check that we've signed it.
            options.TokenValidationParameters.RequireSignedTokens = false;

            //// When receiving a token, check that it is still valid.
            options.TokenValidationParameters.ValidateLifetime = true;

            // This defines the maximum allowable clock skew - i.e. provides a tolerance on the token expiry time
            // when validating the lifetime. As we're creating the tokens locally and validating them on the same
            // machines which should have synchronised time, this can be set to zero. Where external tokens are
            // used, some leeway here could be useful.
            options.TokenValidationParameters.ClockSkew = TimeSpan.FromMinutes(0);

            options.Events = new JwtBearerEvents
            {
                OnTokenValidated = JwtBearerEventImplementations.ValidatedTokenAsync,
                OnAuthenticationFailed = JwtBearerEventImplementations.AuthenticationFailedAsync,
                OnMessageReceived = JwtBearerEventImplementations.MessageReceivedAsync
            };

            app.UseJwtBearerAuthentication(options);

            return app;
        }
Beispiel #8
0
        public static IApplicationBuilder UseJwtBearerAuthenticationWithTokenIssuer(this IApplicationBuilder app)
        {
            var jwtOptions = (IOptions <JwtAuthenticationOptions>)app.ApplicationServices.GetService(typeof(IOptions <JwtAuthenticationOptions>));

            var options = new JwtBearerOptions
            {
                TokenValidationParameters = jwtOptions.Value.Parameters
            };

            app.UseJwtBearerAuthentication(options);

            //JWT token endpoint
            app.UseMiddleware <JwtBearerTokenIssuerMiddleware>();

            return(app);
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            loggerFactory.AddDebug();

            app.UseExceptionHandler("/Home/Error");

            app.UseCors("corsGlobalPolicy");

            app.UseStaticFiles();

            //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            //app.UseIdentityServerAuthentication(options =>
            //{
            //    options.Authority = "https://localhost:44345/";
            //    options.ScopeName = "dataEventRecords";
            //    options.ScopeSecret = "dataEventRecordsSecret";

            //    options.AutomaticAuthenticate = true;
            //    required if you want to return a 403 and not a 401 for forbidden responses

            //   options.AutomaticChallenge = true;
            //});

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary<string, string>();

            var jwtBearerOptions = new JwtBearerOptions()
            {
                Authority = "https://localhost:44345",
                Audience = "https://localhost:44345/resources",
                AutomaticAuthenticate = true,

                // required if you want to return a 403 and not a 401 for forbidden responses
                AutomaticChallenge = true
            };

            app.UseJwtBearerAuthentication(jwtBearerOptions);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        internal void ConfigureJwtBearer(JwtBearerOptions jwtOptions)
        {
            jwtOptions.Authority                  = Authority;
            jwtOptions.RequireHttpsMetadata       = RequireHttpsMetadata;
            jwtOptions.BackchannelTimeout         = BackChannelTimeouts;
            jwtOptions.RefreshOnIssuerKeyNotFound = true;
            jwtOptions.SaveToken                  = SaveToken;
            jwtOptions.Events = new JwtBearerEvents
            {
                OnMessageReceived = e =>
                {
                    e.Token = InternalTokenRetriever(e.Request);
                    return(JwtBearerEvents.MessageReceived(e));
                },

                OnTokenValidated       = e => JwtBearerEvents.TokenValidated(e),
                OnAuthenticationFailed = e => JwtBearerEvents.AuthenticationFailed(e),
                OnChallenge            = e => JwtBearerEvents.Challenge(e)
            };

            if (DiscoveryDocumentRefreshInterval.HasValue)
            {
                var parsedUrl = DiscoveryClient.ParseUrl(Authority);

                var httpClient = new HttpClient(JwtBackChannelHandler ?? new HttpClientHandler())
                {
                    Timeout = BackChannelTimeouts,
                    MaxResponseContentBufferSize = 1024 * 1024 * 10 // 10 MB
                };

                var manager = new ConfigurationManager <OpenIdConnectConfiguration>(
                    parsedUrl.discoveryEndpoint,
                    new OpenIdConnectConfigurationRetriever(),
                    new HttpDocumentRetriever(httpClient)
                {
                    RequireHttps = RequireHttpsMetadata
                })
                {
                    AutomaticRefreshInterval = DiscoveryDocumentRefreshInterval.Value
                };

                jwtOptions.ConfigurationManager = manager;
            }

            if (JwtBackChannelHandler != null)
            {
                jwtOptions.BackchannelHttpHandler = JwtBackChannelHandler;
            }

            // if API name is set, do a strict audience check for
            if (!string.IsNullOrWhiteSpace(ApiName) && !LegacyAudienceValidation)
            {
                jwtOptions.Audience = ApiName;
            }
            else
            {
                // no audience validation, rely on scope checks only
                jwtOptions.TokenValidationParameters.ValidateAudience = false;
            }

            jwtOptions.TokenValidationParameters.NameClaimType = NameClaimType;
            jwtOptions.TokenValidationParameters.RoleClaimType = RoleClaimType;

            if (InboundJwtClaimTypeMap != null)
            {
                var handler = new JwtSecurityTokenHandler
                {
                    InboundClaimTypeMap = InboundJwtClaimTypeMap
                };

                jwtOptions.SecurityTokenValidators.Clear();
                jwtOptions.SecurityTokenValidators.Add(handler);
            }
        }
		private JwtBearerOptions GetJwtBearerOptions(TokenAuthorizationOptions tokenAuthorizationOptions) {
			var options = new JwtBearerOptions();
			options.TokenValidationParameters.IssuerSigningKey = tokenAuthorizationOptions.SigningCredentials.Key;
			options.TokenValidationParameters.ValidAudience = tokenAuthorizationOptions.Audience;
			options.TokenValidationParameters.ValidIssuer = tokenAuthorizationOptions.Issuer;
			options.TokenValidationParameters.ValidateLifetime = true;
			options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;

			return options;
		}
        public async Task ExceptionsReportedInHeaderExposesUserDefinedError(string error, string description, string uri)
        {
            var options = new JwtBearerOptions
            {
                Events = new JwtBearerEvents
                {
                    OnChallenge = context =>
                    {
                        context.Error = error;
                        context.ErrorDescription = description;
                        context.ErrorUri = uri;

                        return Task.FromResult(0);
                    }
                }
            };
            var server = CreateServer(options);

            var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
            Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
            Assert.Equal("", response.ResponseText);

            var builder = new StringBuilder(options.Challenge);

            if (!string.IsNullOrEmpty(error))
            {
                builder.Append(" error=\"");
                builder.Append(error);
                builder.Append("\"");
            }
            if (!string.IsNullOrEmpty(description))
            {
                if (!string.IsNullOrEmpty(error))
                {
                    builder.Append(",");
                }

                builder.Append(" error_description=\"");
                builder.Append(description);
                builder.Append('\"');
            }
            if (!string.IsNullOrEmpty(uri))
            {
                if (!string.IsNullOrEmpty(error) ||
                    !string.IsNullOrEmpty(description))
                {
                    builder.Append(",");
                }

                builder.Append(" error_uri=\"");
                builder.Append(uri);
                builder.Append('\"');
            }

            Assert.Equal(builder.ToString(), response.Response.Headers.WwwAuthenticate.First().ToString());
        }
        public static IApplicationBuilder UseJwtAuthentication(this IApplicationBuilder app)
        {
            var Configuration = (IConfiguration)app.ApplicationServices.GetService(typeof(IConfiguration));
            TicketJwtTokenHandler jwtHandler = new TicketJwtTokenHandler();



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

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = Configuration["ValidIssuer"],

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience    = Configuration["ValidAudience"],

                // Validate the token expiry
                ValidateLifetime = true,

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



            JwtBearerOptions bearerOptions = new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = tokenValidationParameters,
                Authority            = Configuration["domain"],
                RequireHttpsMetadata = false,
                Audience             = Configuration["ValidAudience"],
                Configuration        = new OpenIdConnectConfiguration
                {
                    Issuer = Configuration["ValidIssuer"],
                },

                Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        return(Task.FromResult(0));
                    },
                    OnMessageReceived = context =>
                    {
                        return(Task.FromResult(0));
                    },
                    OnTokenValidated = context =>
                    {
                        var cacheService = app.ApplicationServices.GetService <UserCacheService <IdentityUser> >();
                        var identity     = context.Ticket.Principal.Identity as TicketIdentity;


                        var idClaim = identity.Claims.FirstOrDefault(i => i.Type == "Id");
                        if (idClaim != null)
                        {
                            var cachedUser = cacheService.Get(idClaim.Value);
                            identity.User = cachedUser;
                        }

                        Console.Write(context.Ticket.Principal.Identity.Name);
                        return(Task.FromResult(0));
                    },
                    OnChallenge = context =>
                    {
                        return(Task.FromResult(0));
                    }
                }
            };

            bearerOptions.SecurityTokenValidators.RemoveAt(0);
            bearerOptions.SecurityTokenValidators.Add(jwtHandler);

            app.UseJwtBearerAuthentication(bearerOptions);

            return(app);
        }
Beispiel #14
0
        /// <summary>
        /// Adds the <see cref="JwtBearerMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Bearer token processing capabilities.
        /// This middleware understands appropriately
        /// formatted and secured tokens which appear in the request header. If the Options.AuthenticationMode is Active, the
        /// claims within the bearer token are added to the current request's IPrincipal User. If the Options.AuthenticationMode
        /// is Passive, then the current request is not modified, but IAuthenticationManager AuthenticateAsync may be used at
        /// any time to obtain the claims from the request's bearer token.
        /// See also http://tools.ietf.org/html/rfc6749
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="options">A  <see cref="JwtBearerOptions"/> that specifies options for the middleware.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, JwtBearerOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(app.UseMiddleware <JwtBearerMiddleware>(Options.Create(options)));
        }
 public TokenValidatedContext(HttpContext context, JwtBearerOptions options)
     : base(context, options)
 {
 }
        private static TestServer CreateServer(JwtBearerOptions options, Func<HttpContext, bool> handler = null)
        {
            var builder = new WebHostBuilder()
                .Configure(app =>
                {
                    if (options != null)
                    {
                        app.UseJwtBearerAuthentication(options);
                    }

                    app.Use(async (context, next) =>
                    {
                        if (context.Request.Path == new PathString("/checkforerrors"))
                        {
                            var authContext = new AuthenticateContext(Http.Authentication.AuthenticationManager.AutomaticScheme);
                            await context.Authentication.AuthenticateAsync(authContext);
                            if (authContext.Error != null)
                            {
                                throw new Exception("Failed to authenticate", authContext.Error);
                            }
                            return;
                        }
                        else if (context.Request.Path == new PathString("/oauth"))
                        {
                            if (context.User == null ||
                                context.User.Identity == null ||
                                !context.User.Identity.IsAuthenticated)
                            {
                                context.Response.StatusCode = 401;

                                return;
                            }

                            var identifier = context.User.FindFirst(ClaimTypes.NameIdentifier);
                            if (identifier == null)
                            {
                                context.Response.StatusCode = 500;

                                return;
                            }

                            await context.Response.WriteAsync(identifier.Value);
                        }
                        else if (context.Request.Path == new PathString("/unauthorized"))
                        {
                            // Simulate Authorization failure 
                            var result = await context.Authentication.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
                            await context.Authentication.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme);
                        }
                        else if (context.Request.Path == new PathString("/signIn"))
                        {
                            await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal()));
                        }
                        else if (context.Request.Path == new PathString("/signOut"))
                        {
                            await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync(JwtBearerDefaults.AuthenticationScheme));
                        }
                        else
                        {
                            await next();
                        }
                    });
                })
                .ConfigureServices(services => services.AddAuthentication());
            return new TestServer(builder);
        }
        public async Task EventOnAuthenticationFailedSkipped_NoMoreEventsExecuted()
        {
            var options = new JwtBearerOptions
            {
                Events = new JwtBearerEvents()
                {
                    OnTokenValidated = context =>
                    {
                        throw new Exception("Test Exception");
                    },
                    OnAuthenticationFailed = context =>
                    {
                        context.SkipToNextMiddleware();
                        return Task.FromResult(0);
                    },
                    OnChallenge = context =>
                    {
                        throw new NotImplementedException();
                    },
                }
            };
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT"));
            var server = CreateServer(options);

            var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token");
            Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
            Assert.Equal(string.Empty, response.ResponseText);
        }
        public async Task ExceptionsReportedInHeaderForMultipleAuthenticationFailures()
        {
            var options = new JwtBearerOptions();
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(new InvalidTokenValidator(typeof(SecurityTokenInvalidAudienceException)));
            options.SecurityTokenValidators.Add(new InvalidTokenValidator(typeof(SecurityTokenSignatureKeyNotFoundException)));
            var server = CreateServer(options);

            var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
            Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
            Assert.Equal("Bearer error=\"invalid_token\", error_description=\"The audience is invalid; The signature key was not found\"",
                response.Response.Headers.WwwAuthenticate.First().ToString());
            Assert.Equal("", response.ResponseText);
        }
        public async Task RetrievingTokenFromAlternateLocation()
        {
            var options = new JwtBearerOptions()
            {
                Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        context.Token = "CustomToken";
                        return Task.FromResult<object>(null);
                    }
                }
            };
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT", token =>
            {
                Assert.Equal("CustomToken", token);
            }));
            var server = CreateServer(options);

            var response = await SendAsync(server, "http://example.com/oauth", "Bearer Token");
            Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
            Assert.Equal("Bob le Tout Puissant", response.ResponseText);
        }
 public AuthenticationController(ILogger<AuthenticationController> logger, IOptions<JwtBearerOptions> authOptions, SigningCredentials signingCredentials)
 {
     _logger = logger;
     _AuthOptions = authOptions.Value;
     _SigningCredentials = signingCredentials;
 }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var config =
                new LoggerConfiguration()
                    .WriteTo.Seq(serverUrl: Configuration["Seq:Url"], apiKey: Configuration["Seq:Key"])
                    .Enrich.WithProperty("ApplicationName", "Music Store")
                    .Enrich.With(new HttpRequestIdEnricher());
            Log.Logger = config.CreateLogger();

            loggerFactory.AddSerilog();
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseCors(policy => policy
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            }
            else
            {
                app.UseCors(policy => policy
                            .WithOrigins(Configuration["Cors:Url"])
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials());
            }

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

            app.UseStaticFiles();

            // required for decryption
            var keyAsBase64 = Configuration["Auth0:ClientSecret"].Replace('_', '/').Replace('-', '+');
            var keyAsBytes = Convert.FromBase64String(keyAsBase64);

            var jwtOptions = new JwtBearerOptions
            {
                Audience = Configuration["Auth0:ClientId"],
                Authority = $"https://{Configuration["Auth0:Domain"]}",
                Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        Log.Logger.Error("Authentication failed.", context.Exception);
                        return Task.FromResult(0);
                    }
                },
                TokenValidationParameters =
                {
                    IssuerSigningKey = new SymmetricSecurityKey(keyAsBytes)
                }
            };
            app.UseJwtBearerAuthentication(jwtOptions);

            // Note: this line must be after the OAuth config above
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "",
                    defaults: new { controller = "Home", action = "Index" }
                );
            });
            app.UseSwaggerUi();
            app.UseSwagger();

            app.UseRaygun();

            app.UseApplicationInsightsRequestTelemetry();
            app.UseApplicationInsightsExceptionTelemetry();
        }
        public async Task ExceptionNotReportedInHeaderForOtherFailures(Type errorType)
        {
            var options = new JwtBearerOptions();
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(new InvalidTokenValidator(errorType));
            var server = CreateServer(options);

            var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
            Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
            Assert.Equal("Bearer error=\"invalid_token\"", response.Response.Headers.WwwAuthenticate.First().ToString());
            Assert.Equal("", response.ResponseText);
        }
 public MessageReceivedContext(HttpContext context, JwtBearerOptions options)
     : base(context, options)
 {
 }
 public JwtBearerChallengeContext(HttpContext context, JwtBearerOptions options, AuthenticationProperties properties)
     : base(context, options)
 {
     Properties = properties;
 }
 public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, JwtBearerOptions options)
 {
     throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470");
 }
        public async Task CustomTokenValidated()
        {
            var options = new JwtBearerOptions
            {
                Events = new JwtBearerEvents()
                {
                    OnTokenValidated = context =>
                    {
                        // Retrieve the NameIdentifier claim from the identity
                        // returned by the custom security token validator.
                        var identity = (ClaimsIdentity)context.Ticket.Principal.Identity;
                        var identifier = identity.FindFirst(ClaimTypes.NameIdentifier);

                        Assert.Equal("Bob le Tout Puissant", identifier.Value);

                        // Remove the existing NameIdentifier claim and replace it
                        // with a new one containing a different value.
                        identity.RemoveClaim(identifier);
                        // Make sure to use a different name identifier
                        // than the one defined by BlobTokenValidator.
                        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Bob le Magnifique"));

                        return Task.FromResult<object>(null);
                    }
                }
            };
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(new BlobTokenValidator(options.AuthenticationScheme));
            var server = CreateServer(options);

            var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
            Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode);
            Assert.Equal("Bob le Magnifique", response.ResponseText);
        }
 public AuthenticationFailedContext(HttpContext context, JwtBearerOptions options)
     : base(context, options)
 {
 }
Beispiel #28
0
        public async Task InvalidTokenReceived()
        {
            var options = new JwtBearerOptions
            {
                AutomaticAuthenticate = true
            };
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(new InvalidTokenValidator());
            var server = CreateServer(options);

            var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob");
            Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode);
            Assert.Equal("", response.ResponseText);
        }