Click here to Skip to main content
15,076,465 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
as I am new to the .Net Core, I am facing the following issue

I have Authentication_API that returns JWT Token to the login controller at client side. After successfull login, I want to redirect to Home page. But when I use [Autherize] attribute to the controller it is not working. But without [Autherize] attribute it is displaying the home page.

Please help me how to solve this issue.
I think I am not saving the token in the header.

I was referencing the below API for JWT ,
http://jasonwatmore.com/post/2019/01/08/aspnet-core-22-role-based-authorization-tutorial-with-example-api

Here is my token generator
var tokenHandler = new JwtSecurityTokenHandler();
                   var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                   var tokenDescriptor = new SecurityTokenDescriptor
                   {
                       Subject = new ClaimsIdentity(new Claim[]
                       {
                               new Claim(ClaimTypes.Name, user.UserId.ToString()),
                               new Claim(ClaimTypes.Role,user.Role.RoleNameE.ToString())
                       }),
                       Expires = DateTime.UtcNow.AddDays(7),
                       SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                   };
                   var token = tokenHandler.CreateToken(tokenDescriptor);
                   var tokenString = tokenHandler.WriteToken(token);


After this point, I want to redirect to Home page

this is my Startup page

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


            // Add ASPNETCore DBContext services.
            services.AddDbContext<Tejoury_MSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DatabaseConnection")));

            // configure strongly typed settings objects : abdulla
            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            //--------------- configure jwt(JSON Web Tokens) authentication : abdulla --------------- 
            var appSettings = appSettingsSection.Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                        var userId = int.Parse(context.Principal.Identity.Name);
                        var user = userService.GetById(userId);
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return Task.CompletedTask;
                    }
                };
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
            //----------------------------------------------------------------------

            // configure DI for application services : Abdulla
            services.AddScoped<IUserService, UserService>();
            services.AddAuthorization(options =>
            {
                options.AddPolicy("RequireAdminRole",
                    authBuilder =>
                    { authBuilder.RequireRole("Admin"); });

            });

        }


What I have tried:

I want to implement JWT Authentication API in my client asp.net core applcaiton

this is the api I am using,

ASP.NET Core 2.2 - Role Based Authorization Tutorial with Example API | Jason Watmore's Blog[^]
Posted
Comments
Bohdan Stupak 20-Jan-19 11:28am
   
The controller codes and what exactly doesn't work would be helpful since the only guess from your code I have is that you have a typo in a word Authorize
Bryian Tan 20-Jan-19 16:31pm
   
Based on what you described, sound like the bearer token is not being validated. Try debug it by adding OnAuthenticationFailed

OnAuthenticationFailed = context =>
                    {
                        // Authentication failed
                       
                    }

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900