Solarion
Honorary Master
- Joined
- Nov 14, 2012
- Messages
- 28,051
- Reaction score
- 17,804
I've been working on setting up and MVC project which calls an API.
So far so good, everything has been working up till now but I've hit a snag implementing authorization. This is the JWT I get back from the API on Login. It's the usual crazy long string which translates to this.
This is the middleware I have set up. The secret is the same as on the API project.
And this is in my AccountController
On my Employee controller I have the following at the top:
What is happening is the Employee controller is simply returning a blank page. If I remove the authorize attribute above, the page works. This says to me that it is not reading the Admin role from the token.
Can someone please tell me where I have gone wrong? Been staring at this thing for a while now and would really appreciate some feedback.
So far so good, everything has been working up till now but I've hit a snag implementing authorization. This is the JWT I get back from the API on Login. It's the usual crazy long string which translates to this.
Code:
{
"sub": "[email protected]",
"jti": "871853ae-95a3-4e57-9b51-d5043dc812f7",
"email": "[email protected]",
"id": "480b621b-f55c-43ad-b4d9-2734042b237d",
"role": "Admin",
"nbf": 1618694272,
"exp": 1618694572,
"iat": 1618694272
}
This is the middleware I have set up. The secret is the same as on the API project.
C#:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var signingKey = Encoding.ASCII.GetBytes(jwtSettings.Secret);
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(signingKey)
};
});
C#:
app.UseAuthentication();
And this is in my AccountController
C#:
// api/v1/identity/login
[HttpPost]
public async Task<ActionResult> Login(SignIn signIn)
{
var response = await _serviceClient.LoginUserAsync(_jwtSettings.WebServiceURL + ApiRoutes.Identity.Login, signIn.Email, signIn.Password);
var responseMessage = response.StatusCode;
if(responseMessage != HttpStatusCode.OK)
{
return Redirect("~/Account/Login");
}
return Redirect("~/Employee/Index");
}
On my Employee controller I have the following at the top:
C#:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles ="Admin")]
public class EmployeesController : Controller
{
.
.
.
.
What is happening is the Employee controller is simply returning a blank page. If I remove the authorize attribute above, the page works. This says to me that it is not reading the Admin role from the token.
Can someone please tell me where I have gone wrong? Been staring at this thing for a while now and would really appreciate some feedback.