Skip to content

Commit

Permalink
Add IdentityServer4
Browse files Browse the repository at this point in the history
  • Loading branch information
JuergenGutsch committed Feb 28, 2018
1 parent eb83c76 commit af3ae71
Show file tree
Hide file tree
Showing 114 changed files with 44,043 additions and 55 deletions.
11 changes: 7 additions & 4 deletions ReactChatDemo/Controllers/ChatController.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ReactChatDemo.Models;
using ReactChatDemo.Services;

namespace ReactChatDemo.Controllers
{
[Route("api/[controller]")]
// [Authorize]
public class ChatController : Controller
{
private readonly IChatService _chatService;
Expand All @@ -19,11 +20,13 @@ public ChatController(IChatService chatService)
[HttpGet("[action]")]
public IEnumerable<UserDetails> LoggedOnUsers()
{
return new[]{
return new[]
{
new UserDetails { Id = 1, Name = "Joe" },
new UserDetails { Id = 3, Name = "Mary" },
new UserDetails { Id = 2, Name = "Pete" },
new UserDetails { Id = 4, Name = "Mo" } };
new UserDetails { Id = 4, Name = "Mo" }
};
}

[HttpGet("[action]")]
Expand Down
3 changes: 3 additions & 0 deletions ReactChatDemo/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ReactChatDemo.User;

namespace ReactChatDemo.Controllers
{
[Authorize]
public class HomeController : Controller
{
public IActionResult Index()
Expand Down
8 changes: 3 additions & 5 deletions ReactChatDemo/Hubs/ChatHub.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using ReactChatDemo.User;
using Microsoft.AspNetCore.SignalR;
using ReactChatDemo.Models;
using System;
using Microsoft.AspNetCore.SignalR;
using ReactChatDemo.Services;

namespace ReactChatDemo.Hubs
Expand All @@ -17,7 +14,8 @@ public ChatHub(IChatService chatService)

public void AddMessage(string message)
{
var chatMessage = _chatService.CreateNewMessage("Juergen", message);
var username = Context.User.Identity.Name;
var chatMessage = _chatService.CreateNewMessage(username, message);
// Call the MessageAdded method to update clients.
Clients.All.InvokeAsync("MessageAdded", chatMessage);
}
Expand Down
8 changes: 2 additions & 6 deletions ReactChatDemo/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace ReactChatDemo
{
public class Program
{
public static void Main(string[] args)
{
Console.Title = "React Chat Demo";

BuildWebHost(args).Run();
}

Expand Down
7 changes: 7 additions & 0 deletions ReactChatDemo/ReactChatDemo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="IdentityModel" Version="3.1.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.3.0" />
<PackageReference Include="IdentityServer4.EntityFramework" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.5" />
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.0-alpha2-final" />
</ItemGroup>
Expand Down Expand Up @@ -37,6 +40,10 @@
<TypeScriptCompile Include="ClientApp\services\WebsocketService.ts" />
</ItemGroup>

<ItemGroup>
<Folder Include="Data\" />
</ItemGroup>

<Target Name="DebugRunWebpack" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('wwwroot\dist') ">
<!-- Ensure Node.js is installed -->
<Exec Command="node --version" ContinueOnError="true">
Expand Down
82 changes: 81 additions & 1 deletion ReactChatDemo/Services/ChatService.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,89 @@
using ReactChatDemo.Models;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using ReactChatDemo.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ReactChatDemo.Services
{
public class ChatMessageRepository : IChatMessageRepository
{
private const string accountName = "reactchatdemo";
private const string accountKey = "hxBCWoyJaOdI0QbtaL2neMCQo+2QH9RjtjAiSlWh/2DLlRZOhnurDG8KFmaCHW/SJWkQGXPhmQkecPp+RP2rgA==";
private const string tableName = "reactchatmessages";

private readonly CloudTableClient _tableClient;

public ChatMessageRepository()
{
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
_tableClient = storageAccount.CreateCloudTableClient();

}

// https://docs.microsoft.com/en-us/azure/cosmos-db/table-storage-how-to-use-dotnet
public async Task<List<ChatMessageTableEntity>> GetTopMessages(int number = 100)
{
var table = _tableClient.GetTableReference(tableName);

// Create the table if it doesn't exist.
await table.CreateIfNotExistsAsync();

var query = new TableQuery<ChatMessageTableEntity>()
.Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "chatmessages"))
.Take(number);

var result = await table.ExecuteQuerySegmentedAsync(query, null);

return result.Results;
}

// https://docs.microsoft.com/en-us/azure/cosmos-db/table-storage-how-to-use-dotnet
public async Task<ChatMessageTableEntity> AddMessage(string message, string sender)
{
var table = _tableClient.GetTableReference(tableName);

// Create the table if it doesn't exist.
await table.CreateIfNotExistsAsync();

var chatMessage = new ChatMessageTableEntity(Guid.NewGuid())
{
Message = message,
Sender = sender
};

// Create the TableOperation object that inserts the customer entity.
TableOperation insertOperation = TableOperation.Insert(chatMessage);

// Execute the insert operation.
await table.ExecuteAsync(insertOperation);

return chatMessage;
}

}

public class ChatMessageTableEntity : TableEntity
{
public ChatMessageTableEntity(Guid key)
{
PartitionKey = "chatmessages";
RowKey = key.ToString("X");
}

public ChatMessageTableEntity() { }

public string Message { get; set; }

public string Sender { get; set; }
}

public interface IChatMessageRepository
{
}

public class ChatService : IChatService
{
private IDictionary<int, ChatMessage> messages;
Expand Down
29 changes: 28 additions & 1 deletion ReactChatDemo/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
Expand Down Expand Up @@ -28,6 +31,28 @@ public void ConfigureServices(IServiceCollection services)
services.AddSignalR();
services.AddSingleton<IUserTracker, UserTracker>();
services.AddSingleton<IChatService, ChatService>();


JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5002";
options.RequireHttpsMetadata = false;
options.TokenValidationParameters.NameClaimType = "name";
options.ClientId = "reactchat";
options.SaveTokens = true;
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand All @@ -47,8 +72,10 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseExceptionHandler("/Home/Error");
}

app.UseAuthentication();

app.UseStaticFiles();

app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("chat");
Expand Down
37 changes: 0 additions & 37 deletions ReactChatDemo/User/IUserTracker.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using ReactChatDemo.Models;
Expand All @@ -16,40 +15,4 @@ public interface IUserTracker
event Action<UserDetails> UserJoined;
event Action<UserDetails> UserLeft;
}

public class UserTracker : IUserTracker
{
public event Action<UserDetails> UserJoined;
public event Action<UserDetails> UserLeft;

private ICollection<UserDetails> joinedUsers = new List<UserDetails>();

public void AddUser(HubConnectionContext connection, UserDetails userDetails)
{
userDetails.ConnectionId = connection.ConnectionId;

if (!joinedUsers.Any(x => x.Id == userDetails.Id))
{
joinedUsers.Add(userDetails);
UserJoined?.Invoke(userDetails);
}
}

public void RemoveUser(HubConnectionContext connection)
{
var connectionId = connection.ConnectionId;

var user = joinedUsers.FirstOrDefault(x => x.ConnectionId == connectionId);
if (user != null)
{
joinedUsers.Remove(user);
UserLeft?.Invoke(user);
}
}

public Task<ICollection<UserDetails>> UsersOnline()
{
return Task.FromResult(joinedUsers);
}
}
}
45 changes: 45 additions & 0 deletions ReactChatDemo/User/UserTracker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using ReactChatDemo.Models;

namespace ReactChatDemo.User
{
public class UserTracker : IUserTracker
{
public event Action<UserDetails> UserJoined;
public event Action<UserDetails> UserLeft;

private ICollection<UserDetails> joinedUsers = new List<UserDetails>();

public void AddUser(HubConnectionContext connection, UserDetails userDetails)
{
userDetails.ConnectionId = connection.ConnectionId;

if (!joinedUsers.Any(x => x.Id == userDetails.Id))
{
joinedUsers.Add(userDetails);
UserJoined?.Invoke(userDetails);
}
}

public void RemoveUser(HubConnectionContext connection)
{
var connectionId = connection.ConnectionId;

var user = joinedUsers.FirstOrDefault(x => x.ConnectionId == connectionId);
if (user != null)
{
joinedUsers.Remove(user);
UserLeft?.Invoke(user);
}
}

public Task<ICollection<UserDetails>> UsersOnline()
{
return Task.FromResult(joinedUsers);
}
}
}
Loading

0 comments on commit af3ae71

Please sign in to comment.