New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example for how to configure CookieAuthentication in ASP.NET Core 2 Preview #1219

Closed
RickStrahl opened this Issue May 14, 2017 · 23 comments

Comments

Projects
None yet
9 participants
@RickStrahl

RickStrahl commented May 14, 2017

Is there an example somewhere on how to configure Cookie Authenticaiton in the preview?

The old configuration mentioned in the documentation now breaks, and so is no longer valid.

Any examples on how to configure Cookie authentication would be useful. In the meantime app's broken which is kind of sad given that this was working and now fails with a hard compiler error.

@davidfowl

This comment has been minimized.

Show comment
Hide comment
@davidfowl

davidfowl May 14, 2017

Member

services.AddCookieAuthentication();
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();

Member

davidfowl commented May 14, 2017

services.AddCookieAuthentication();
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();

@davidfowl

This comment has been minimized.

Show comment
Hide comment
@davidfowl

davidfowl May 14, 2017

Member

The gist of the changes are that things were moved from middleware into services.

Member

davidfowl commented May 14, 2017

The gist of the changes are that things were moved from middleware into services.

@damienbod

This comment has been minimized.

Show comment
Hide comment
@damienbod

This comment has been minimized.

Show comment
Hide comment
@damienbod

damienbod May 14, 2017

Hi @Tratcher

The new way is more complicated than before. Why was this changed?

Greetings Damien

damienbod commented May 14, 2017

Hi @Tratcher

The new way is more complicated than before. Why was this changed?

Greetings Damien

@HaoK

This comment has been minimized.

Show comment
Hide comment
@HaoK

HaoK May 14, 2017

Member

The startup changes for any individual auth aren't really that different except that they have moved to ConfigureServices as opposed to Configuring a middleware. You can see aspnet/Announcements#232 for more details.

The main things that are different in startup is moving the concept of AutomaticChallenge/Authenticate out of each options into a shared place eliminating the possibility of multiple auth setting these flags, and having only a single UseAuthentication() middleware.

Member

HaoK commented May 14, 2017

The startup changes for any individual auth aren't really that different except that they have moved to ConfigureServices as opposed to Configuring a middleware. You can see aspnet/Announcements#232 for more details.

The main things that are different in startup is moving the concept of AutomaticChallenge/Authenticate out of each options into a shared place eliminating the possibility of multiple auth setting these flags, and having only a single UseAuthentication() middleware.

@RickStrahl

This comment has been minimized.

Show comment
Hide comment
@RickStrahl

RickStrahl May 14, 2017

Thanks for some of the links but neither of those show how to set specific values for the cookie authentication.

My old code used this to specify custom login path:

    app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = false,
                LoginPath = "/api/login"
            });

I can't find the place (or whatever replaced them) where I can apply these options.

RickStrahl commented May 14, 2017

Thanks for some of the links but neither of those show how to set specific values for the cookie authentication.

My old code used this to specify custom login path:

    app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = false,
                LoginPath = "/api/login"
            });

I can't find the place (or whatever replaced them) where I can apply these options.

@HaoK

This comment has been minimized.

Show comment
Hide comment
@HaoK

HaoK May 14, 2017

Member
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCookieAuthentication(o => o.LoginPath = "/api/login");
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseAuthentication();
        }
Member

HaoK commented May 14, 2017

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCookieAuthentication(o => o.LoginPath = "/api/login");
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseAuthentication();
        }
@RickStrahl

This comment has been minimized.

Show comment
Hide comment
@RickStrahl

RickStrahl May 14, 2017

Aaargh - yes thank you. This is a case where Visual Studio Intellisense didn't show the AddCookieAuthenitcation() and tried working off AddAuthentication() only which didn't have the right settings to set.

This gets me a little further:

public void ConfigureServices(IServiceCollection services)
{
	services.AddCookieAuthentication(o =>
    {
		o.LoginPath = "/api/login";
		o.LogoutPath = "/api/logout";				
    });
}

and app.UseAuthentication() in Configure().

However this gets me:

No authentication handler is configured to handle the scheme: Cookies

So there's something else missing here.

+++ Rick ---

RickStrahl commented May 14, 2017

Aaargh - yes thank you. This is a case where Visual Studio Intellisense didn't show the AddCookieAuthenitcation() and tried working off AddAuthentication() only which didn't have the right settings to set.

This gets me a little further:

public void ConfigureServices(IServiceCollection services)
{
	services.AddCookieAuthentication(o =>
    {
		o.LoginPath = "/api/login";
		o.LogoutPath = "/api/logout";				
    });
}

and app.UseAuthentication() in Configure().

However this gets me:

No authentication handler is configured to handle the scheme: Cookies

So there's something else missing here.

+++ Rick ---

@Tratcher

This comment has been minimized.

Show comment
Hide comment
@Tratcher

Tratcher May 14, 2017

Member

Stack trace? The calling methods also changed. See the announcement.

Member

Tratcher commented May 14, 2017

Stack trace? The calling methods also changed. See the announcement.

@RickStrahl

This comment has been minimized.

Show comment
Hide comment
@RickStrahl

RickStrahl May 14, 2017

The announcement doesn't give much info. I can't figure out what this is trying to say:

   context.Authenticate|Challenge|SignInAsync("scheme"); // Calls 2.0 auth stack

Here's what I have in my existing auth method that works in 1.1:

        [AllowAnonymous]                    
        [HttpPost]
        [Route("api/login")]
        public async Task<bool> Login([FromBody]  User loginUser)
        {            
            var user = await accountRepo.AuthenticateAndLoadUser(loginUser.Username, loginUser.Password);
            if (user == null)
                throw new ApiException("Invalid Login Credentials", 401);

            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, user.Username))    ;
           
            if (user.Fullname == null)
                user.Fullname = string.Empty;
            identity.AddClaim(new Claim("FullName", user.Fullname));

			await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(identity));

            return true;
        }

Stacktrace:

Application started. Press Ctrl+C to shut down.
fail: AlbumViewerAspNetCore.ApiExceptionFilter[0]
      No authentication handler is configured to handle the scheme: Cookies
System.InvalidOperationException: No authentication handler is configured to handle the scheme: Cookies
   at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.<SignInAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AlbumViewerAspNetCore.AccountController.<Login>d__2.MoveNext() in C:\projects2010\AlbumViewerVNext\src\AlbumViewerNetCore\Controllers\AccountController.cs:line 43
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ObjectMethodExecutor.<CastToObject>d__38`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextExceptionFilterAsync>d__15.MoveNext()

I also tried this in addition to AddCookieAuthentication() in ConfigureServices():

services.AddAuthentication(o =>
			{
				o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
			});

but no luck. Something is still missing?

RickStrahl commented May 14, 2017

The announcement doesn't give much info. I can't figure out what this is trying to say:

   context.Authenticate|Challenge|SignInAsync("scheme"); // Calls 2.0 auth stack

Here's what I have in my existing auth method that works in 1.1:

        [AllowAnonymous]                    
        [HttpPost]
        [Route("api/login")]
        public async Task<bool> Login([FromBody]  User loginUser)
        {            
            var user = await accountRepo.AuthenticateAndLoadUser(loginUser.Username, loginUser.Password);
            if (user == null)
                throw new ApiException("Invalid Login Credentials", 401);

            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, user.Username))    ;
           
            if (user.Fullname == null)
                user.Fullname = string.Empty;
            identity.AddClaim(new Claim("FullName", user.Fullname));

			await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(identity));

            return true;
        }

Stacktrace:

Application started. Press Ctrl+C to shut down.
fail: AlbumViewerAspNetCore.ApiExceptionFilter[0]
      No authentication handler is configured to handle the scheme: Cookies
System.InvalidOperationException: No authentication handler is configured to handle the scheme: Cookies
   at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.<SignInAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at AlbumViewerAspNetCore.AccountController.<Login>d__2.MoveNext() in C:\projects2010\AlbumViewerVNext\src\AlbumViewerNetCore\Controllers\AccountController.cs:line 43
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ObjectMethodExecutor.<CastToObject>d__38`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextExceptionFilterAsync>d__15.MoveNext()

I also tried this in addition to AddCookieAuthentication() in ConfigureServices():

services.AddAuthentication(o =>
			{
				o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
			});

but no luck. Something is still missing?

@HaoK

This comment has been minimized.

Show comment
Hide comment
@HaoK

HaoK May 14, 2017

Member
Member

HaoK commented May 14, 2017

@RickStrahl

This comment has been minimized.

Show comment
Hide comment
@RickStrahl

RickStrahl May 15, 2017

I'm not sure what you're saying? What do you mean drop the authentication? I have an API that needs to create a signin cookie.

Are you saying this isn't implemented in this preview?

IOW I'm not using Identity just raw auth cookies which is perfect for this particular application.

RickStrahl commented May 15, 2017

I'm not sure what you're saying? What do you mean drop the authentication? I have an API that needs to create a signin cookie.

Are you saying this isn't implemented in this preview?

IOW I'm not using Identity just raw auth cookies which is perfect for this particular application.

@dotnetchris

This comment has been minimized.

Show comment
Hide comment
@dotnetchris

dotnetchris May 15, 2017

The authentication system of ASP.NET CORE is nightmarishly over-engineered.

What in the world happened to the simplicity of override the Authorize method that used to exist in ASP.NET MVC?

I get that Microsoft is trying to do everything possible to eliminate people from rolling their own auth by making it pretty much impossible to roll your own, but that one size fits all is a very naive end product. Especially when Identity and the schema/models it uses is almost wholly wrong IMO. My view of identity is vastly different than most people, I shouldn't have to bother trying to convince anyone, I should just be able to easily implement my own. Implementing my own identity in Core was literally one of the hardest things I've ever done in my entire programming career.

I feel like we've taken multiple steps backwards. Easily since 2006 one of the chores of .NET has always been rip out all of the membership and identity stuff and roll your own on top of FormsAuthentication (ensure properly cookie protection). Now Identity is even worse than the Membership stuff.

Crazy and very sad at the same time.

dotnetchris commented May 15, 2017

The authentication system of ASP.NET CORE is nightmarishly over-engineered.

What in the world happened to the simplicity of override the Authorize method that used to exist in ASP.NET MVC?

I get that Microsoft is trying to do everything possible to eliminate people from rolling their own auth by making it pretty much impossible to roll your own, but that one size fits all is a very naive end product. Especially when Identity and the schema/models it uses is almost wholly wrong IMO. My view of identity is vastly different than most people, I shouldn't have to bother trying to convince anyone, I should just be able to easily implement my own. Implementing my own identity in Core was literally one of the hardest things I've ever done in my entire programming career.

I feel like we've taken multiple steps backwards. Easily since 2006 one of the chores of .NET has always been rip out all of the membership and identity stuff and roll your own on top of FormsAuthentication (ensure properly cookie protection). Now Identity is even worse than the Membership stuff.

Crazy and very sad at the same time.

@HaoK

This comment has been minimized.

Show comment
Hide comment
@HaoK

HaoK May 15, 2017

Member

@RickStrahl I mean you need to call httpContext.SignInAsync instead to call the 2.0 authentication stack.

Member

HaoK commented May 15, 2017

@RickStrahl I mean you need to call httpContext.SignInAsync instead to call the 2.0 authentication stack.

@RickStrahl

This comment has been minimized.

Show comment
Hide comment
@RickStrahl

RickStrahl May 15, 2017

LOL! Sure enough that's it!

Miscommunication. So this now works:

		[AllowAnonymous]                    
		[HttpPost]
		[Route("api/login")]
		public async Task<bool> Login([FromBody]  User loginUser)
		{            
			var user = await accountRepo.AuthenticateAndLoadUser(loginUser.Username, loginUser.Password);
			if (user == null)
				throw new ApiException("Invalid Login Credentials", 401);

			var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
			identity.AddClaim(new Claim(ClaimTypes.Name, user.Username))    ;
           
			if (user.Fullname == null)
				user.Fullname = string.Empty;
			identity.AddClaim(new Claim("FullName", user.Fullname));

			
			//context.Authenticate | Challenge | SignInAsync("scheme"); // Calls 2.0 auth stack
			
			await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
				new ClaimsPrincipal(identity));

			return true;
		}

I'll write that up tonight for my own sanity.

Thank you.

RickStrahl commented May 15, 2017

LOL! Sure enough that's it!

Miscommunication. So this now works:

		[AllowAnonymous]                    
		[HttpPost]
		[Route("api/login")]
		public async Task<bool> Login([FromBody]  User loginUser)
		{            
			var user = await accountRepo.AuthenticateAndLoadUser(loginUser.Username, loginUser.Password);
			if (user == null)
				throw new ApiException("Invalid Login Credentials", 401);

			var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
			identity.AddClaim(new Claim(ClaimTypes.Name, user.Username))    ;
           
			if (user.Fullname == null)
				user.Fullname = string.Empty;
			identity.AddClaim(new Claim("FullName", user.Fullname));

			
			//context.Authenticate | Challenge | SignInAsync("scheme"); // Calls 2.0 auth stack
			
			await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
				new ClaimsPrincipal(identity));

			return true;
		}

I'll write that up tonight for my own sanity.

Thank you.

@RickStrahl RickStrahl closed this May 15, 2017

@RickStrahl

This comment has been minimized.

Show comment
Hide comment
@RickStrahl

RickStrahl May 15, 2017

@dotnetchris It doesn't have to be all difficult. The code I use here is an example of a very simple auth implementation that's no more complicated than Forms Auth in classic ASP.NET. You still need the config stuff, but the new config that's mentioned here is actually less than 10 lines of code, so not exactly difficult.

I do agree if you go full bore with the entire identity system then things are a lot more complicated. But if you just need to do the auth and let a backend application deal with customer/user mapping (as is usually the case anyway), it's not that difficult to make that happen.

RickStrahl commented May 15, 2017

@dotnetchris It doesn't have to be all difficult. The code I use here is an example of a very simple auth implementation that's no more complicated than Forms Auth in classic ASP.NET. You still need the config stuff, but the new config that's mentioned here is actually less than 10 lines of code, so not exactly difficult.

I do agree if you go full bore with the entire identity system then things are a lot more complicated. But if you just need to do the auth and let a backend application deal with customer/user mapping (as is usually the case anyway), it's not that difficult to make that happen.

@mikeball

This comment has been minimized.

Show comment
Hide comment
@mikeball

mikeball Aug 27, 2017

@dotnetchris completely agree with you after battling this new stuff for an entire week in an attempt to get something running that was trivial in forms auth. And it's still now working.

mikeball commented Aug 27, 2017

@dotnetchris completely agree with you after battling this new stuff for an entire week in an attempt to get something running that was trivial in forms auth. And it's still now working.

@plsft

This comment has been minimized.

Show comment
Hide comment
@plsft

plsft Oct 17, 2017

AddCookieAuthentication() doesn't seem to work for me. I thought i added the correct packages. any thoughts? gettting:

InvalidOperationException: No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Cookies

with following code:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthorization(o =>
        {
            o.AddPolicy("Users", p => p.RequireClaim("Users"));
            o.AddPolicy("SuperUsers", p => p.RequireClaim("SuperUsers"));
            o.AddPolicy("PlatformUsers", p => p.RequireClaim("PlatformUsers"));
        });

        services.AddAuthentication(options =>
        {
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie("Cookieauth", options =>
        {
            options.LoginPath = new PathString("/login");
            options.AccessDeniedPath = new PathString("/error?unauth");
        });



        services.AddMvc();
    }

plsft commented Oct 17, 2017

AddCookieAuthentication() doesn't seem to work for me. I thought i added the correct packages. any thoughts? gettting:

InvalidOperationException: No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Cookies

with following code:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthorization(o =>
        {
            o.AddPolicy("Users", p => p.RequireClaim("Users"));
            o.AddPolicy("SuperUsers", p => p.RequireClaim("SuperUsers"));
            o.AddPolicy("PlatformUsers", p => p.RequireClaim("PlatformUsers"));
        });

        services.AddAuthentication(options =>
        {
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie("Cookieauth", options =>
        {
            options.LoginPath = new PathString("/login");
            options.AccessDeniedPath = new PathString("/error?unauth");
        });



        services.AddMvc();
    }
@Tratcher

This comment has been minimized.

Show comment
Hide comment
@Tratcher

Tratcher Oct 17, 2017

Member

Your scheme names don't match. That should be

        services.AddAuthentication("Cookieauth")
        .AddCookie("Cookieauth", options =>
        {
            options.LoginPath = new PathString("/login");
            options.AccessDeniedPath = new PathString("/error?unauth");
        });
Member

Tratcher commented Oct 17, 2017

Your scheme names don't match. That should be

        services.AddAuthentication("Cookieauth")
        .AddCookie("Cookieauth", options =>
        {
            options.LoginPath = new PathString("/login");
            options.AccessDeniedPath = new PathString("/error?unauth");
        });
@davidfowl

This comment has been minimized.

Show comment
Hide comment
@davidfowl

davidfowl Oct 20, 2017

Member

@Tratcher @HaoK can we list out the all registered schemes in the exception message?

Member

davidfowl commented Oct 20, 2017

@Tratcher @HaoK can we list out the all registered schemes in the exception message?

@Tratcher

This comment has been minimized.

Show comment
Hide comment
@Tratcher

Tratcher Oct 20, 2017

Member

It's possible, and may help people that keep mismatching their scheme names. #1502

Member

Tratcher commented Oct 20, 2017

It's possible, and may help people that keep mismatching their scheme names. #1502

@peirens-bart

This comment has been minimized.

Show comment
Hide comment
@peirens-bart

peirens-bart Feb 6, 2018

Hi
I know this topic is closed but I still have question where I can't find the answer for.
in core 1.1 I can do

app.UseCookieAuthentication(_cookieOptions);
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                Audience = ...,
                ClaimsIssuer = ...,
                AutomaticAuthenticate = true,
                RequireHttpsMetadata = !env.IsDevelopment(), 
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = ...,
                    ValidateAudience= true,
                    ValidAudience = ...,
                    RequireExpirationTime= false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(...))
                }
            });

when i create the cookie and de jwt token with the same claims, i can get the claims in a middelware from (httpContext.User.Identity as ClaimsIdentity).Claims

in core 2.0
I do this

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = <<AUTHENTICATIONSCHEME>>;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddCookie(<<AUTHENTICATIONSCHEME>>,options =>
            {
                options.LoginPath = new PathString("/Account/login");
                options.AccessDeniedPath = new PathString("/Account/login");
                options.LogoutPath = new PathString("/Account/Logoff");
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme,options =>
            {
                options.Audience = ...;
                options.ClaimsIssuer = ...;
                options.RequireHttpsMetadata = !_hostingEnvironment.IsDevelopment();
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = ...,
                    ValidateAudience = true,
                    ValidAudience = ..,
                    RequireExpirationTime = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(...))
                };
            });

in the middleware I can read the claims from the cookie but nor for the jwt token
the request I'm using is adding in the header Key:Authorization, value: bearer <>

can someone explain me why this was working in 1.1 and not in 2.0

Thanks

peirens-bart commented Feb 6, 2018

Hi
I know this topic is closed but I still have question where I can't find the answer for.
in core 1.1 I can do

app.UseCookieAuthentication(_cookieOptions);
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                Audience = ...,
                ClaimsIssuer = ...,
                AutomaticAuthenticate = true,
                RequireHttpsMetadata = !env.IsDevelopment(), 
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = ...,
                    ValidateAudience= true,
                    ValidAudience = ...,
                    RequireExpirationTime= false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(...))
                }
            });

when i create the cookie and de jwt token with the same claims, i can get the claims in a middelware from (httpContext.User.Identity as ClaimsIdentity).Claims

in core 2.0
I do this

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = <<AUTHENTICATIONSCHEME>>;
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddCookie(<<AUTHENTICATIONSCHEME>>,options =>
            {
                options.LoginPath = new PathString("/Account/login");
                options.AccessDeniedPath = new PathString("/Account/login");
                options.LogoutPath = new PathString("/Account/Logoff");
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme,options =>
            {
                options.Audience = ...;
                options.ClaimsIssuer = ...;
                options.RequireHttpsMetadata = !_hostingEnvironment.IsDevelopment();
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = ...,
                    ValidateAudience = true,
                    ValidAudience = ..,
                    RequireExpirationTime = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(...))
                };
            });

in the middleware I can read the claims from the cookie but nor for the jwt token
the request I'm using is adding in the header Key:Authorization, value: bearer <>

can someone explain me why this was working in 1.1 and not in 2.0

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment