C
C#4w ago
Salight

I got a Mvc and an a API project i want to use [Authorize] attribute in mvc is it possible?

How Could i do that i added the token validation parameters in the mvc project same as the api's i am using the api's login method it returns 200 but when i try to access to [Authorize] view it sends me 401 unauthorized i also set the access token to the httpcontext but i don't know how to make that authorized in the pages
9 Replies
Salight
SalightOP4w ago
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginRequesting UserModel)
{
//var loginResponse = await _apiClient.LoginAsync<LoginRequesting, LoginResponse>("https://localhost:5001/api/authentication/login", UserModel);
var obj= await _apiClient.AuthenticateUser(UserModel);
if (obj != null && obj.AccessToken.ToString() != "")
{

HttpContext.Session.SetString("AuthToken", obj.AccessToken);
HttpContext.Session.SetString("RefreshToken", obj.RefreshToken);
return RedirectToAction("Index", "Home");

}
else
{
HttpContext.Session.SetString("JWTToken", "");
HttpContext.Session.SetString("RefreshToken", "");
}
return View(obj);
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginRequesting UserModel)
{
//var loginResponse = await _apiClient.LoginAsync<LoginRequesting, LoginResponse>("https://localhost:5001/api/authentication/login", UserModel);
var obj= await _apiClient.AuthenticateUser(UserModel);
if (obj != null && obj.AccessToken.ToString() != "")
{

HttpContext.Session.SetString("AuthToken", obj.AccessToken);
HttpContext.Session.SetString("RefreshToken", obj.RefreshToken);
return RedirectToAction("Index", "Home");

}
else
{
HttpContext.Session.SetString("JWTToken", "");
HttpContext.Session.SetString("RefreshToken", "");
}
return View(obj);
public async Task<LoginResponse> AuthenticateUser(LoginRequesting userDetails)
{
HttpResponseMessage response = await _httpClient.PostAsJsonAsync("authentication/login", userDetails);
response.EnsureSuccessStatusCode();

var contents = await response.Content.ReadAsStringAsync();
var APIResponse = JsonConvert.DeserializeObject<LoginResponse>(contents);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", APIResponse.AccessToken);
return APIResponse;

}
public async Task<LoginResponse> AuthenticateUser(LoginRequesting userDetails)
{
HttpResponseMessage response = await _httpClient.PostAsJsonAsync("authentication/login", userDetails);
response.EnsureSuccessStatusCode();

var contents = await response.Content.ReadAsStringAsync();
var APIResponse = JsonConvert.DeserializeObject<LoginResponse>(contents);
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", APIResponse.AccessToken);
return APIResponse;

}
Unknown User
Unknown User4w ago
Message Not Public
Sign In & Join Server To View
Salight
SalightOP4w ago
what is the existing handler i am not aware of that
Unknown User
Unknown User4w ago
Message Not Public
Sign In & Join Server To View
Salight
SalightOP4w ago
i am using jwtbearer
public static void ConfigureJWT(this IServiceCollection services, IConfiguration
configuration)
{
var jwtConfiguration = new JwtConfiguration();
configuration.Bind(jwtConfiguration.Section, jwtConfiguration);
var secretKey = Environment.GetEnvironmentVariable("SECRET");
services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,

ValidIssuer = jwtConfiguration.ValidIssuer,
ValidAudience = jwtConfiguration.ValidAudience,
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine("Authentication failed: " + context.Exception.Message);
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine("Token validated: " + context.SecurityToken);
return Task.CompletedTask;
}
};
});
public static void ConfigureJWT(this IServiceCollection services, IConfiguration
configuration)
{
var jwtConfiguration = new JwtConfiguration();
configuration.Bind(jwtConfiguration.Section, jwtConfiguration);
var secretKey = Environment.GetEnvironmentVariable("SECRET");
services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,

ValidIssuer = jwtConfiguration.ValidIssuer,
ValidAudience = jwtConfiguration.ValidAudience,
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine("Authentication failed: " + context.Exception.Message);
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
Console.WriteLine("Token validated: " + context.SecurityToken);
return Task.CompletedTask;
}
};
});
like this
Unknown User
Unknown User4w ago
Message Not Public
Sign In & Join Server To View
Salight
SalightOP4w ago
context.Exception.Message = "IDX10208: Unable to validate audience. validationParameters.ValidAudience is null or whitespace and validationParameters.ValidAudiences is null."
context.Exception.Message = "IDX10208: Unable to validate audience. validationParameters.ValidAudience is null or whitespace and validationParameters.ValidAudiences is null."
this is my exception btw
Unknown User
Unknown User4w ago
Message Not Public
Sign In & Join Server To View
Salight
SalightOP4w ago
you mean audience it is not actually okay bro i solved you were right i was thinking i am getting the data from appsettings but i forget the add configure jwt settings service now it authorizes

Did you find this page helpful?