Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSB auth cookies #145

Merged
merged 2 commits into from
Feb 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/BlazorBoilerplate.CommonUI/App.razor
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,29 @@
[Inject] HttpClient _httpClient { get; set; }
[Inject] NavigationManager _navigationManager { get; set; }

#if ServerSideBlazor
[Inject] IHttpContextAccessor _http { get; set; }
#endif

protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();

_httpClient.BaseAddress = new Uri(_navigationManager.BaseUri);

#if ServerSideBlazor
// likely user refreshed page, we need to grab the cookies if they exist and pass it to the HttpClient for this request
if (_http != null && _http.HttpContext.Request.Cookies.Any())
{
var cks = new List<string>();

foreach (var cookie in _http.HttpContext.Request.Cookies)
{
cks.Add($"{cookie.Key}={cookie.Value}");
}

_httpClient.DefaultRequestHeaders.Add("Cookie", String.Join(';', cks));
}
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
<PackageReference Include="Microsoft.AspNetCore.Components" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="3.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" />
<PackageReference Include="Toolbelt.Blazor.LoadingBar" Version="10.0.0" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,87 @@
using BlazorBoilerplate.CommonUI.Services.Contracts;
using BlazorBoilerplate.Shared.Dto;
using System.Collections.Generic;
using Microsoft.JSInterop;
using System.Linq;
using System.Net;

namespace BlazorBoilerplate.CommonUI.Services.Implementations
{
public class AuthorizeApi : IAuthorizeApi
{
private readonly HttpClient _httpClient;
private readonly NavigationManager _navigationManager;
private readonly IJSRuntime _jsRuntime;

public AuthorizeApi(HttpClient httpClient)
public AuthorizeApi(NavigationManager navigationManager, HttpClient httpClient, IJSRuntime jsRuntime)
{
_httpClient = httpClient;
_navigationManager = navigationManager;
_httpClient = httpClient;
_jsRuntime = jsRuntime;
}

public async Task<ApiResponseDto> Login(LoginDto loginParameters)
{
return await _httpClient.PostJsonAsync<ApiResponseDto>("api/Account/Login", loginParameters);
ApiResponseDto resp;

var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "api/Account/Login");
httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(loginParameters));
httpRequestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

using (var response = await _httpClient.SendAsync(httpRequestMessage))
{
response.EnsureSuccessStatusCode();

#if ServerSideBlazor

if (response.Headers.TryGetValues("Set-Cookie", out var cookieEntries))
{
var uri = response.RequestMessage.RequestUri;
var cookieContainer = new CookieContainer();

foreach (var cookieEntry in cookieEntries)
{
cookieContainer.SetCookies(uri, cookieEntry);
}

var cookies = cookieContainer.GetCookies(uri).Cast<Cookie>();

foreach (var cookie in cookies)
{
await _jsRuntime.InvokeVoidAsync("jsInterops.setCookie", cookie.ToString());
}
}
#endif

var content = await response.Content.ReadAsStringAsync();
resp = JsonConvert.DeserializeObject<ApiResponseDto>(content);
}

return resp;
}

public async Task<ApiResponseDto> Logout()
{
return await _httpClient.PostJsonAsync<ApiResponseDto>("api/Account/Logout", null);
#if ServerSideBlazor
var cookies = _httpClient.DefaultRequestHeaders?.GetValues("Cookie")?.ToList();
#endif

var resp = await _httpClient.PostJsonAsync<ApiResponseDto>("api/Account/Logout", null);

#if ServerSideBlazor
if (resp.StatusCode == 200 && cookies != null && cookies.Any())
{
_httpClient.DefaultRequestHeaders.Remove("Cookie");

foreach (var cookie in cookies[0].Split(';'))
{
var cookieParts = cookie.Split('=');
await _jsRuntime.InvokeVoidAsync("jsInterops.removeCookie", cookieParts[0]);
}
}
#endif

return resp;
}

public async Task<ApiResponseDto> Create(RegisterDto registerParameters)
Expand Down
1 change: 1 addition & 0 deletions src/BlazorBoilerplate.CommonUI/_Imports.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Http;
@using Microsoft.JSInterop
@using BlazorBoilerplate.Shared
@using BlazorBoilerplate.Shared.Dto
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
window.jsInterops = {
setCookie: function (cookie) {
document.cookie = cookie;
},
removeCookie: function (cookieName) {
document.cookie = cookieName + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
}
1 change: 1 addition & 0 deletions src/BlazorBoilerplate.Server/Pages/index_ssb.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,6 @@
<script src="_content/MatBlazor/dist/matBlazor.js"></script>
<script src="_content/BlazorBoilerplate.CommonUI/javascript/signalr.min.js"></script>
<script src="_content/BlazorBoilerplate.CommonUI/javascript/chatClient.js"></script>
<script src="_content/BlazorBoilerplate.CommonUI/javascript/jsInterops.js"></script>
</body>
</html>