Skip to content

Commit

Permalink
Merge pull request #1372 from sbwalker/dev
Browse files Browse the repository at this point in the history
auth improvements related to multi-tenancy
  • Loading branch information
sbwalker authored May 19, 2021
2 parents 6e21eb7 + 09537ab commit ddc4254
Show file tree
Hide file tree
Showing 23 changed files with 235 additions and 134 deletions.
13 changes: 9 additions & 4 deletions Oqtane.Client/Modules/Admin/Login/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@
{
<ModuleMessage Message="@_message" Type="@_type" />
}
<AuthorizeView>
<AuthorizeView Roles="@RoleNames.Registered">
<Authorizing>
<text>...</text>
</Authorizing>
<Authorized>
<ModuleMessage Message="@Localizer["You Are Already Signed In"]" Type="MessageType.Info" />
</Authorized>
<NotAuthorized>
<form @ref="login" class="@(validated ? "was-validated" : "needs-validation")" novalidate>
<div class="container Oqtane-Modules-Admin-Login" @onkeypress="@(e => KeyPressed(e))">
Expand Down Expand Up @@ -112,11 +118,10 @@
if (user.IsAuthenticated)
{
await logger.LogInformation("Login Successful For Username {Username}", _username);
// complete the login on the server so that the cookies are set correctly on SignalR
// complete the login on the server so that the cookies are set correctly
string antiforgerytoken = await interop.GetElementByName("__RequestVerificationToken");
var fields = new { __RequestVerificationToken = antiforgerytoken, username = _username, password = _password, remember = _remember, returnurl = _returnUrl };
string url = "/pages/login/";
if (!string.IsNullOrEmpty(PageState.Alias.Path)) url = "/" + PageState.Alias.Path + url;
string url = Utilities.TenantUrl(PageState.Alias, "/pages/login/");
await interop.SubmitForm(url, fields);
}
else
Expand Down
2 changes: 1 addition & 1 deletion Oqtane.Client/Modules/Admin/Register/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

@if (PageState.Site.AllowRegistration)
{
<AuthorizeView>
<AuthorizeView Roles="@RoleNames.Registered">
<Authorizing>
<text>...</text>
</Authorizing>
Expand Down
7 changes: 4 additions & 3 deletions Oqtane.Client/Modules/Admin/Sites/Add.razor
Original file line number Diff line number Diff line change
Expand Up @@ -301,15 +301,15 @@ else
connectionString = databaseConfigControl.GetConnectionString();
}
var database = _databases.SingleOrDefault(d => d.Name == _databaseName);

if (connectionString != "")
{
config.TenantName = _tenantName;
config.DatabaseType = database.DBType;
config.ConnectionString = connectionString;
config.HostPassword = _hostpassword;
config.HostEmail = user.Email;
config.HostPassword = _hostpassword;
config.HostName = user.DisplayName;
config.TenantName = _tenantName;
config.IsNewTenant = true;
}
else
Expand All @@ -333,6 +333,7 @@ else
if (tenant != null)
{
config.TenantName = tenant.Name;
config.DatabaseType = tenant.DBType;
config.ConnectionString = tenant.DBConnectionString;
config.IsNewTenant = false;
}
Expand Down
29 changes: 12 additions & 17 deletions Oqtane.Client/Providers/IdentityAuthenticationStateProvider.cs
Original file line number Diff line number Diff line change
@@ -1,29 +1,27 @@
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Oqtane.Models;
using Oqtane.Services;
using Oqtane.Security;
using Oqtane.Shared;

namespace Oqtane.Providers
{
public class IdentityAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly NavigationManager _navigationManager;
private readonly SiteState _siteState;
private readonly IServiceProvider _serviceProvider;

public IdentityAuthenticationStateProvider(NavigationManager navigationManager, SiteState siteState, IServiceProvider serviceProvider)
private readonly NavigationManager _navigationManager;

public IdentityAuthenticationStateProvider(IServiceProvider serviceProvider, NavigationManager navigationManager)
{
_navigationManager = navigationManager;
_siteState = siteState;
_serviceProvider = serviceProvider;
_navigationManager = navigationManager;
}

public override async Task<AuthenticationState> GetAuthenticationStateAsync()
Expand All @@ -32,17 +30,14 @@ public override async Task<AuthenticationState> GetAuthenticationStateAsync()

// get HttpClient lazily from IServiceProvider as you cannot use standard dependency injection due to the AuthenticationStateProvider being initialized prior to NavigationManager(https://github.com/aspnet/AspNetCore/issues/11867 )
var http = _serviceProvider.GetRequiredService<HttpClient>();
string apiurl = "/api/User/authenticate";
User user = await http.GetFromJsonAsync<User>(apiurl);
// get alias as SiteState has not been initialized ( cannot use AliasService as it is not yet registered )
var path = new Uri(_navigationManager.Uri).LocalPath.Substring(1);
var alias = await http.GetFromJsonAsync<Alias>($"/api/Alias/name/?path={WebUtility.UrlEncode(path)}&sync={DateTime.UtcNow.ToString("yyyyMMddHHmmssfff")}");
// get user
User user = await http.GetFromJsonAsync<User>(Utilities.TenantUrl(alias, "/api/User/authenticate"));
if (user.IsAuthenticated)
{
identity = new ClaimsIdentity("Identity.Application");
identity.AddClaim(new Claim(ClaimTypes.Name, user.Username));
identity.AddClaim(new Claim(ClaimTypes.PrimarySid, user.UserId.ToString()));
foreach (string role in user.Roles.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
identity = UserSecurity.CreateClaimsIdentity(alias, user);
}

return new AuthenticationState(new ClaimsPrincipal(identity));
Expand Down
15 changes: 8 additions & 7 deletions Oqtane.Client/Services/AliasService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,36 +19,37 @@ public AliasService(HttpClient http, SiteState siteState) : base(http)
_siteState = siteState;
}

private string Apiurl => CreateApiUrl("Alias", _siteState.Alias);
private string ApiUrl => CreateApiUrl("Alias", _siteState.Alias);

public async Task<List<Alias>> GetAliasesAsync()
{
List<Alias> aliases = await GetJsonAsync<List<Alias>>(Apiurl);
List<Alias> aliases = await GetJsonAsync<List<Alias>>(ApiUrl);
return aliases.OrderBy(item => item.Name).ToList();
}

public async Task<Alias> GetAliasAsync(int aliasId)
{
return await GetJsonAsync<Alias>($"{Apiurl}/{aliasId}");
return await GetJsonAsync<Alias>($"{ApiUrl}/{aliasId}");
}

public async Task<Alias> GetAliasAsync(string path, DateTime lastSyncDate)
{
return await GetJsonAsync<Alias>($"{Apiurl}/name/?path={WebUtility.UrlEncode(path)}&sync={lastSyncDate.ToString("yyyyMMddHHmmssfff")}");
// tenant agnostic as SiteState does not exist
return await GetJsonAsync<Alias>($"{CreateApiUrl("Alias", null)}/name/?path={WebUtility.UrlEncode(path)}&sync={lastSyncDate.ToString("yyyyMMddHHmmssfff")}");
}

public async Task<Alias> AddAliasAsync(Alias alias)
{
return await PostJsonAsync<Alias>(Apiurl, alias);
return await PostJsonAsync<Alias>(ApiUrl, alias);
}

public async Task<Alias> UpdateAliasAsync(Alias alias)
{
return await PutJsonAsync<Alias>($"{Apiurl}/{alias.AliasId}", alias);
return await PutJsonAsync<Alias>($"{ApiUrl}/{alias.AliasId}", alias);
}
public async Task DeleteAliasAsync(int aliasId)
{
await DeleteAsync($"{Apiurl}/{aliasId}");
await DeleteAsync($"{ApiUrl}/{aliasId}");
}
}
}
2 changes: 1 addition & 1 deletion Oqtane.Client/Services/InstallationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public InstallationService(HttpClient http, SiteState siteState) : base(http)
_siteState = siteState;
}

private string ApiUrl => CreateApiUrl("Installation", _siteState.Alias);
private string ApiUrl => CreateApiUrl("Installation", null); // tenant agnostic as SiteState does not exist

public async Task<Installation> IsInstalled()
{
Expand Down
6 changes: 1 addition & 5 deletions Oqtane.Client/Services/ServiceBase.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
Expand Down Expand Up @@ -81,7 +81,6 @@ protected async Task<string> GetStringAsync(string uri)
}
catch (Exception e)
{
//TODO replace with logging
Console.WriteLine(e);
}

Expand Down Expand Up @@ -169,8 +168,6 @@ private bool CheckResponse(HttpResponseMessage response)
if (response.IsSuccessStatusCode) return true;
if (response.StatusCode != HttpStatusCode.NoContent && response.StatusCode != HttpStatusCode.NotFound)
{
//TODO: Log errors here

Console.WriteLine($"Request: {response.RequestMessage.RequestUri}");
Console.WriteLine($"Response status: {response.StatusCode} {response.ReasonPhrase}");
}
Expand All @@ -182,7 +179,6 @@ private static bool ValidateJsonContent(HttpContent content)
{
var mediaType = content?.Headers.ContentType?.MediaType;
return mediaType != null && mediaType.Equals("application/json", StringComparison.OrdinalIgnoreCase);
//TODO Missing content JSON validation
}

[Obsolete("This method is obsolete. Use CreateApiUrl(Alias alias, string serviceName) instead.", false)]
Expand Down
2 changes: 1 addition & 1 deletion Oqtane.Client/Themes/Controls/Theme/ControlPanel.razor
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@
<LanguageSwitcher />
}

@if (UserSecurity.IsAuthorized(PageState.User, PermissionNames.Edit, PageState.Page.Permissions) || (PageState.Page.IsPersonalizable && PageState.User != null))
@if (UserSecurity.IsAuthorized(PageState.User, PermissionNames.Edit, PageState.Page.Permissions) || (PageState.Page.IsPersonalizable && PageState.User != null && UserSecurity.IsAuthorized(PageState.User, RoleNames.Registered)))
{
if (PageState.EditMode)
{
Expand Down
2 changes: 1 addition & 1 deletion Oqtane.Client/Themes/Controls/Theme/Login.razor
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
@inject IStringLocalizer<Login> Localizer

<span class="app-login">
<AuthorizeView>
<AuthorizeView Roles="@RoleNames.Registered">
<Authorizing>
<text>...</text>
</Authorizing>
Expand Down
3 changes: 1 addition & 2 deletions Oqtane.Client/Themes/Controls/Theme/LoginBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ protected async Task LogoutUser()
var interop = new Interop(jsRuntime);
string antiforgerytoken = await interop.GetElementByName("__RequestVerificationToken");
var fields = new { __RequestVerificationToken = antiforgerytoken, returnurl = !authorizedtoviewpage ? PageState.Alias.Path : PageState.Alias.Path + "/" + PageState.Page.Path };
string url = "/pages/logout/";
if (!string.IsNullOrEmpty(PageState.Alias.Path)) url = "/" + PageState.Alias.Path + url;
string url = Utilities.TenantUrl(PageState.Alias, "/pages/logout/");
await interop.SubmitForm(url, fields);
}
else
Expand Down
2 changes: 1 addition & 1 deletion Oqtane.Client/Themes/Controls/Theme/UserProfile.razor
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
@inject NavigationManager NavigationManager

<span class="app-profile">
<AuthorizeView>
<AuthorizeView Roles="@RoleNames.Registered">
<Authorizing>
<text>...</text>
</Authorizing>
Expand Down
10 changes: 5 additions & 5 deletions Oqtane.Client/UI/SiteRouter.razor
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
@inject IUserService UserService
@inject IModuleService ModuleService
@inject ILogService LogService
@inject IJSRuntime JSRuntime
@implements IHandleAfterRender

@DynamicComponent
Expand Down Expand Up @@ -107,7 +108,7 @@
SiteState.Alias = alias; // set state for services
lastsyncdate = alias.SyncDate;

// process any sync events
// process any sync events
if (reload != Reload.Site && alias.SyncEvents.Any())
{
// if running on WebAssembly reload the client application if the server application was restarted
Expand Down Expand Up @@ -330,15 +331,13 @@
await Refresh();
}

Task IHandleAfterRender.OnAfterRenderAsync()
async Task IHandleAfterRender.OnAfterRenderAsync()
{
if (!_navigationInterceptionEnabled)
{
_navigationInterceptionEnabled = true;
return NavigationInterception.EnableNavigationInterceptionAsync();
await NavigationInterception.EnableNavigationInterceptionAsync();
}

return Task.CompletedTask;
}

private Dictionary<string, string> ParseQueryString(string query)
Expand Down Expand Up @@ -556,4 +555,5 @@
=> RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER"))
? Oqtane.Shared.Runtime.WebAssembly
: Oqtane.Shared.Runtime.Server;

}
2 changes: 1 addition & 1 deletion Oqtane.Server/Controllers/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ public async Task<User> Login([FromBody] User user, bool setCookie, bool isPersi
[Authorize]
public async Task Logout([FromBody] User user)
{
await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
await HttpContext.SignOutAsync(Constants.AuthenticationScheme);
_logger.Log(LogLevel.Information, this, LogFunction.Security, "User Logout {Username}", (user != null) ? user.Username : "");
}

Expand Down
27 changes: 15 additions & 12 deletions Oqtane.Server/Pages/Login.cshtml.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Threading.Tasks;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
Expand All @@ -21,20 +21,23 @@ public LoginModel(UserManager<IdentityUser> identityUserManager, SignInManager<I

public async Task<IActionResult> OnPostAsync(string username, string password, bool remember, string returnurl)
{
bool validuser = false;
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(username);
if (identityuser != null)
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, password, false);
if (result.Succeeded)
bool validuser = false;
IdentityUser identityuser = await _identityUserManager.FindByNameAsync(username);
if (identityuser != null)
{
validuser = true;
var result = await _identitySignInManager.CheckPasswordSignInAsync(identityuser, password, false);
if (result.Succeeded)
{
validuser = true;
}
}
}

if (validuser)
{
await _identitySignInManager.SignInAsync(identityuser, remember);
if (validuser)
{
await _identitySignInManager.SignInAsync(identityuser, remember);
}
}

if (returnurl == null)
Expand All @@ -49,4 +52,4 @@ public async Task<IActionResult> OnPostAsync(string username, string password, b
return LocalRedirect(Url.Content("~" + returnurl));
}
}
}
}
11 changes: 7 additions & 4 deletions Oqtane.Server/Pages/Logout.cshtml.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Threading.Tasks;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Oqtane.Shared;

namespace Oqtane.Pages
{
Expand All @@ -12,7 +12,10 @@ public class LogoutModel : PageModel
{
public async Task<IActionResult> OnPostAsync(string returnurl)
{
await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
if (HttpContext.User.Identity.IsAuthenticated)
{
await HttpContext.SignOutAsync(Constants.AuthenticationScheme);
}

if (returnurl == null)
{
Expand All @@ -26,4 +29,4 @@ public async Task<IActionResult> OnPostAsync(string returnurl)
return LocalRedirect(Url.Content("~" + returnurl));
}
}
}
}
Loading

0 comments on commit ddc4254

Please sign in to comment.