Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I get tokenKey from path https://localhost:7107/api/login And when i try to test token and get data from Path https://localhost:7107/api/Values
the token work good and data comes well
but when i remove token the data continue come and didn't tell me the I am UnAuthorized
i want if i remove token from Postman the data didn't come because I am UnAuthorized
I mean i can get data from path:<a href="https://localhost:7107/api/Values"> in token or without token I don't want that
I Create try to Secure my Api by JWT
i will explain what happen

What I have tried:

<pre>
In Class Program.cs
C#
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidIssuer = builder.Configuration["JWT:Issuer"],
        ValidAudience = builder.Configuration["JWT:Audience"],
        IssuerSigningKey=new SymmetricSecurityKey
        (Encoding.UTF8.GetBytes(builder.Configuration["JWT:Key"])),
        ValidateIssuer=true,
        ValidateAudience=true,
        ValidateLifetime=true,
        ValidateIssuerSigningKey=true

    };

});


app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}")
    .RequireAuthorization();

app.Run();


Two Controller Api
login
Values

in Controller login   
   [Route("api/[controller]")]
   [ApiController]
   public class loginController : ControllerBase
   {

       IConfiguration configuration;
       public loginController(IConfiguration configuration)
       {
           this.configuration = configuration;

       }

   
       [HttpPost]
       [AllowAnonymous]
       public IActionResult Post([FromBody] UserModel model)
       {
           try
           {
               var response = Unauthorized();

               UserModel myuser = Authorize(model);

               if (myuser != null)
               {
                   var token = GenerateToken(model);
                   return Ok(new{token=token});
               }
               return response;
           }
           catch (Exception ex)
           {

               throw ex;
           }



       }

       public string GenerateToken(UserModel user)


       {

           var SecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Key"]));
           var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
           var token = new JwtSecurityToken(configuration["JWT:Issuer"],
               configuration["JWT:Key"], null,
               expires: DateTime.Now.AddMinutes(2000),
               signingCredentials: credentials);

           return new JwtSecurityTokenHandler().WriteToken(token);


       }


       public UserModel Authorize(UserModel model)
       {
           try
           {
               if (model.UserName == "ah" && model.Password == "123")
               {
                  return new UserModel
                   {

                       UserName = "ah",
                       Email = "ab5221744@gmail.com"
                   };

               }

               return null;
           }
           catch (Exception ex)
           {

               throw ex;
           }


       }

Controller Values

  [Route("api/[controller]")]
  [ApiController]
  public class ValuesController : ControllerBase
  {
      // GET: api/<ValuesController>
      [HttpGet]
      public IEnumerable<string> Get()
      {
          return new string[] { "value1", "value2" };
      }

      // GET api/<ValuesController>/5
      [HttpGet("{id}")]
      public string Get(int id)
      {
          return "value";
      }

      // POST api/<ValuesController>
      [HttpPost]
      public void Post([FromBody] string value)
      {
      }

      // PUT api/<ValuesController>/5
      [HttpPut("{id}")]
      public void Put(int id, [FromBody] string value)
      {
      }

      // DELETE api/<ValuesController>/5
      [HttpDelete("{id}")]
      public void Delete(int id)
      {
      }
  }
Posted
Updated 20-Nov-23 8:06am
v2
Comments
Andre Oosthuizen 20-Nov-23 14:09pm    
Quote: i will explain what happen - You have not yet explained what happened, we cannot help until you do - what happens when you run the code, what errors do you get and what do they say? Based on your code there is no checks to run Authorization, so it seems all will pass anyway...
A Belal 20-Nov-23 14:21pm    
ok my best friend i will tell you , i get tokenKey from path https://localhost:7107/api/login And when i try to test token and get data from Path https://localhost:7107/api/Values
the token key work good and data comes well
but when i remove token the data continue come and didn't tell me that iam UnAuthorized
i want if i remove token from Postman the didn't come because Iam UnAuthorized

i mean when i remove token key from postman
i can't call data because i am not authorized
and infact that doesn't happen
i want to get token key from
path https://localhost:7107/api/login And when i try to test token and get data from Path https://localhost:7107/api/Values
in if i remove token key i Can't call data because iam not authorized


Ok, so first - to run some error checking outside of your app, clear your browser cache or any other caching mechanisms that might be storing the old token as this might become an issue.

I have converted your code to what I think might work, again, more information leads to an absolute solution... -
C#
[Route("api/[controller]")]
[ApiController]
public class loginController : ControllerBase
{
    //Your existing code...

    [HttpGet("token")]
    [AllowAnonymous]
    public IActionResult GetToken()
    {
        try
        {
            //Reading from a default user for token retrieval...
            var model = new UserModel { UserName = "ah", Password = "123" };
            var token = GenerateToken(model);
            return Ok(new { token = token });
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex.Message}");
        }
    }

    // Existing code...
}


Now you can make a 'GET' request to 'https://localhost:7107/api/login/token'. After obtaining the token, you can use it to make requests to your 'https://localhost:7107/api/Values' values -
HTTP
GET /api/Values
Authorization: Bearer <your_token_here>


The above is a shove in the right direction, you can see way more code than me to adjust this code to wotk for you.
 
Share this answer
 
Comments
A Belal 21-Nov-23 11:27am    
Controller named Values
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ValuesController : ControllerBase
{
// GET: api/<valuescontroller>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/<valuescontroller>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/<valuescontroller>
[HttpPost]
public void Post([FromBody] string value)
{
}

// PUT api/<valuescontroller>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/<valuescontroller>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}


Controller named login

[Route("api/[controller]")]
[ApiController]
public class loginController : ControllerBase
{

IConfiguration configuration;
public loginController(IConfiguration configuration)
{
this.configuration = configuration;

}



// GET: api/<login>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/<login>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/<login>

[HttpPost]
[AllowAnonymous]
public IActionResult Post([FromBody] UserModel model)
{
try
{
var response = Unauthorized();

UserModel myuser = Authorize(model);

if (myuser != null)
{
var token = GenerateToken(model);
return Ok(new{token=token});
}
return response;
}
catch (Exception ex)
{

throw ex;
}



}

public string GenerateToken(UserModel user)


{

var SecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Key"]));
var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(configuration["JWT:Issuer"],
configuration["JWT:Key"], null,
expires: DateTime.Now.AddMinutes(2000),
signingCredentials: credentials);

return new JwtSecurityTokenHandler().WriteToken(token);


}


public UserModel Authorize(UserModel model)
{
try
{
if (model.UserName == "ah" && model.Password == "123")
{
return new UserModel
{

UserName = "ah",
Email = "ab5221744@gmail.com"
};

}

return null;
}
catch (Exception ex)
{

throw ex;
}


}





// PUT api/<login>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/<login>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}


do you have any Notes
You have no [Authorize] attribute on your ValuesController or any of its actions. Unless you have some configuration that you haven't shown, all of those actions will allow anonymous callers.

Simple authorization in ASP.NET Core | Microsoft Learn[^]
 
Share this answer
 
Comments
A Belal 21-Nov-23 11:15am    
Richard Deeming, That's my Class Program.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidIssuer = builder.Configuration["JWT:Issuer"],
ValidAudience = builder.Configuration["JWT:Audience"],
IssuerSigningKey=new SymmetricSecurityKey
(Encoding.UTF8.GetBytes(builder.Configuration["JWT:Key"])),
ValidateIssuer=true,
ValidateAudience=true,
ValidateLifetime=true,
ValidateIssuerSigningKey=true

};

});



var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();



app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.RequireAuthorization();

app.Run();
Richard Deeming 21-Nov-23 11:17am    
Irrelevant; your actions are configured to allow anonymous access, which is why they aren't returning an "access denied" response when you omit the authorization header.

Add the [Authorize] attribute to your actions, your controller, or as a global filter. The MS documentation has plenty of examples.
A Belal 21-Nov-23 11:28am    
Controller named Values
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ValuesController : ControllerBase
{
// GET: api/<valuescontroller>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/<valuescontroller>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/<valuescontroller>
[HttpPost]
public void Post([FromBody] string value)
{
}

// PUT api/<valuescontroller>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/<valuescontroller>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}


Controller named login

[Route("api/[controller]")]
[ApiController]
public class loginController : ControllerBase
{

IConfiguration configuration;
public loginController(IConfiguration configuration)
{
this.configuration = configuration;

}



// GET: api/<login>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/<login>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/<login>

[HttpPost]
[AllowAnonymous]
public IActionResult Post([FromBody] UserModel model)
{
try
{
var response = Unauthorized();

UserModel myuser = Authorize(model);

if (myuser != null)
{
var token = GenerateToken(model);
return Ok(new{token=token});
}
return response;
}
catch (Exception ex)
{

throw ex;
}



}

public string GenerateToken(UserModel user)


{

var SecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Key"]));
var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(configuration["JWT:Issuer"],
configuration["JWT:Key"], null,
expires: DateTime.Now.AddMinutes(2000),
signingCredentials: credentials);

return new JwtSecurityTokenHandler().WriteToken(token);


}


public UserModel Authorize(UserModel model)
{
try
{
if (model.UserName == "ah" && model.Password == "123")
{
return new UserModel
{

UserName = "ah",
Email = "ab5221744@gmail.com"
};

}

return null;
}
catch (Exception ex)
{

throw ex;
}


}





// PUT api/<login>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/<login>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}


do you have any Notes
A Belal 21-Nov-23 11:21am    
i do that now new Error is
Online
02:48:44.055
GET https://localhost:7107/api/values
Error: connect ECONNREFUSED 127.0.0.1:7107
Request Headers
User-Agent: PostmanRuntime/7.35.0
Accept: */*
Postman-Token: f73459b3-a3ed-43bb-91c9-929a082bd90f
Host: localhost:7107
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
02:48:51.097
POST https://localhost:7107/api/login
Error: connect ECONNREFUSED 127.0.0.1:7107
Request Headers
Content-Type: application/json
User-Agent: PostmanRuntime/7.35.0
Accept: */*
Postman-Token: f64c27f0-331a-44d1-a5cf-d6512aff23d4
Host: localhost:7107
Accept-Encoding: gzip, deflate, br
Connection: keep-alive

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