diff --git a/.gitignore b/.gitignore index 3b08958..e035641 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,9 @@ ################################################################################ /.vs/Icarus +/bin/* /bin/Debug/netcoreapp2.2 /Migrations /obj +/obj/* +/Icarus.txt diff --git a/Certs/Signing.cs b/Certs/Signing.cs new file mode 100644 index 0000000..55bfc8e --- /dev/null +++ b/Certs/Signing.cs @@ -0,0 +1,80 @@ +using System; +using System.Security.Cryptography; + +using Microsoft.IdentityModel.Tokens; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.OpenSsl; + + +namespace Icarus.Certs +{ + public class SigningIssuerCertificate : IDisposable + { + private readonly RSACryptoServiceProvider _rsa; + + public SigningIssuerCertificate() + { + _rsa = new RSACryptoServiceProvider(); + } + + public RsaSecurityKey GetIssuerSigningKey(string publicKeyPath) + { + var file = publicKeyPath; + var publicKey = System.IO.File.ReadAllText(file); + + using (var reader = System.IO.File.OpenText(file)) + { + var pem = new PemReader(reader); + var o = (RsaKeyParameters)pem.ReadObject(); + var parameters = new RSAParameters(); + parameters.Modulus = o.Modulus.ToByteArray(); + parameters.Exponent = o.Exponent.ToByteArray(); + _rsa.ImportParameters(parameters); + } + + return new RsaSecurityKey(_rsa); + } + + + public void Dispose() + { + _rsa?.Dispose(); + } + } + + + public class SigningAudienceCertificate : IDisposable + { + private readonly RSACryptoServiceProvider _rsa; + + public SigningAudienceCertificate() + { + _rsa = new RSACryptoServiceProvider(); + } + + public SigningCredentials GetAudienceSigningKey(string keyPath) + { + var file = keyPath; + var publicKey = System.IO.File.ReadAllText(file); + + using (var reader = System.IO.File.OpenText(file)) + { + var pem = new PemReader(reader); + var o = (RsaKeyParameters)pem.ReadObject(); + var parameters = new RSAParameters(); + parameters.Modulus = o.Modulus.ToByteArray(); + parameters.Exponent = o.Exponent.ToByteArray(); + _rsa.ImportParameters(parameters); + } + + return new SigningCredentials( + key: new RsaSecurityKey(_rsa), + algorithm: SecurityAlgorithms.RsaSha256); + } + + public void Dispose() + { + _rsa?.Dispose(); + } + } +} \ No newline at end of file diff --git a/Controllers/Managers/SongManager.cs b/Controllers/Managers/SongManager.cs index 96e0c20..500b50b 100644 --- a/Controllers/Managers/SongManager.cs +++ b/Controllers/Managers/SongManager.cs @@ -180,23 +180,30 @@ namespace Icarus.Controllers.Managers DirectoryManager dirMgr = new DirectoryManager(_config, song); dirMgr.CreateDirectory(); - var filePath = dirMgr.SongDirectory; - filePath += $"{song.Filename}"; + var tempPath = song.SongPath(); + song.Filename = song.GenerateFilename(1); + var filePath = $"{dirMgr.SongDirectory}{song.Filename}"; _logger.Info($"Absolute song path: {filePath}"); - using (var fileStream = new FileStream(filePath, FileMode.Create)) + await Task.Run(() => { - var songBytes = await System.IO.File.ReadAllBytesAsync(song.SongPath()); + using (var fileStream = new FileStream(filePath, FileMode.Create)) + { + var songBytes = System.IO.File.ReadAllBytes(tempPath); - System.IO.File.WriteAllBytesAsync(filePath, songBytes); - System.IO.File.Delete(song.SongPath()); + _logger.Info("Saving song to the filesystem"); + fileStream.Write(songBytes, 0, songBytes.Count()); - song.SongDirectory = dirMgr.SongDirectory; + System.IO.File.Delete(tempPath); + _logger.Info("Deleting temp file"); - _logger.Info("Song successfully saved to filesystem"); - } + _logger.Info("Song successfully saved to filesystem"); + } + }); + + song.SongDirectory = dirMgr.SongDirectory; var coverMgr = new CoverArtManager(_config); var coverArt = coverMgr.SaveCoverArt(song); @@ -211,51 +218,74 @@ namespace Icarus.Controllers.Managers } } - public async Task SaveSongToFileSystem(IFormFile songFile, IFormFile coverArtData, Song song) + public void SaveSongToFileSystem(IFormFile songFile, IFormFile coverArtData, Song song) { + song.SongDirectory = _tempDirectoryRoot; + song.DateCreated = DateTime.Now; + if (string.IsNullOrEmpty(song.Filename)) { song.Filename = song.GenerateFilename(1); } - song.SongDirectory = _tempDirectoryRoot; - song.DateCreated = DateTime.Now; + _logger.Info($"Temporary directory: {_tempDirectoryRoot}"); - using (var filestream = new FileStream(song.SongPath(), FileMode.Create)) + var tempPath = song.SongPath(); + + _logger.Info("Temporary song path: {0}", tempPath); + + using (var filestream = new FileStream(tempPath, FileMode.Create)) { _logger.Info("Saving song to temporary directory"); - await songFile.CopyToAsync(filestream); + songFile.CopyTo(filestream); } var coverMgr = new CoverArtManager(_config); - var coverArt = coverMgr.SaveCoverArt(coverArtData, song); - var meta = new MetadataRetriever(); + var coverArt = coverMgr.SaveCoverArt(coverArtData, song); + meta.UpdateCoverArt(song, coverArt); song.Duration = meta.RetrieveSongDuration(song.SongPath()); meta.UpdateMetadata(song, song); - meta.UpdateCoverArt(song, coverArt); + DirectoryManager dirMgr = new DirectoryManager(_config, song); dirMgr.CreateDirectory(); - var filePath = dirMgr.SongDirectory + song.Filename; + song.SongDirectory = dirMgr.SongDirectory; + var filePath = song.SongPath(); _logger.Info($"Absolute song path: {filePath}"); - using (var fileStream = new FileStream(filePath, FileMode.Create)) { - var songBytes = await System.IO.File.ReadAllBytesAsync(song.SongPath()); + var songBytes = System.IO.File.ReadAllBytes(tempPath); - await System.IO.File.WriteAllBytesAsync(filePath, songBytes); - System.IO.File.Delete(song.SongPath()); - song.SongDirectory = dirMgr.SongDirectory; + try + { + if (System.IO.File.Exists(filePath) && System.IO.File.Exists(tempPath) && fileStream.Length > 0) + { + System.IO.File.Delete(tempPath); + _logger.Info("Deleted temp song from filesystem: {0}", tempPath); + } + else + { + fileStream.Write(songBytes, 0, songBytes.Count()); + _logger.Info("Saved song to filesystem: {0}", filePath); + + System.IO.File.Delete(tempPath); + _logger.Info("Deleted temp song from filesystem: {0}", tempPath); + } + } + catch (Exception ex) + { + var msg = ex.Message; + _logger.Error($"An error occurred: {msg}"); + } _logger.Info("Song successfully saved to filesystem"); } - coverMgr.SaveCoverArtToDatabase(ref song, ref coverArt); SaveSongToDatabase(song); } @@ -296,20 +326,23 @@ namespace Icarus.Controllers.Managers var song = new Song(); _logger.Info("Assigning song filename"); song.SongDirectory = _tempDirectoryRoot; - song.Filename = song.GenerateFilename(1); + var filename = song.GenerateFilename(1); + song.Filename = filename; using (var filestream = new FileStream(song.SongPath(), FileMode.Create)) { - _logger.Info("Saving song to temporary directory"); + _logger.Info("Saving temp song: {0}", song.SongPath()); await songFile.CopyToAsync(filestream); } - - MetadataRetriever meta = new MetadataRetriever(); - song = meta.RetrieveMetaData(song.SongPath()); + await Task.Run(() => + { + MetadataRetriever meta = new MetadataRetriever(); + song = meta.RetrieveMetaData(song.SongPath()); + }); song.SongDirectory = _tempDirectoryRoot; - song.Filename = song.GenerateFilename(1); song.DateCreated = DateTime.Now; + song.Filename = filename; return song; } diff --git a/Controllers/Managers/TokenManager.cs b/Controllers/Managers/TokenManager.cs index 4dbd878..4f819de 100644 --- a/Controllers/Managers/TokenManager.cs +++ b/Controllers/Managers/TokenManager.cs @@ -1,20 +1,39 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Threading.Tasks; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using JWT; +using JWT.Serializers; using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Security; + using RestSharp; using Icarus.Models; namespace Icarus.Controllers.Managers { + #region Classes public class TokenManager : BaseManager { #region Fields private string _clientId; private string _clientSecret; + private string _privateKeyPath; + private string _privateKey; + private string _publicKeyPath; + private string _publicKey; private string _audience; private string _grantType; private string _url; @@ -58,7 +77,7 @@ namespace Icarus.Controllers.Managers _logger.Info("Deserializing response"); var tokenResult = JsonConvert - .DeserializeObject(response.Content); + .DeserializeObject(response.Content); _logger.Info("Response deserialized"); return new LoginResult @@ -68,6 +87,259 @@ namespace Icarus.Controllers.Managers Message = "Successfully retrieved token" }; } + + + public LoginResult LogIn(User user) + { + var tokenResult = new TokenTierOne(); + tokenResult.TokenType = "Jwt"; + + var privateKey = ReadKeyContent(_privateKeyPath).Result; + var publicKey = ReadKeyContent(_publicKeyPath).Result; + + var payload = Payload(); + + var token = CreateToken(payload, privateKey); + tokenResult.AccessToken = token; + + var expClaim = payload.FirstOrDefault(cl => + { + return cl.Type.Equals("exp"); + }); + + tokenResult.Expiration = System.Convert.ToInt32(expClaim.Value); + + return new LoginResult + { + UserID = user.UserID, Username = user.Username, Token = tokenResult.AccessToken, + TokenType = tokenResult.TokenType, Expiration = tokenResult.Expiration, + Message = "Successfully retrieved token" + }; + } + + public LoginResult LoginSymmetric(User user) + { + var tokenResult = new TokenTierOne(); + tokenResult.TokenType = "Jwt"; + + var payload = Payload(); + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JWT:Secret"])); + var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + var token = new JwtSecurityToken( + _config["JWT:Issuer"], + _config["JWT:Audience"], + payload, + expires: DateTime.UtcNow.AddMinutes(30), + signingCredentials: signIn); + + tokenResult.AccessToken = new JwtSecurityTokenHandler().WriteToken(token); + + var expClaim = payload.FirstOrDefault(cl => + { + return cl.Type.Equals("exp"); + }); + + var expiredDate = DateTime.Parse(expClaim.Value); + var exp = Math.Floor((expiredDate - DateTime.UnixEpoch).TotalSeconds); + tokenResult.Expiration = Convert.ToInt32(exp); + + return new LoginResult + { + UserID = user.UserID, Username = user.Username, Token = tokenResult.AccessToken, + TokenType = tokenResult.TokenType, Expiration = tokenResult.Expiration, + Message = "Successfully retrieved token" + }; + } + + public bool IsTokenValid(string scope, string accessToken) + { + var result = false; + var token = DecodeToken(accessToken); + + if (token == null || token.Erroneous()) + { + return result; + } + + result = (!token.TokenExpired() && token.ContainsScope(scope)) ? true : false; + + // What would make a token valid? + // 1. The expiration date must be before the current date + // 2. The desired scope must be part of the scopes within the access token + // 3. Must be able to be decoded + + return result; + } + + public Token? DecodeToken(string accessToken) + { + var rsaParams = GetRSAPublic(_publicKey); + Token tok = null; + + try + { + using (var rsa = new RSACryptoServiceProvider()) + { + rsa.ImportParameters(rsaParams); + + IJsonSerializer serializer = new JsonNetSerializer(); + IDateTimeProvider provider = new UtcDateTimeProvider(); + IJwtValidator validator = new JwtValidator(serializer, provider); + IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); + var algorithm = new JWT.Algorithms.RS256Algorithm(rsa); + IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm); + + var json = decoder.Decode(accessToken); + tok = JsonConvert.DeserializeObject(json); + } + } + catch (Exception ex) + { + _logger.Error("An error occurred: {0}", ex.Message); + } + + + return tok; + } + + + private string AllScopes() + { + var allScopes = new List() + { + "download:songs", + "read:song_details", + "upload:songs", + "delete:songs", + "read:albums", + "read:artists", + "update:songs", + "stream:songs", + "read:genre", + "read:year", + "download:cover_art" + }; + + var scopes = string.Empty; + + for (var i = 0; i < allScopes.Count; i++) + { + if (i == allScopes.Count - 1) + { + scopes += allScopes[i]; + } + else + { + scopes += allScopes[i] + " "; + } + } + + return scopes; + } + + private List Payload() + { + var expLimit = 30; + var currentDate = DateTime.Now; + var expiredDate = currentDate.AddMinutes(expLimit); + var issued = Math.Floor((currentDate - DateTime.UnixEpoch).TotalSeconds); + var expires = Math.Floor((expiredDate - DateTime.UnixEpoch).TotalSeconds); + var issuer = "https://soaricarus.auth0.com"; + issuer = "http://localhost:5002"; + var audience = "https://icarus/api"; + audience = "http://localhost:5002"; + var subject = _config["JWT:Subject"]; + + var claim = new List() + { + new System.Security.Claims.Claim("scope", AllScopes(), "string"), + new System.Security.Claims.Claim(JwtRegisteredClaimNames.Exp, expiredDate.ToString()), + new System.Security.Claims.Claim(JwtRegisteredClaimNames.Aud, audience), + new System.Security.Claims.Claim(JwtRegisteredClaimNames.Iss, issuer), + new Claim(JwtRegisteredClaimNames.Sub, subject), + new System.Security.Claims.Claim(JwtRegisteredClaimNames.Iat, currentDate.ToString()) + }; + + return claim; + } + + private string CreateToken(List claims, string privateKey) + { + var token = string.Empty; + + if (string.IsNullOrEmpty(privateKey)) + { + privateKey = ReadKeyContent(_privateKeyPath).Result; + } + + RSAParameters rsaParams; + using (var tr = new System.IO.StringReader(privateKey)) + { + var pemReader = new PemReader(tr); + var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair; + if (keyPair == null) + { + throw new Exception("Could not read RSA private key"); + } + var privateRsaParams = keyPair.Private as RsaPrivateCrtKeyParameters; + rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams); + } + + using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) + { + var rsaParamsPublic = GetRSAPublic(ReadKeyContent(_publicKeyPath).Result); + var rsaPublic = new RSACryptoServiceProvider(); + + rsa.ImportParameters(rsaParams); + rsaPublic.ImportParameters(rsaParamsPublic); + + Dictionary payload = new Dictionary(); + + foreach (var claim in claims) + { + var type = claim.Type; + var val = Int32.TryParse(claim.Value, out _); + + if (val) + { + payload.Add(type, Convert.ToInt32(claim.Value)); + } + else + { + payload.Add(type, claim.Value); + } + + } + + var algorithm = new JWT.Algorithms.RS256Algorithm(rsaPublic, rsa); + IJsonSerializer serializer = new JsonNetSerializer(); + IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); + IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); + + token = encoder.Encode(payload, privateKey); + } + + return token; + } + + private RSAParameters GetRSAPublic(string publicKey) + { + using (var tr = new System.IO.StringReader(publicKey)) + { + var pemReader = new PemReader(tr); + var publicKeyParams = pemReader.ReadObject() as RsaKeyParameters; + if (publicKeyParams == null) + { + throw new Exception("Could not read RSA public key"); + } + return DotNetUtilities.ToRSAParameters(publicKeyParams); + } + } + + private async Task ReadKeyContent(string filepath) + { + return await System.IO.File.ReadAllTextAsync(filepath); + } private TokenRequest RetrieveTokenRequest() { @@ -89,6 +361,10 @@ namespace Icarus.Controllers.Managers _audience = _config["Auth0:ApiIdentifier"]; _grantType = "client_credentials"; _url = $"https://{_config["Auth0:Domain"]}"; + _privateKeyPath = _config["RSAKeys:PrivateKeyPath"]; + _publicKeyPath = _config["RSAKeys:PublicKeyPath"]; + _privateKey = System.IO.File.ReadAllText(_privateKeyPath); + _publicKey = System.IO.File.ReadAllText(_publicKeyPath); PrintCredentials(); } @@ -119,7 +395,7 @@ namespace Icarus.Controllers.Managers [JsonProperty("grant_type")] public string GrantType { get; set; } } - private class Token + private class TokenTierOne { [JsonProperty("access_token")] public string AccessToken { get; set; } @@ -130,4 +406,5 @@ namespace Icarus.Controllers.Managers } #endregion } + #endregion } diff --git a/Controllers/v1/AlbumController.cs b/Controllers/v1/AlbumController.cs index cdb6502..7980f71 100644 --- a/Controllers/v1/AlbumController.cs +++ b/Controllers/v1/AlbumController.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Configuration; using System.Linq; using Microsoft.AspNetCore.Authorization; @@ -10,18 +9,17 @@ using Microsoft.Extensions.Logging; using Icarus.Models; using Icarus.Database.Contexts; -// using Icarus.Database.Repositories; namespace Icarus.Controllers.V1 { [Route("api/v1/album")] [ApiController] - public class AlbumController : ControllerBase + [Authorize] + public class AlbumController : BaseController { #region Fields private readonly ILogger _logger; private string _connectionString; - private IConfiguration _config; #endregion @@ -41,8 +39,7 @@ namespace Icarus.Controllers.V1 #region HTTP Routes [HttpGet] - [Authorize("read:albums")] - public IActionResult Get() + public IActionResult GetAlbums() { List albums = new List(); @@ -57,8 +54,7 @@ namespace Icarus.Controllers.V1 } [HttpGet("{id}")] - [Authorize("read:albums")] - public IActionResult Get(int id) + public IActionResult GetAlbum(int id) { Album album = new Album { diff --git a/Controllers/v1/ArtistController.cs b/Controllers/v1/ArtistController.cs index 0531149..219e6c5 100644 --- a/Controllers/v1/ArtistController.cs +++ b/Controllers/v1/ArtistController.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Configuration; using System.Linq; using Microsoft.AspNetCore.Authorization; @@ -15,12 +13,12 @@ namespace Icarus.Controllers.V1 { [Route("api/v1/artist")] [ApiController] - public class ArtistController : ControllerBase + [Authorize] + public class ArtistController : BaseController { #region Fields private readonly ILogger _logger; private string _connectionString; - private IConfiguration _config; #endregion @@ -40,8 +38,7 @@ namespace Icarus.Controllers.V1 #region HTTP Routes [HttpGet] - [Authorize("read:artists")] - public IActionResult Get() + public IActionResult GetArtists() { var artistContext = new ArtistContext(_connectionString); @@ -54,9 +51,13 @@ namespace Icarus.Controllers.V1 } [HttpGet("{id}")] - [Authorize("read:artists")] - public IActionResult Get(int id) + public IActionResult GetArtist(int id) { + if (!IsTokenValid("read:artists")) + { + return StatusCode(401, "Not allowed"); + } + Artist artist = new Artist { ArtistID = id diff --git a/Controllers/v1/BaseController.cs b/Controllers/v1/BaseController.cs new file mode 100644 index 0000000..9cec68a --- /dev/null +++ b/Controllers/v1/BaseController.cs @@ -0,0 +1,51 @@ +using System; +using System.Linq; + +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; + +using Icarus.Controllers.Managers; + + +namespace Icarus.Controllers.V1 +{ + public class BaseController : ControllerBase + { + #region Fiends + protected IConfiguration _config; + #endregion + + + #region Methods + [ApiExplorerSettings(IgnoreApi = true)] + protected string ParseBearerTokenFromHeader() + { + var token = string.Empty; + const string tokenType = "Bearer"; + const string otherTokenType = "Jwt"; + + var req = Request; + var auth = req.Headers.Authorization; + var val = auth.ToString(); + + if ((val.Contains(tokenType) || val.Contains(otherTokenType)) && val.Split(" ").Count() > 1) + { + var split = val.Split(" "); + token = split[1]; + } + + + return token; + } + + [ApiExplorerSettings(IgnoreApi = true)] + protected bool IsTokenValid(string scope) + { + var token = ParseBearerTokenFromHeader(); + var tokMgr = new TokenManager(_config); + + return tokMgr.IsTokenValid(scope, token); + } + #endregion + } +} \ No newline at end of file diff --git a/Controllers/v1/CoverArtController.cs b/Controllers/v1/CoverArtController.cs index 103d1c3..4d3ef29 100644 --- a/Controllers/v1/CoverArtController.cs +++ b/Controllers/v1/CoverArtController.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading.Tasks; @@ -17,12 +15,12 @@ namespace Icarus.Controllers.V1 { [Route("api/v1/coverart")] [ApiController] - public class CoverArtController : ControllerBase + [Authorize] + public class CoverArtController : BaseController { #region Fields private readonly ILogger _logger; private string _connectionString; - private IConfiguration _config; #endregion @@ -37,7 +35,8 @@ namespace Icarus.Controllers.V1 #region HTTP Routes - public IActionResult Get() + [HttpGet] + public IActionResult GetCoverArts() { var coverArtContext = new CoverArtContext(_connectionString); @@ -56,8 +55,7 @@ namespace Icarus.Controllers.V1 } [HttpGet("{id}")] - [Authorize("download:cover_art")] - public async Task Get(int id) + public IActionResult GetCoverArt(int id) { var coverArt = new CoverArt { CoverArtID = id }; @@ -68,7 +66,7 @@ namespace Icarus.Controllers.V1 if (coverArt != null) { _logger.LogInformation("Found cover art record"); - var coverArtBytes = await System.IO.File.ReadAllBytesAsync( + var coverArtBytes = System.IO.File.ReadAllBytes( coverArt.ImagePath); return File(coverArtBytes, "application/x-msdownload", diff --git a/Controllers/v1/GenreController.cs b/Controllers/v1/GenreController.cs index a53bc4e..d5a86c1 100644 --- a/Controllers/v1/GenreController.cs +++ b/Controllers/v1/GenreController.cs @@ -14,12 +14,12 @@ namespace Icarus.Controllers.V1 { [Route("api/v1/genre")] [ApiController] - public class GenreController : ControllerBase + [Authorize] + public class GenreController : BaseController { #region Fields private readonly ILogger _logger; private string _connectionString; - private IConfiguration _config; #endregion @@ -39,8 +39,7 @@ namespace Icarus.Controllers.V1 #region HTTP Routes [HttpGet] - [Authorize("read:genre")] - public IActionResult Get() + public IActionResult GetGenres() { var genres = new List(); @@ -55,8 +54,7 @@ namespace Icarus.Controllers.V1 } [HttpGet("{id}")] - [Authorize("read:genre")] - public IActionResult Get(int id) + public IActionResult GetGenre(int id) { var genre = new Genre { diff --git a/Controllers/v1/LoginController.cs b/Controllers/v1/LoginController.cs index 9510a98..8446063 100644 --- a/Controllers/v1/LoginController.cs +++ b/Controllers/v1/LoginController.cs @@ -1,8 +1,5 @@ using System; -using System.Collections.Generic; -using System.Configuration; using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; @@ -41,7 +38,8 @@ namespace Icarus.Controllers.V1 #region HTTP endpoints - public IActionResult Post([FromBody] User user) + [HttpPost] + public IActionResult Login([FromBody] User user) { var context = new UserContext(_connectionString); @@ -55,34 +53,44 @@ namespace Icarus.Controllers.V1 Username = user.Username }; - if (context.Users.FirstOrDefault(usr => usr.Username.Equals(user.Username)) != null) + try { - user = context.Users.FirstOrDefault(usr => usr.Username.Equals(user.Username)); - - var validatePass = new PasswordEncryption(); - var validated = validatePass.VerifyPassword(user, password); - if (!validated) + if (context.Users.FirstOrDefault(usr => usr.Username.Equals(user.Username)) != null) { - loginRes.Message = message; - _logger.LogInformation(message); + user = context.Users.FirstOrDefault(usr => usr.Username.Equals(user.Username)); + + var validatePass = new PasswordEncryption(); + var validated = validatePass.VerifyPassword(user, password); + if (!validated) + { + loginRes.Message = message; + _logger.LogInformation(message); + + return Ok(loginRes); + } + + _logger.LogInformation("Successfully validated user credentials"); + + TokenManager tk = new TokenManager(_config); + + loginRes = tk.LoginSymmetric(user); return Ok(loginRes); } + else + { + loginRes.Message = message; - _logger.LogInformation("Successfully validated user credentials"); - - TokenManager tk = new TokenManager(_config); - - loginRes = tk.RetrieveLoginResult(user); - - return Ok(loginRes); + return NotFound(loginRes); + } } - else + catch (Exception ex) { - loginRes.Message = message; - - return NotFound(loginRes); + _logger.LogError("An error occurred: {0}", ex.Message); + _logger.LogError("Inner Exception: {0}", ex.InnerException.Message); } + + return NotFound(loginRes); } #endregion } diff --git a/Controllers/v1/RegisterController.cs b/Controllers/v1/RegisterController.cs index e1352d8..202b728 100644 --- a/Controllers/v1/RegisterController.cs +++ b/Controllers/v1/RegisterController.cs @@ -37,7 +37,7 @@ namespace Icarus.Controllers.V1 #endregion [HttpPost] - public IActionResult Post([FromBody] User user) + public IActionResult RegisterUser([FromBody] User user) { PasswordEncryption pe = new PasswordEncryption(); user.Password = pe.HashPassword(user); diff --git a/Controllers/v1/SongCompressedDataControllers.cs b/Controllers/v1/SongCompressedDataControllers.cs index 97f36c8..789a5d4 100644 --- a/Controllers/v1/SongCompressedDataControllers.cs +++ b/Controllers/v1/SongCompressedDataControllers.cs @@ -19,11 +19,11 @@ namespace Icarus.Controllers.V1 { [Route("api/v1/song/compressed/data")] [ApiController] - public class SongCompressedDataController : ControllerBase + [Authorize] + public class SongCompressedDataController : BaseController { #region Fields private string _connectionString; - private IConfiguration _config; private string _songTempDir; private string _archiveDir; #endregion @@ -46,8 +46,7 @@ namespace Icarus.Controllers.V1 #region API Routes [HttpGet("{id}")] - [Authorize("download:songs")] - public async Task Get(int id) + public async Task DownloadCompressedSong(int id) { var context = new SongContext(_connectionString); diff --git a/Controllers/v1/SongController.cs b/Controllers/v1/SongController.cs index 82a72d6..c7ebe3d 100644 --- a/Controllers/v1/SongController.cs +++ b/Controllers/v1/SongController.cs @@ -18,12 +18,12 @@ namespace Icarus.Controllers.V1 { [Route("api/v1/song")] [ApiController] - public class SongController : ControllerBase + [Authorize] + public class SongController : BaseController { #region Fields private readonly ILogger _logger; private string _connectionString; - private IConfiguration _config; private SongManager _songMgr; #endregion @@ -43,9 +43,12 @@ namespace Icarus.Controllers.V1 #endregion + #region Methods + #region HTTP Endpoints + + [HttpGet] - [Authorize("read:song_details")] - public IActionResult Get() + public IActionResult GetSongs() { List songs = new List(); Console.WriteLine("Attemtping to retrieve songs"); @@ -62,8 +65,7 @@ namespace Icarus.Controllers.V1 } [HttpGet("{id}")] - [Authorize("read:song_details")] - public IActionResult Get(int id) + public IActionResult GetSong(int id) { var context = new SongContext(_connectionString); @@ -78,9 +80,8 @@ namespace Icarus.Controllers.V1 return NotFound(); } - [Authorize("update:songs")] [HttpPut("{id}")] - public IActionResult Put(int id, [FromBody] Song song) + public IActionResult UpdateSong(int id, [FromBody] Song song) { var context = new SongContext(_connectionString); @@ -100,5 +101,7 @@ namespace Icarus.Controllers.V1 return Ok(songRes); } + #endregion + #endregion } } diff --git a/Controllers/v1/SongDataController.cs b/Controllers/v1/SongDataController.cs index 8b66acc..48341b6 100644 --- a/Controllers/v1/SongDataController.cs +++ b/Controllers/v1/SongDataController.cs @@ -20,11 +20,11 @@ namespace Icarus.Controllers.V1 { [Route("api/v1/song/data")] [ApiController] - public class SongDataController : ControllerBase + [Authorize] + public class SongDataController : BaseController { #region Fields private string _connectionString; - private IConfiguration _config; private ILogger _logger; private SongManager _songMgr; private string _songTempDir; @@ -47,16 +47,13 @@ namespace Icarus.Controllers.V1 #endregion - [HttpGet("download/{id}")] - [Route("private-scoped")] - [Authorize("download:songs")] - public async Task Get(int id) + public IActionResult Download(int id) { var songContext = new SongContext(_connectionString); var songMetaData = songContext.RetrieveRecord(new Song { SongID = id}); - var song = await _songMgr.RetrieveSong(songMetaData); + var song = _songMgr.RetrieveSong(songMetaData).Result; return File(song.Data, "application/x-msdownload", songMetaData.Filename); } @@ -74,25 +71,24 @@ namespace Icarus.Controllers.V1 // Cover art // [HttpPost("upload"), DisableRequestSizeLimit] - [Route("private-scoped")] - [Authorize("upload:songs")] - public async Task Post([FromForm(Name = "file")] List songData) + public IActionResult Upload([FromForm(Name = "file")] List songData) { try { - Console.WriteLine("Uploading song..."); + // Console.WriteLine("Uploading song..."); _logger.LogInformation("Uploading song..."); var uploads = _songTempDir; - Console.WriteLine($"Song Root Path {uploads}"); + // Console.WriteLine($"Song Root Path {uploads}"); _logger.LogInformation($"Song root path {uploads}"); foreach (var sng in songData) - if (sng.Length > 0) { - Console.WriteLine($"Song filename {sng.FileName}"); + if (sng.Length > 0) + { + // Console.WriteLine($"Song filename {sng.FileName}"); _logger.LogInformation($"Song filename {sng.FileName}"); - await _songMgr.SaveSongToFileSystem(sng); + _songMgr.SaveSongToFileSystem(sng).Wait(); } return Ok(); @@ -111,9 +107,7 @@ namespace Icarus.Controllers.V1 // as well as the cover art // [HttpPost("upload/with/data")] - [Route("private-scoped")] - [Authorize("upload:songs")] - public async Task Post ([FromForm] UploadSongWithDataForm up) + public IActionResult UploadWithData([FromForm] UploadSongWithDataForm up) { try { @@ -122,7 +116,7 @@ namespace Icarus.Controllers.V1 var song = Newtonsoft.Json.JsonConvert.DeserializeObject(up.SongFile); _logger.LogInformation($"Song title: {song.Title}"); - await _songMgr.SaveSongToFileSystem(up.SongData, up.CoverArtData, song); + _songMgr.SaveSongToFileSystem(up.SongData, up.CoverArtData, song); } } catch (Exception ex) @@ -134,8 +128,7 @@ namespace Icarus.Controllers.V1 } [HttpDelete("delete/{id}")] - [Authorize("delete:songs")] - public IActionResult Delete(int id) + public IActionResult DeleteSong(int id) { var songContext = new SongContext(_connectionString); @@ -160,15 +153,15 @@ namespace Icarus.Controllers.V1 } - public class UploadSongWithDataForm - { - [FromForm(Name = "file")] - public IFormFile SongData { get; set; } - // TODO: Think about making this optional and if it is not provided, use the stock cover art - [FromForm(Name = "cover")] - public IFormFile CoverArtData { get; set; } - [FromForm(Name = "metadata")] - public string SongFile { get; set; } - } + public class UploadSongWithDataForm + { + [FromForm(Name = "file")] + public IFormFile SongData { get; set; } + // NOTE: Think about making this optional and if it is not provided, use the stock cover art + [FromForm(Name = "cover")] + public IFormFile CoverArtData { get; set; } + [FromForm(Name = "metadata")] + public string SongFile { get; set; } + } } } diff --git a/Controllers/v1/SongStreamController.cs b/Controllers/v1/SongStreamController.cs index a15607d..de92076 100644 --- a/Controllers/v1/SongStreamController.cs +++ b/Controllers/v1/SongStreamController.cs @@ -13,18 +13,19 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Icarus.Models; +using Icarus.Controllers.Managers; using Icarus.Database.Contexts; namespace Icarus.Controllers.V1 { [Route("api/v1/song/stream")] [ApiController] - public class SongStreamController : ControllerBase + [Authorize] + public class SongStreamController : BaseController { #region Fields private ILogger _logger; private string _connectionString; - private IConfiguration _config; #endregion @@ -44,8 +45,7 @@ namespace Icarus.Controllers.V1 #region HTTP endpoints [HttpGet("{id}")] - [Authorize("stream:songs")] - public async Task Get(int id) + public async Task StreamSong(int id) { var context = new SongContext(_config.GetConnectionString("DefaultConnection")); diff --git a/Database/Contexts/UserContext.cs b/Database/Contexts/UserContext.cs index 030b538..2083f3c 100644 --- a/Database/Contexts/UserContext.cs +++ b/Database/Contexts/UserContext.cs @@ -8,6 +8,7 @@ using System.Linq; // using MySql.Data.Entity; // using MySql.Data.MySqlClient; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using Icarus.Models; @@ -18,11 +19,15 @@ namespace Icarus.Database.Contexts public DbSet Users { get; set; } + #region Constructors public UserContext(DbContextOptions options) : base(options) { } + [ActivatorUtilitiesConstructor] public UserContext(string connString) : base(new DbContextOptionsBuilder() .UseMySQL(connString).Options) { } + #endregion + protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Icarus.csproj b/Icarus.csproj index bfbfd41..7e626cd 100644 --- a/Icarus.csproj +++ b/Icarus.csproj @@ -3,7 +3,7 @@ net6 InProcess - 0.1.9 + 0.1.10 @@ -11,6 +11,7 @@ + @@ -21,8 +22,10 @@ + + diff --git a/Icarus.sln b/Icarus.sln new file mode 100644 index 0000000..018545a --- /dev/null +++ b/Icarus.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32616.157 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Icarus", "Icarus.csproj", "{66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {0BE61157-7A0C-41CF-B097-71178A3F6755} + EndGlobalSection +EndGlobal diff --git a/Models/Song.cs b/Models/Song.cs index fe7107b..6c54c70 100644 --- a/Models/Song.cs +++ b/Models/Song.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Threading.Tasks; using Newtonsoft.Json; @@ -79,6 +80,21 @@ namespace Icarus.Models s[random.Next(s.Length)]).ToArray()); var extension = ".mp3"; + return flag == 0 ? filename : $"{filename}{extension}"; + } + public async Task GenerateFilenameAsync(int flag = 0) + { + const int length = 25; + const string chars = "ABCDEF0123456789"; + var extension = ".mp3"; + var random = new Random(); + var filename = await Task.Run(() => + { + return new string(Enumerable.Repeat(chars, length).Select(s => + s[random.Next(s.Length)]).ToArray()); + }); + + return flag == 0 ? filename : $"{filename}{extension}"; } #endregion diff --git a/Models/Token.cs b/Models/Token.cs new file mode 100644 index 0000000..bfa5889 --- /dev/null +++ b/Models/Token.cs @@ -0,0 +1,56 @@ +using System; +using System.Linq; + +using Newtonsoft.Json; + + +namespace Icarus.Models +{ + public class Token + { + #region Properties + [JsonProperty("scope")] + public string Scope { get; set; } + [JsonProperty("exp")] + public int Expiration { get; set; } + [JsonProperty("aud")] + public string Audience { get; set; } + [JsonProperty("iss")] + public string Issuer { get; set; } + [JsonProperty("iat")] + public int Issued { get; set; } + #endregion + + #region Methods + public bool TokenExpired() + { + var result = false; + var currentDate = DateTime.Now; + + var currentDateInSeconds = Math.Floor((currentDate - DateTime.UnixEpoch).TotalSeconds); + + result = (currentDateInSeconds >= Expiration) ? true : false; + + return result; + } + + public bool ContainsScope(string desiredScope) + { + var result = false; + result = Scope.Contains(desiredScope); + + return result; + } + + public bool Erroneous() + { + var result = true; + Func isEmpty = a => string.IsNullOrEmpty(a); + result = (!isEmpty(Scope) && !isEmpty(Audience) && !isEmpty(Issuer) && + Expiration > 0 && Issued > 0) ? false : true; + + return result; + } + #endregion + } +} \ No newline at end of file diff --git a/Models/User.cs b/Models/User.cs index 6fd74a9..4dece75 100644 --- a/Models/User.cs +++ b/Models/User.cs @@ -1,6 +1,7 @@ using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; using Newtonsoft.Json; @@ -9,6 +10,7 @@ namespace Icarus.Models [Table("User")] public class User { + #region Properties [JsonProperty("user_id")] [Column("UserID")] [Key] @@ -35,5 +37,21 @@ namespace Icarus.Models public string Status { get; set; } [JsonProperty("last_login")] public DateTime? LastLogin { get; set; } + + [JsonIgnore] + [NotMapped] + public System.Collections.Generic.IEnumerable Roles { get; set; } + #endregion + + + #region Methods + public System.Collections.Generic.IEnumerable Claims() + { + var claims = new System.Collections.Generic.List { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, Username) }; + claims.AddRange(Roles.Select(role => new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, role))); + + return claims; + } + #endregion } } diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json index 82a1227..b71d9cb 100644 --- a/Properties/launchSettings.json +++ b/Properties/launchSettings.json @@ -12,7 +12,7 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "api/values", + "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -20,7 +20,8 @@ "Icarus": { "commandName": "Project", "launchBrowser": true, - "launchUrl": "api/values", + "dotnetRuneMessage": true, + "launchUrl": "swagger", "applicationUrl": "http://localhost:5002", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/README.md b/README.md index e205100..c3bb084 100644 --- a/README.md +++ b/README.md @@ -10,76 +10,68 @@ One can interface with Icarus the music server either by: * [IcarusDownloadManager](https://github.com/amazing-username/IcarusDownloadManager) - ## Built With - * C# [.NET](https://dotnet.microsoft.com/) 6 * [MySql](https://www.nuget.org/packages/MySql.Data/) +* OpenSSL +* BCrypt.Net-Next +* DotNetZip +* ID3 +* JWT +* Microsoft.AspNetCore.Authentication.JwtBearer +* Microsoft.AspNetCore.Mvc.NewtonsoftJson +* Microsoft.EntityFrameworkCore +* Microsoft.EntityFrameworkCore.Tools +* MySql.EntityFrameworkCore * [Newtonsoft.Json](https://www.newtonsoft.com/json) +* NLog.Web.AspNetCpre +* Portable.BouncyCastle +* RestSharp +* SevenZip +* System.IdentityModel.Tokens.Jwt * [TagLib#](https://github.com/mono/taglib-sharp) -![image](https://user-images.githubusercontent.com/14333136/56252069-28532d00-6084-11e9-896d-1a3c378014ef.png) + ## Getting started + There are several things that need to be completed to properly setup and secure the API. -1. Auth0 API configuration +This API uses OpenAPI Specification 3.0. After configuring the API, launch the software +and navigate your browser to https://localhost:5001/swagger to view the endpoints. + +1. JWT Information 2. API filesystem paths 3. Database connection string 4. Migrations -### Auth0 API configuration -Securing Icarus is required, preventing the API from being publicly accessible. To do so, create an Auth0 account (it's free), for the sake of this section of the documentation, I will not go over how to create an Auth0 account. Once created, create a tentant and proceed to create an API -

- -

+### JWT Information -Create the API and enter an approrpiate name and identified. For the identified, append **api** like in the example -

- -

-Replace [domain] with the domain name of the created tenant. This can be found in the Default App from the Application menu. Replace [identifier] with the identifer root name in the appsettings environment file. Not the friendly name but the root name of the identifier, omitting the http protocol and the *api* path. +Configure JWT information. Notably the Secret ```Json - "Auth0": { - "Domain": "[domain].auth0.com", - "ApiIdentifier": "https://[identifier]/api" + "JWT": { + "Issuer": "IcarusAPI", + "Audience": "IcarusAPIClient", + "Secret": "Manaiswhatyouthinkitis", + "Subject": "Authorization" }, ``` -For the sake of this section, I will not go over configuring the API to accept the signing algorithm since it has already been configured in the [Startip](Startup.cs).cs file. Click on permissions to create the permissions for the API. -

- -

-The permissions ensure that a validated user can interact with the API with a token that has not expired. Ensure that the permissions match, the description can change but the permission identifier must match. -

- -

+Replace [domain] with the domain name that represent's your domain. Replace [identifier] with the identifer root name in the appsettings environment file. Not the friendly name but the root name of the identifier, omitting the http protocol and the *api* path. -On the left side, click on Application and create a new Application. Choose the Machine to Machine Application -

- -

- -With the grant permissions you created from the API, enable all the permissions. This is important because if they are not enabled then even with a valid token the request will return 403 (unauthorized) -

- -

- -From the Application page, copy the client id and client secret. These values will be used for the API to interact with API. -

- -

-Enter the information in the corresponding appsettings json file ```Json - "Auth0": { - "ClientId":"", - "ClientSecret":"" - }, +"Auth0": { + "Domain": "[domain].auth0.com", + "ApiIdentifier": "https://[identifier]/api" +}, ``` +**Note**: The Auth0 section is likely to be changed or removed in future releases. + + ### API filesystem paths For the purposes of properly uploading, downloading, updating, deleting, and streaming songs the API filesystem paths must be configured. What is meant by this is that the `RootMusicPath` directory where all music will be stored must exist as well as the `ArchivePath` and `TemporaryMusicPath` paths. An example on a Linux system: @@ -87,12 +79,14 @@ For the purposes of properly uploading, downloading, updating, deleting, and str { "RootMusicPath": "/home/dev/null/music/", "TemporaryMusicPath": "/home/dev/null/music/temp/", - "ArchivePath": "/home/dev/null/music/archive/" + "ArchivePath": "/home/dev/null/music/archive/", + "CoverArtPath": "/home/dev/null/music/coverart/" } ``` * RootMusicPath - Where music will be stored in the following convention: *`Artist/Album/Songs`* * TemporaryMusicPath - Where music will be stored when uploding songs to the server until the metadata has been fully parsed and entered into the database. Upon completion the files will be deleted and moved to the appropriate path in the `RootMusicPath` * ArchivePath - When downloading compressed songs this is the path where songs will be compressed prior to dataa being read into memory, deleting the compressed file, and sending the compressed file from memory to the client +* CoverArtPath - Root directory where cover art will be saved to **Note**: The `TemporaryMusic` or `ArchivePath` does not have to be located in the `RootMusicPath`. Ensure that the permissions are properly set for all of the paths. @@ -100,15 +94,15 @@ For the purposes of properly uploading, downloading, updating, deleting, and str ### Database connection string In order for Database functionality to be operable, there must be a valid connection string and credentials with appropriate permissions. **At the moment there is only support for MySQL**. Depending on your environment `Release` or `Debug` you will need to edit the appsettings.json or appsettings.Development.json accordingly. An example of the fields to change are below: + ```Json { - "ConnectionStrings": { - "DefaultConnection": "Server=localhost;Database=my_db;Uid=admin;Pwd=toughpassword;" + "DefaultConnection": "Server=localhost;Database=my_db;Uid=admin;Pwd=toughpassword;" } - } ``` + * Server - The address or domain name of the MySQL server * Database - The database name * Uid - Username @@ -146,15 +140,6 @@ From this point the database has been successfully configured. Metadata and song Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the code of conduct, and the process for submitting pull requests to the project. -## Versioning - -* [v0.1](https://github.com/amazing-username/Icarus/releases/tag/v0.1) - -## Authors - -* **Kun Deng** - [amazing-username](https://github.com/amazing-username) - -See also the list of [contributors](https://github.com/amazing-username/Icarus/graphs/contributors) who participated in this project. ## License diff --git a/Scripts/Migrations/Linux/AddUpdate.sh b/Scripts/Migrations/Linux/AddUpdate.sh old mode 100755 new mode 100644 diff --git a/Startup.cs b/Startup.cs index 44e5481..89c50d1 100644 --- a/Startup.cs +++ b/Startup.cs @@ -1,42 +1,42 @@ using System; -using System.Collections.Generic; +using System.Text; using System.Linq; -using System.Threading.Tasks; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpsPolicy; -using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; +using Microsoft.OpenApi.Models; using Newtonsoft.Json; using NLog; using NLog.Web; using NLog.Web.AspNetCore; -using Icarus.Authorization; -using Icarus.Authorization.Handlers; using Icarus.Database.Contexts; namespace Icarus { public class Startup { + #region Constructors public Startup(IConfiguration configuration) { Configuration = configuration; } + #endregion + #region Properties public IConfiguration Configuration { get; } + #endregion + + #region Methods // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { @@ -46,66 +46,21 @@ namespace Icarus var domain = $"https://{auth_id}/"; var audience = Configuration["Auth0:ApiIdentifier"]; - services - .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddJwtBearer(options => - { - options.Authority = domain; - options.Audience = audience; - }); - - services.AddAuthorization(options => - { - options.AddPolicy("download:songs", policy => - policy.Requirements - .Add(new HasScopeRequirement("download:songs", domain))); - - options.AddPolicy("download:cover_art", policy => - policy.Requirements - .Add(new HasScopeRequirement("download:cover_art", domain))); - - options.AddPolicy("upload:songs", policy => - policy.Requirements - .Add(new HasScopeRequirement("upload:songs", domain))); - - options.AddPolicy("delete:songs", policy => - policy.Requirements - .Add(new HasScopeRequirement("delete:songs", domain))); - - options.AddPolicy("read:song_details", policy => - policy.Requirements - .Add(new HasScopeRequirement("read:song_details", domain))); - - options.AddPolicy("update:songs", policy => - policy.Requirements - .Add(new HasScopeRequirement("update:songs", domain))); - - options.AddPolicy("read:artists", policy => - policy.Requirements - .Add(new HasScopeRequirement("read:artists", domain))); - - options.AddPolicy("read:albums", policy => - policy.Requirements - .Add(new HasScopeRequirement("read:albums", domain))); - - options.AddPolicy("read:genre", policy => - policy.Requirements - .Add(new HasScopeRequirement("read:genre", domain))); - - options.AddPolicy("read:year", policy => - policy.Requirements - .Add(new HasScopeRequirement("read:year", domain))); - - options.AddPolicy("stream:songs", policy => - policy.Requirements - .Add(new HasScopeRequirement("stream:songs", domain))); - }); - - - services.AddSingleton(); - var connString = Configuration.GetConnectionString("DefaultConnection"); + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => + { + options.RequireHttpsMetadata = false; + options.SaveToken = true; + options.TokenValidationParameters = new TokenValidationParameters() + { + ValidateIssuer = true, + ValidateAudience = true, + ValidAudience = Configuration["JWT:Audience"], + ValidIssuer = Configuration["JWT:Issuer"], + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"])) + }; + }); services.AddDbContext(options => options.UseMySQL(connString)); services.AddDbContext(options => options.UseMySQL(connString)); @@ -116,12 +71,48 @@ namespace Icarus services.AddControllers() .AddNewtonsoftJson(); + + services.AddEndpointsApiExplorer(); + services.AddSwaggerGen(c => + { + c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); + + c.SwaggerDoc("v1", new OpenApiInfo { Title = "Icarus", Version = "v1" }); + c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() + { + Name = "Authorization", + Scheme = "Bearer", + BearerFormat = "JWT", + Type = SecuritySchemeType.ApiKey, + In = ParameterLocation.Header, + Description = "Bearer *Auth Token*", + }); + c.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + } + }, + new string[] {} + } + }); + }); } // Called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // NOTE: Dev-related configuration can be done when env.IsDevelopment() evaluated to true + if (env.IsDevelopment()) + { + app.UseSwagger(); + app.UseSwaggerUI(); + } app.UseRouting(); app.UseAuthentication(); @@ -131,5 +122,6 @@ namespace Icarus endpoints.MapControllers(); }); } + #endregion } } diff --git a/appsettings.Development.json b/appsettings.Development.json index 827e74a..c8ed0de 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -12,6 +12,16 @@ "ClientId": "", "ClientSecret": "" }, + "RSAKeys": { + "PrivateKeyPath": "", + "PublicKeyPath": "" + }, + "JWT": { + "Issuer": "", + "Audience": "", + "Secret": "", + "Subject": "" + }, "ConnectionStrings": { "DefaultConnection": "Server=;Database=;Uid=;Pwd=;" }, diff --git a/appsettings.json b/appsettings.json index bd1b862..71f2123 100644 --- a/appsettings.json +++ b/appsettings.json @@ -12,6 +12,16 @@ "ClientId": "", "ClientSecret": "" }, + "RSAKeys": { + "PrivateKeyPath": "", + "PublicKeyPath": "" + }, + "JWT": { + "Issuer": "", + "Audience": "", + "Secret": "", + "Subject": "" + }, "ConnectionStrings": { "DefaultConnection": "Server=;Database=;Uid=;Pwd=;" },