Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
* static added to Constants

* Docker support for Blazor

* GetHttp, PostHttp, ... inside AuthService, Docker working with login, Cookies Configuration temporary disabled

* BaseAddress get web uri from Blazor Shared.

* cookie options changed to fix docker.

* Fixed returnUrl when inserting admin link and navigate without login

* Functions not used removed.

* AddPolicy using GetWebUrl

* Login link removed from NavMenu

* Change ConfigureCookieSettings, ConfigureCoreServices and ConfigureWebServices to be IServiceCollection extentions.

* GetOriginWebUrl added.

* Auto InDocker switch added.

* Removed not used using .
  • Loading branch information
ShadyNagy authored Jul 27, 2020
1 parent e1f9ddd commit 6880641
Show file tree
Hide file tree
Showing 25 changed files with 149 additions and 192 deletions.
2 changes: 2 additions & 0 deletions docker-compose.override.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ services:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://+:80
- DOTNET_RUNNING_IN_CONTAINER=true
ports:
- "5106:80"
volumes:
Expand All @@ -13,6 +14,7 @@ services:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://+:80
- DOTNET_RUNNING_IN_CONTAINER=true
ports:
- "5200:80"
volumes:
Expand Down
7 changes: 0 additions & 7 deletions src/BlazorAdmin/Constants.cs

This file was deleted.

2 changes: 1 addition & 1 deletion src/BlazorAdmin/Pages/CatalogItemPage/Delete.razor
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
{
<div class="container">
<div class="row">
<img class="col-md-6 esh-picture" src="@($"https://localhost:44315/{_item.PictureUri}")">
<img class="col-md-6 esh-picture" src="@($"{Auth.WebUrl}{_item.PictureUri}")">

<dl class="col-md-6 dl-horizontal">
<dt>
Expand Down
2 changes: 1 addition & 1 deletion src/BlazorAdmin/Pages/CatalogItemPage/Details.razor
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
{
<div class="container">
<div class="row">
<img class="col-md-6 esh-picture" src="@($"https://localhost:44315/{_item.PictureUri}")">
<img class="col-md-6 esh-picture" src="@($"{Auth.WebUrl}{_item.PictureUri}")">

<dl class="col-md-6 dl-horizontal">
<dt>
Expand Down
3 changes: 1 addition & 2 deletions src/BlazorAdmin/Pages/CatalogItemPage/List.razor
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
@page "/admin"
@attribute [Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS)]
@inject AuthService Auth
@using global::BlazorShared.Authorization
@inherits BlazorAdmin.Helpers.BlazorComponent
@namespace BlazorAdmin.Pages.CatalogItemPage

Expand Down Expand Up @@ -38,7 +37,7 @@ else
{
<tr @onclick="@(() => DetailsClick(item.Id))">
<td>
<img class="img-thumbnail" src="@($"https://localhost:44315/{item.PictureUri}")">
<img class="img-thumbnail" src="@($"{Auth.WebUrl}{item.PictureUri}")">
</td>
<td>@Services.CatalogTypeServices.List.GetTypeName(catalogTypes, item.CatalogTypeId)</td>
<td>@Services.CatalogBrandServices.List.GetBrandName(catalogBrands, item.CatalogBrandId)</td>
Expand Down
191 changes: 72 additions & 119 deletions src/BlazorAdmin/Services/AuthService.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using BlazorAdmin.JavaScript;
Expand All @@ -20,6 +16,12 @@ public class AuthService
private readonly HttpClient _httpClient;
private readonly ILocalStorageService _localStorage;
private readonly IJSRuntime _jSRuntime;

public string ApiUrl => Constants.GetApiUrl(InDocker);
public string WebUrl => Constants.GetWebUrl(InDocker);

private static bool InDocker { get; set; }

public bool IsLoggedIn { get; set; }
public string UserName { get; set; }

Expand All @@ -30,51 +32,33 @@ public AuthService(HttpClient httpClient, ILocalStorageService localStorage, IJS
_jSRuntime = jSRuntime;
}

public HttpClient GetHttpClient()
public async Task<HttpResponseMessage> HttpGet(string uri)
{
return _httpClient;
return await _httpClient.GetAsync($"{ApiUrl}{uri}");
}

public async Task<AuthResponse> LoginWithoutSaveToLocalStorage(AuthRequest user)
public async Task<HttpResponseMessage> HttpDelete(string uri, int id)
{
var jsonContent = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"{Constants.API_URL}authenticate", jsonContent);
var authResponse = new AuthResponse();

if (response.IsSuccessStatusCode)
{
authResponse = await DeserializeToAuthResponse(response);

IsLoggedIn = true;
}

return authResponse;
return await _httpClient.DeleteAsync($"{ApiUrl}{uri}/{id}");
}

public async Task<AuthResponse> Login(AuthRequest user)
public async Task<HttpResponseMessage> HttpPost(string uri, object dataToSend)
{
var jsonContent = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync($"{Constants.API_URL}authenticate", jsonContent);
var authResponse = new AuthResponse();
var content = ToJson(dataToSend);

if (response.IsSuccessStatusCode)
{
authResponse = await DeserializeToAuthResponse(response);
await SaveTokenInLocalStorage(authResponse);
await SaveUsernameInLocalStorage(authResponse);
await SetAuthorizationHeader();
return await _httpClient.PostAsync($"{ApiUrl}{uri}", content);
}

UserName = await GetUsername();
IsLoggedIn = true;
}
public async Task<HttpResponseMessage> HttpPut(string uri, object dataToSend)
{
var content = ToJson(dataToSend);

return authResponse;
return await _httpClient.PutAsync($"{ApiUrl}{uri}", content);
}

public async Task Logout()
{
await _localStorage.RemoveItemAsync("authToken");
await _localStorage.RemoveItemAsync("username");
await DeleteLocalStorage();
await DeleteCookies();
RemoveAuthorizationHeader();
UserName = null;
Expand All @@ -95,35 +79,73 @@ public async Task RefreshLoginInfoFromCookie()
var username = await new Cookies(_jSRuntime).GetCookie("username");
await SaveUsernameInLocalStorage(username);

var inDocker = await new Cookies(_jSRuntime).GetCookie("inDocker");
await SaveInDockerInLocalStorage(inDocker);

await RefreshLoginInfo();
}

public async Task<string> GetToken()
{

var token = await _localStorage.GetItemAsync<string>("authToken");
return token;
}

public async Task<UserInfo> GetTokenFromController()
{
return await _httpClient.GetFromJsonAsync<UserInfo>("User");
}

public async Task<string> GetUsername()
{
var username = await _localStorage.GetItemAsync<string>("username");
return username;
}

public async Task<bool> GetInDocker()
{
return (await _localStorage.GetItemAsync<string>("inDocker")).ToLower() == "true";
}

private StringContent ToJson(object obj)
{
return new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
}

private async Task LogoutIdentityManager()
{
await _httpClient.PostAsync("Identity/Account/Logout", null);
}

private async Task DeleteLocalStorage()
{
await _localStorage.RemoveItemAsync("authToken");
await _localStorage.RemoveItemAsync("username");
await _localStorage.RemoveItemAsync("inDocker");
}

private async Task DeleteCookies()
{
await new Cookies(_jSRuntime).DeleteCookie("token");
await new Cookies(_jSRuntime).DeleteCookie("username");
await new Cookies(_jSRuntime).DeleteCookie("inDocker");
}

private async Task SetLoginData()
{
IsLoggedIn = !string.IsNullOrEmpty(await GetToken());
UserName = await GetUsername();
InDocker = await GetInDocker();
await SetAuthorizationHeader();
}

private async Task<AuthResponse> DeserializeToAuthResponse(HttpResponseMessage response)
{
var responseContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AuthResponse>(responseContent);
}

private async Task SaveTokenInLocalStorage(AuthResponse authResponse)
private void RemoveAuthorizationHeader()
{
await _localStorage.SetItemAsync("authToken", SaveTokenInLocalStorage(authResponse.Token));
if (_httpClient.DefaultRequestHeaders.Contains("Authorization"))
{
_httpClient.DefaultRequestHeaders.Remove("Authorization");
}
}

private async Task SaveTokenInLocalStorage(string token)
Expand All @@ -135,19 +157,6 @@ private async Task SaveTokenInLocalStorage(string token)
await _localStorage.SetItemAsync("authToken", token);
}

private void RemoveAuthorizationHeader()
{
if (_httpClient.DefaultRequestHeaders.Contains("Authorization"))
{
_httpClient.DefaultRequestHeaders.Remove("Authorization");
}
}

private async Task SaveUsernameInLocalStorage(AuthResponse authResponse)
{
await _localStorage.SetItemAsync("username", SaveUsernameInLocalStorage(authResponse.Username));
}

private async Task SaveUsernameInLocalStorage(string username)
{
if (string.IsNullOrEmpty(username))
Expand All @@ -157,22 +166,13 @@ private async Task SaveUsernameInLocalStorage(string username)
await _localStorage.SetItemAsync("username", username);
}

public async Task<string> GetToken()
{

var token = await _localStorage.GetItemAsync<string>("authToken");
return token;
}

public async Task<UserInfo> GetTokenFromController()
private async Task SaveInDockerInLocalStorage(string inDocker)
{
return await _httpClient.GetFromJsonAsync<UserInfo>("User");
}

public async Task<string> GetUsername()
{
var username = await _localStorage.GetItemAsync<string>("username");
return username;
if (string.IsNullOrEmpty(inDocker))
{
return;
}
await _localStorage.SetItemAsync("inDocker", inDocker);
}

private async Task SetAuthorizationHeader()
Expand All @@ -181,52 +181,5 @@ private async Task SetAuthorizationHeader()
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}

public IEnumerable<Claim> ParseClaimsFromJwt(string jwt)
{
var claims = new List<Claim>();
if (string.IsNullOrEmpty(jwt))
{
return claims;
}

var payload = jwt.Split('.')[1];
var jsonBytes = ParseBase64WithoutPadding(payload);
var keyValuePairs = JsonConvert.DeserializeObject<Dictionary<string, object>>(Encoding.UTF8.GetString(jsonBytes));

keyValuePairs.TryGetValue(ClaimTypes.Role, out object roles);

if (roles != null)
{
if (roles.ToString().Trim().StartsWith("["))
{
var parsedRoles = JsonConvert.DeserializeObject<string[]>(roles.ToString());

foreach (var parsedRole in parsedRoles)
{
claims.Add(new Claim(ClaimTypes.Role, parsedRole));
}
}
else
{
claims.Add(new Claim(ClaimTypes.Role, roles.ToString()));
}

keyValuePairs.Remove(ClaimTypes.Role);
}

claims.AddRange(keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString())));

return claims;
}

private byte[] ParseBase64WithoutPadding(string base64)
{
switch (base64.Length % 4)
{
case 2: base64 += "=="; break;
case 3: base64 += "="; break;
}
return Convert.FromBase64String(base64);
}
}
}
2 changes: 1 addition & 1 deletion src/BlazorAdmin/Services/CatalogBrandServices/List.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public async Task<List<CatalogBrand>> HandleAsync()

try
{
var result = (await _authService.GetHttpClient().GetAsync($"{Constants.API_URL}catalog-brands"));
var result = await _authService.HttpGet("catalog-brands");
if (result.StatusCode != HttpStatusCode.OK)
{
return brands;
Expand Down
6 changes: 1 addition & 5 deletions src/BlazorAdmin/Services/CatalogItemServices/Create.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

Expand All @@ -19,9 +17,7 @@ public async Task<CatalogItem> HandleAsync(CreateCatalogItemRequest catalogItem)
{
var catalogItemResult = new CatalogItem();

var content = new StringContent(JsonConvert.SerializeObject(catalogItem), Encoding.UTF8, "application/json");

var result = await _authService.GetHttpClient().PostAsync($"{Constants.API_URL}catalog-items", content);
var result = await _authService.HttpPost("catalog-items", catalogItem);
if (result.StatusCode != HttpStatusCode.OK)
{
return catalogItemResult;
Expand Down
2 changes: 1 addition & 1 deletion src/BlazorAdmin/Services/CatalogItemServices/Delete.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public async Task<string> HandleAsync(int catalogItemId)
{
var catalogItemResult = string.Empty;

var result = await _authService.GetHttpClient().DeleteAsync($"{Constants.API_URL}catalog-items/{catalogItemId}");
var result = await _authService.HttpDelete("catalog-items", catalogItemId);
if (result.StatusCode != HttpStatusCode.OK)
{
return catalogItemResult;
Expand Down
6 changes: 1 addition & 5 deletions src/BlazorAdmin/Services/CatalogItemServices/Edit.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

Expand All @@ -19,9 +17,7 @@ public async Task<CatalogItem> HandleAsync(CatalogItem catalogItem)
{
var catalogItemResult = new CatalogItem();

var content = new StringContent(JsonConvert.SerializeObject(catalogItem), Encoding.UTF8, "application/json");

var result = await _authService.GetHttpClient().PutAsync($"{Constants.API_URL}catalog-items", content);
var result = await _authService.HttpPut("catalog-items", catalogItem);
if (result.StatusCode != HttpStatusCode.OK)
{
return catalogItemResult;
Expand Down
2 changes: 1 addition & 1 deletion src/BlazorAdmin/Services/CatalogItemServices/GetById.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public async Task<CatalogItem> HandleAsync(int catalogItemId)
{
var catalogItemResult = new CatalogItem();

var result = await _authService.GetHttpClient().GetAsync($"{Constants.API_URL}catalog-items/{catalogItemId}");
var result = await _authService.HttpGet($"catalog-items/{catalogItemId}");
if (result.StatusCode != HttpStatusCode.OK)
{
return catalogItemResult;
Expand Down
Loading

0 comments on commit 6880641

Please sign in to comment.