none
How can implement Cookie base authentication and jwt in asp.net core 2.2? RRS feed

  • Question

  • hi,

    I want used both of cookie base authentication and jwt in my program, used authentication user to access mvc controller and jwt to access web api.

    public void ConfigureServices(IServiceCollection services)
            {
    
                
                services.Configure<CookiePolicyOptions>(options =>
                {
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                    options.ConsentCookie.Name = "Cookie";
                });
                services.ConfigureApplicationCookie(options =>
                {
                    options.Cookie.Name = "Cookie";
                    options.ClaimsIssuer = Configuration["Authentication:ClaimsIssuer"];
                });
    
                services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
    
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddIdentity<ApplicationUser, ApplicationRole>()
                    .AddEntityFrameworkStores<ApplicationDbContext>()
                    .AddDefaultUI(UIFramework.Bootstrap4)
                    .AddDefaultTokenProviders();
    
                services.Configure<IdentityOptions>(options =>
                {
                    // Password settings.
                    options.Password.RequireDigit = true;
                    options.Password.RequireLowercase = true;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = false;
                    options.Password.RequiredLength = 5;
                    options.Password.RequiredUniqueChars = 1;
    
                    // Lockout settings.
                    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                    options.Lockout.MaxFailedAccessAttempts = 5;
                    options.Lockout.AllowedForNewUsers = true;
    
                    // User settings.
                    options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                    options.User.RequireUniqueEmail = false;
    
                    //Token
                });
    
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    
                })
                    .AddCookie(options =>
                    {
                        options.Cookie.Name = "Cookie";
                        options.ClaimsIssuer = Configuration["Authentication:ClaimsIssuer"];
                    })
                    .AddMicrosoftAccount(microsoftOptions =>
                     {
                         microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
                         microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:Password"];
                     })
                    .AddGoogle(googleOptions => 
                    {
                        googleOptions.ClientId = "XXXXXXXXXXX.apps.googleusercontent.com";
                        googleOptions.ClientSecret = "g4GZ2#...GD5Gg1x";
                        googleOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
                        googleOptions.ClaimActions.MapJsonKey(ClaimTypes.Gender, "gender");
                        googleOptions.SaveTokens = true;
                        googleOptions.Events.OnCreatingTicket = ctx =>
                        {
                            List<AuthenticationToken> tokens = ctx.Properties.GetTokens()
                                as List<AuthenticationToken>;
                            tokens.Add(new AuthenticationToken()
                            {
                                Name = "TicketCreated",
                                Value = DateTime.UtcNow.ToString()
                            });
                            ctx.Properties.StoreTokens(tokens);
                            return Task.CompletedTask;
                        };
                    })
                    .AddJwtBearer(options =>
                    {
                        options.ClaimsIssuer = Configuration["Authentication:ClaimsIssuer"];
                        options.SaveToken = true;
                        options.Authority = Configuration["Authentication:Authority"];
                        options.Audience = Configuration["Authentication:Audience"];
                        options.RequireHttpsMetadata = false;
                        options.TokenValidationParameters = new TokenValidationParameters()
                        {
                            
                            ValidateIssuerSigningKey = true,
    
                            ValidateIssuer = true,
                            ValidIssuer = Configuration["Authentication:ValidIssuer"],
    
                            ValidateAudience = true,
                            ValidAudience = Configuration["Authentication:ValidAudience"],
                            
                            ValidateLifetime = true,
                            
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:SecurityKey"]))
                        };
                    });
    
    
    
    
    
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                services.AddSession();
    
                services.AddSingleton<IConfiguration>(Configuration);
                
            }
    [AllowAnonymous]
            [HttpPost]
            public async Task<IActionResult> GetToken(TokenLoginModel model)
            {
    
                if (!ModelState.IsValid) return BadRequest("Token failed to generate");
                var user = await _usermanager.FindByNameAsync(model.UserName);
                //var user = true;// (model.Password == "password" && model.Username == "username");
                if (user != null && await _usermanager.CheckPasswordAsync(user, model.Password))
                {
                    var claims = new[]{
                        new Claim("ClaimsIssuer", _configuration.GetSection("Authentication:ClaimsIssuer").Value),
                    new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Sub,user.UserName),
                    new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
                };
                    string SecurKey = Startup.StaticConfig.GetSection("Authentication:SecurityKey").Value;
                    var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecurKey));
                    var token = new JwtSecurityToken(
                        issuer: _configuration.GetSection("Authentication:ValidIssuer").Value,
                        audience: _configuration.GetSection("Authentication:Audience").Value,
                        expires: DateTime.UtcNow.AddDays(30),
                        claims: claims,
                        signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                    );
                    return Ok(new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo
                    });
                }
                return Unauthorized();
                
            }

    I implement control that create token but when I want try authorize with that I get this error:

    An unhandled exception occurred while processing the request.
    
    HttpRequestException: Response status code does not indicate success: 404 (Not Found).
    System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
    
    IOException: IDX20804: Unable to retrieve document from: 'https://localhost:44383/oauth2/default/.well-known/openid-configuration'.
    Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string address, CancellationToken cancel)
    
    InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://localhost:44383/oauth2/default/.well-known/openid-configuration'.
    Microsoft.IdentityModel.Protocols.ConfigurationManager<T>.GetConfigurationAsync(CancellationToken cancel)

    how can I used normal authenticate for web user and token authentication for web api?

    • Moved by CoolDadTx Monday, May 13, 2019 1:39 PM ASP.NET related
    Friday, May 10, 2019 5:17 PM

Answers

All replies

  • Hello,

    The best place for assistance is in the ASP.NET forums.

    https://forums.asp.net/


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Friday, May 10, 2019 6:17 PM
  • Hi Faraz Pourafshin,

    Thank you for posting here.

    Since this thread is related to asp.net core, you could post in the following forum.

    https://forums.asp.net/1255.aspx/1?ASP+NET+Core​​​​​​​

    The Visual C# forum discusses and asks questions about the C# programming language, IDE, libraries, samples, and tools.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, May 13, 2019 1:27 AM
  • When we use the Authorize attribute, it actually binds to the first authentication system by default. The [Authorize] attribute could specify the authentication scheme or schemes to use regardless of whether a default is configured. 

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [Route("/api/values")]
    public class ValuesController : Controller

    Refer to:

    Authorize with a specific scheme in ASP.NET Core

    https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2

    Monday, May 13, 2019 8:10 AM
  • When we use the Authorize attribute, it actually binds to the first authentication system by default. The [Authorize] attribute could specify the authentication scheme or schemes to use regardless of whether a default is configured. 

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [Route("/api/values")]
    public class ValuesController : Controller

    Refer to:

    Authorize with a specific scheme in ASP.NET Core

    https://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2


    This is of little benefit in the C# forum. Where it would be beneficial would be in the MVC and WebAPI forums in ASP.NET forums.
    Monday, May 13, 2019 8:53 AM