diff options
author | branislav.radivojevic <wafflemynxyt@gmail.com> | 2022-10-27 21:56:19 +0200 |
---|---|---|
committer | branislav.radivojevic <wafflemynxyt@gmail.com> | 2022-10-27 21:56:19 +0200 |
commit | f7997bed82a22b91e4c6364bfb9f64679357f0d1 (patch) | |
tree | 9704b619696d539ae3cf6b475d580a5fc4586067 /Backend/Api | |
parent | cf00223fbf339757b3f1e5de144147eba9af3fa2 (diff) | |
parent | 8bfb37503f6af6dac4bf067337d851cedace1c67 (diff) |
Merge branch 'develop' of http://gitlab.pmf.kg.ac.rs/BrzoDoLokacije2022/odyssey/brzodolokacije into develop
Diffstat (limited to 'Backend/Api')
-rw-r--r-- | Backend/Api/Api/Api.csproj | 2 | ||||
-rw-r--r-- | Backend/Api/Api/Interfaces/IJwtService.cs | 12 | ||||
-rw-r--r-- | Backend/Api/Api/Interfaces/IUserService.cs | 1 | ||||
-rw-r--r-- | Backend/Api/Api/Program.cs | 25 | ||||
-rw-r--r-- | Backend/Api/Api/Services/JwtService.cs | 73 | ||||
-rw-r--r-- | Backend/Api/Api/Services/UserService.cs | 6 | ||||
-rw-r--r-- | Backend/Api/Api/appsettings.json | 28 |
7 files changed, 135 insertions, 12 deletions
diff --git a/Backend/Api/Api/Api.csproj b/Backend/Api/Api/Api.csproj index 91e0755..dc8b264 100644 --- a/Backend/Api/Api/Api.csproj +++ b/Backend/Api/Api/Api.csproj @@ -7,8 +7,10 @@ </PropertyGroup> <ItemGroup> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.10" /> <PackageReference Include="MongoDB.Driver" Version="2.18.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" /> + <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.24.0" /> </ItemGroup> </Project> diff --git a/Backend/Api/Api/Interfaces/IJwtService.cs b/Backend/Api/Api/Interfaces/IJwtService.cs new file mode 100644 index 0000000..35f5843 --- /dev/null +++ b/Backend/Api/Api/Interfaces/IJwtService.cs @@ -0,0 +1,12 @@ +using Api.Models; + +namespace Api.Interfaces +{ + public interface IJwtService + { + Task<string> GenToken(User user); + Task<string> TokenToId(string token); + Task<string> RenewToken(string existingToken); + + } +}
\ No newline at end of file diff --git a/Backend/Api/Api/Interfaces/IUserService.cs b/Backend/Api/Api/Interfaces/IUserService.cs index a2fa0a1..33c0889 100644 --- a/Backend/Api/Api/Interfaces/IUserService.cs +++ b/Backend/Api/Api/Interfaces/IUserService.cs @@ -10,5 +10,6 @@ namespace Api.Interfaces Task<User> getUserByUsername(String username); Task<long> updateUser(User user); Task<User> deleteUser(String email); + Task<User> getUserById(string id); } } diff --git a/Backend/Api/Api/Program.cs b/Backend/Api/Api/Program.cs index d00f39f..26ed445 100644 --- a/Backend/Api/Api/Program.cs +++ b/Backend/Api/Api/Program.cs @@ -1,7 +1,10 @@ +using System.Text; using Api.Database; using Api.Interfaces; using Api.Services; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; using MongoDB.Driver; var builder = WebApplication.CreateBuilder(args); @@ -18,6 +21,25 @@ builder.Services.AddSingleton<IMongoClient>(s => new MongoClient(builder.Configuration.GetValue<string>("DatabaseSettings:ConnectionString"))); builder.Services.AddScoped<IUserService, UserService>(); +builder.Services.AddScoped<IJwtService, JwtService>(); + + + + +//Add Authentication +builder.Services.AddAuthentication( + JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration.GetSection("AppSettings:JwtToken").Value)), + ValidateIssuer = false, + ValidateAudience = false + }; + + }); + + builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -46,6 +68,9 @@ if (app.Environment.IsDevelopment()) app.UseAuthorization(); +//Add Authentication +app.UseAuthentication(); + app.MapControllers(); app.Run(); diff --git a/Backend/Api/Api/Services/JwtService.cs b/Backend/Api/Api/Services/JwtService.cs new file mode 100644 index 0000000..a10f093 --- /dev/null +++ b/Backend/Api/Api/Services/JwtService.cs @@ -0,0 +1,73 @@ +using System.Data; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using System.Xml.Linq; +using Api.Interfaces; +using Api.Models; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; + +namespace Api.Services +{ + public class JwtService : IJwtService + { + private readonly IConfiguration _config; + private readonly IUserService _userService; + public JwtService(IConfiguration config,IUserService userService) + { + _config = config; + _userService = userService; + } + + public async Task<string> GenToken(User user) + { + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:JwtToken").Value); + var tokenDescriptor = new SecurityTokenDescriptor + { + Subject = new ClaimsIdentity(new[] { new Claim("id", user._id) }), + Expires = DateTime.UtcNow.AddDays(7), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) + }; + var token = tokenHandler.CreateToken(tokenDescriptor); + return tokenHandler.WriteToken(token); + } + public async Task<string> TokenToId(string token) + { + if (token == null) + return null; + var tokenHandler = new JwtSecurityTokenHandler(); + var key = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:JwtToken").Value); + try + { + tokenHandler.ValidateToken(token, new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(key), + ValidateIssuer = false, + ValidateAudience = false, + }, out SecurityToken validatedToken); + + var jwtToken = (JwtSecurityToken)validatedToken; + return jwtToken.Claims.First(x => x.Type == "id").Value; + } + catch + { + return null; + } + + } + + public async Task<string> RenewToken(string existingToken) + { + var id = await TokenToId(existingToken); + if (id == null) + return null; + var user = await _userService.getUserById(id); + + return await GenToken(user); + + } + } +} diff --git a/Backend/Api/Api/Services/UserService.cs b/Backend/Api/Api/Services/UserService.cs index fc582b5..2940d2e 100644 --- a/Backend/Api/Api/Services/UserService.cs +++ b/Backend/Api/Api/Services/UserService.cs @@ -45,6 +45,12 @@ namespace Api.Services return await _users.Find(_=>true).ToListAsync(); } + public async Task<User> getUserById(string id) + { + return await _users.Find(user => user._id == id).SingleAsync(); + + } + public async Task<long> updateUser(User user) { /* vraca broj izmenjenih korisnika diff --git a/Backend/Api/Api/appsettings.json b/Backend/Api/Api/appsettings.json index e02ac8d..7cc504d 100644 --- a/Backend/Api/Api/appsettings.json +++ b/Backend/Api/Api/appsettings.json @@ -1,16 +1,20 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "DatabaseSettings": { + "AppSettings": { + "JwtToken": "PjrVqQJ1P2VOkuWLw7NaZUluT4z7bkau" + }, + + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "DatabaseSettings": { - "ConnectionString": "mongodb://127.0.0.1:27017/", - "DatabaseName": "Odyssey", - "UserCollectionName": "users" + "ConnectionString": "mongodb://127.0.0.1:27017/", + "DatabaseName": "Odyssey", + "UserCollectionName": "users" - } + } } |