Commit b0cab96d authored by adnansetiawan's avatar adnansetiawan
Browse files

implement Api auth based on Role

parent 99720294
Pipeline #23993 passed with stages
in 6 minutes and 20 seconds
......@@ -39,6 +39,7 @@ namespace EasyParking.API.Controllers
/// </summary>
/// <returns></returns>
/// <response code="200">Returns All Users </response>
[Authorize(Roles = "Administrator")]
[HttpGet]
[ProducesResponseType(typeof(UserDetailDto[]), 200)]
public IActionResult Get()
......@@ -181,14 +182,21 @@ namespace EasyParking.API.Controllers
var jwtSecretKey = _configuration.GetSection("Jwt:SecretKey").Value;
// authentication successful so generate jwt token
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, loginRequest.Email)
};
var userExisting = _userService.GetUserByEmail(loginRequest.Email);
if (userExisting != null)
{
claims.Add(new Claim(ClaimTypes.Role, userExisting.UserRole.Name));
}
var subject = new ClaimsIdentity(claims);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(jwtSecretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Email, loginRequest.Email)
}),
Subject = subject,
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
......
......@@ -29,6 +29,6 @@
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.6.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.3" />
</ItemGroup>
</Project>
......@@ -18,7 +18,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
namespace EasyParking.API
{
public class Startup
......@@ -33,21 +34,6 @@ namespace EasyParking.API
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<EPDbContext>(options => options.UseSqlServer(connectionString));
services.AddScoped<ILocationRepository, LocationRepository>();
services.AddScoped<IZonaRepository, ZonaRepository>();
services.AddScoped<ISlotRepository, SlotRepository>();
services.AddScoped<IUserRoleRepository, UserRoleRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IParkingRepository, ParkingRepository>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IBookingRepository, BookingRepository>();
services.AddScoped<IRateRepository, RateRepository>();
services.AddControllers();
// configure jwt authentication
var jwtSecretKey = Configuration.GetSection("Jwt:SecretKey").Value;
var key = Encoding.ASCII.GetBytes(jwtSecretKey);
......@@ -64,15 +50,59 @@ namespace EasyParking.API
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true,
ValidateIssuer = false,
ValidateAudience = false
};
});
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<EPDbContext>(options => options.UseSqlServer(connectionString));
services.AddScoped<ILocationRepository, LocationRepository>();
services.AddScoped<IZonaRepository, ZonaRepository>();
services.AddScoped<ISlotRepository, SlotRepository>();
services.AddScoped<IUserRoleRepository, UserRoleRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IParkingRepository, ParkingRepository>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IBookingRepository, BookingRepository>();
services.AddScoped<IRateRepository, RateRepository>();
services.AddControllers();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("api", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "EasyParking API", Version = "v1" });
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description =
"JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML";
var commentsFile = Path.Combine(baseDirectory, commentsFileName);
......@@ -99,15 +129,17 @@ namespace EasyParking.API
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
}
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
app.UseRouting();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
......
......@@ -50,6 +50,13 @@ namespace EasyParking.Core
throw new Core.Exceptions.UserNotFoundExeption();
return user;
}
public User GetUserByEmail(string email)
{
var user = _userRepository.GetByEmail(email);
if (user == null)
throw new Core.Exceptions.UserNotFoundExeption();
return user;
}
public User Update(User user)
{
_userRepository.Update(user);
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment