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

Remove MagicOnion.Server.Authentication #483

Merged
merged 2 commits into from
Dec 13, 2021
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
2 changes: 0 additions & 2 deletions .github/workflows/build-canary.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ jobs:
- run: dotnet build ./src/MagicOnion.Server/ -c Release -p:VersionSuffix=${MAGICONION_VERSION}
- run: dotnet build ./src/MagicOnion.Server.HttpGateway/ -c Release -p:VersionSuffix=${MAGICONION_VERSION}
- run: dotnet build ./src/MagicOnion.Server.Redis/ -c Release -p:VersionSuffix=${MAGICONION_VERSION}
- run: dotnet build ./src/MagicOnion.Server.Authentication/ -c Release -p:VersionSuffix=${MAGICONION_VERSION}
#- run: dotnet build ./src/MagicOnion.Server.OpenTelemetry/ -c Release -p:VersionSuffix=${MAGICONION_VERSION}
- run: dotnet build ./src/MagicOnion.MSBuild.Tasks/ -c Release -p:VersionSuffix=${MAGICONION_VERSION}
- run: dotnet build ./src/MagicOnion.Generator/ -c Release -p:VersionSuffix=${MAGICONION_VERSION}
Expand All @@ -48,7 +47,6 @@ jobs:
- run: dotnet pack ./src/MagicOnion.Server/MagicOnion.Server.csproj -c Release --include-symbols --include-source --no-build -p:VersionSuffix=${MAGICONION_VERSION} -o ./publish
- run: dotnet pack ./src/MagicOnion.Server.HttpGateway/MagicOnion.Server.HttpGateway.csproj -c Release --include-symbols --include-source --no-build -p:VersionSuffix=${MAGICONION_VERSION} -o ./publish
- run: dotnet pack ./src/MagicOnion.Server.Redis/MagicOnion.Server.Redis.csproj -c Release --include-symbols --include-source --no-build -p:VersionSuffix=${MAGICONION_VERSION} -o ./publish
- run: dotnet pack ./src/MagicOnion.Server.Authentication/MagicOnion.Server.Authentication.csproj -c Release --include-symbols --include-source --no-build -p:VersionSuffix=${MAGICONION_VERSION} -o ./publish
#- run: dotnet pack ./src/MagicOnion.Server.OpenTelemetry/MagicOnion.Server.OpenTelemetry.csproj -c Release --include-symbols --include-source --no-build -p:VersionSuffix=${MAGICONION_VERSION} -o ./publish
- run: dotnet pack ./src/MagicOnion.MSBuild.Tasks/MagicOnion.MSBuild.Tasks.csproj -c Release --include-symbols --include-source --no-build -p:VersionSuffix=${MAGICONION_VERSION} -o ./publish
- run: dotnet pack ./src/MagicOnion.Generator/MagicOnion.Generator.csproj -c Release --include-symbols --include-source --no-build -p:VersionSuffix=${MAGICONION_VERSION} -o ./publish
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/build-debug.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ jobs:
- run: dotnet build ./src/MagicOnion.Server/ -c Debug
- run: dotnet build ./src/MagicOnion.Server.HttpGateway/ -c Debug
- run: dotnet build ./src/MagicOnion.Server.Redis/ -c Debug
- run: dotnet build ./src/MagicOnion.Server.Authentication/ -c Debug
#- run: dotnet build ./src/MagicOnion.Server.OpenTelemetry/ -c Debug
- run: dotnet build ./src/MagicOnion.MSBuild.Tasks/ -c Debug
- run: dotnet build ./src/MagicOnion.Generator/ -c Debug
Expand Down
2 changes: 0 additions & 2 deletions .github/workflows/build-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ jobs:
- run: dotnet build ./src/MagicOnion.Server/ -c Release -p:VersionPrefix=${{ env.GIT_TAG }}
- run: dotnet build ./src/MagicOnion.Server.HttpGateway/ -c Release -p:VersionPrefix=${{ env.GIT_TAG }}
- run: dotnet build ./src/MagicOnion.Server.Redis/ -c Release -p:VersionPrefix=${{ env.GIT_TAG }}
- run: dotnet build ./src/MagicOnion.Server.Authentication/ -c Release -p:VersionPrefix=${{ env.GIT_TAG }}
#- run: dotnet build ./src/MagicOnion.Server.OpenTelemetry/ -c Release -p:VersionPrefix=${{ env.GIT_TAG }}
- run: dotnet build ./src/MagicOnion.MSBuild.Tasks/ -c Release -p:VersionPrefix=${{ env.GIT_TAG }}
- run: dotnet build ./src/MagicOnion.Generator/ -c Release -p:VersionPrefix=${{ env.GIT_TAG }}
Expand All @@ -110,7 +109,6 @@ jobs:
- run: dotnet pack ./src/MagicOnion.Server/MagicOnion.Server.csproj -c Release --no-build -p:VersionPrefix=${{ env.GIT_TAG }} -o ./publish
- run: dotnet pack ./src/MagicOnion.Server.HttpGateway/MagicOnion.Server.HttpGateway.csproj -c Release --no-build -p:VersionPrefix=${{ env.GIT_TAG }} -o ./publish
- run: dotnet pack ./src/MagicOnion.Server.Redis/MagicOnion.Server.Redis.csproj -c Release --no-build -p:VersionPrefix=${{ env.GIT_TAG }} -o ./publish
- run: dotnet pack ./src/MagicOnion.Server.Authentication/MagicOnion.Server.Authentication.csproj -c Release --no-build -p:VersionPrefix=${{ env.GIT_TAG }} -o ./publish
#- run: dotnet pack ./src/MagicOnion.Server.OpenTelemetry/MagicOnion.Server.OpenTelemetry.csproj -c Release --no-build -p:VersionPrefix=${{ env.GIT_TAG }} -o ./publish
- run: dotnet pack ./src/MagicOnion.MSBuild.Tasks/MagicOnion.MSBuild.Tasks.csproj -c Release --no-build -p:VersionPrefix=${{ env.GIT_TAG }} -o ./publish
- run: dotnet pack ./src/MagicOnion.Generator/MagicOnion.Generator.csproj -c Release --no-build -p:VersionPrefix=${{ env.GIT_TAG }} -o ./publish
Expand Down
11 changes: 2 additions & 9 deletions MagicOnion.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.28729.10
# Visual Studio Version 17
VisualStudioVersion = 17.0.31919.166
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1987061F-8970-4018-8D58-6932961C9EB4}"
EndProject
Expand Down Expand Up @@ -43,8 +43,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{42EBB7E4
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ChatApp.Shared", "samples\ChatApp\ChatApp.Shared\ChatApp.Shared.csproj", "{5CDEE44D-8AC2-4E7C-90CC-669E336F2D15}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MagicOnion.Server.Authentication", "src\MagicOnion.Server.Authentication\MagicOnion.Server.Authentication.csproj", "{8937CACA-862F-4B42-8AFF-EF4747792E8F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ChatApp", "ChatApp", "{FEE2B9AB-A1D0-41BA-A172-FC95935542DF}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "JwtAuthentication", "JwtAuthentication", "{EBF51D3A-A093-4177-865A-D17F816EDEF5}"
Expand Down Expand Up @@ -117,10 +115,6 @@ Global
{5CDEE44D-8AC2-4E7C-90CC-669E336F2D15}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5CDEE44D-8AC2-4E7C-90CC-669E336F2D15}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5CDEE44D-8AC2-4E7C-90CC-669E336F2D15}.Release|Any CPU.Build.0 = Release|Any CPU
{8937CACA-862F-4B42-8AFF-EF4747792E8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8937CACA-862F-4B42-8AFF-EF4747792E8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8937CACA-862F-4B42-8AFF-EF4747792E8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8937CACA-862F-4B42-8AFF-EF4747792E8F}.Release|Any CPU.Build.0 = Release|Any CPU
{93BC9FC7-D157-4541-A05E-C56D31B2F2BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{93BC9FC7-D157-4541-A05E-C56D31B2F2BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{93BC9FC7-D157-4541-A05E-C56D31B2F2BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand Down Expand Up @@ -178,7 +172,6 @@ Global
{EE768243-100A-4075-8823-C49EA086680A} = {1987061F-8970-4018-8D58-6932961C9EB4}
{56C42B86-138C-413B-805A-30D07566660A} = {1987061F-8970-4018-8D58-6932961C9EB4}
{5CDEE44D-8AC2-4E7C-90CC-669E336F2D15} = {FEE2B9AB-A1D0-41BA-A172-FC95935542DF}
{8937CACA-862F-4B42-8AFF-EF4747792E8F} = {1987061F-8970-4018-8D58-6932961C9EB4}
{FEE2B9AB-A1D0-41BA-A172-FC95935542DF} = {5A3F5158-7B17-4586-9885-9E60C1393185}
{EBF51D3A-A093-4177-865A-D17F816EDEF5} = {5A3F5158-7B17-4586-9885-9E60C1393185}
{93BC9FC7-D157-4541-A05E-C56D31B2F2BC} = {EBF51D3A-A093-4177-865A-D17F816EDEF5}
Expand Down
18 changes: 10 additions & 8 deletions samples/JwtAuthentication/JwtAuthApp.Client/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Text;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Client;
Expand All @@ -17,6 +18,7 @@ static Task Main(string[] args)
private async Task MainCore(string[] args)
{
var channel = GrpcChannel.ForAddress("https://localhost:5001");
//var channel = new Channel("127.0.0.1", 5000, ChannelCredentials.Insecure);

// 1. Call an API without an authentication token.
{
Expand Down Expand Up @@ -56,7 +58,7 @@ private async Task MainCore(string[] args)
this,
option: new CallOptions().WithHeaders(new Metadata()
{
{ "auth-token-bin", AuthenticationTokenStorage.Current.Token }
{ "Authorization", "Bearer " + AuthenticationTokenStorage.Current.Token }
}));
await timerHubClient.SetAsync(TimeSpan.FromSeconds(5));
await Task.Yield(); // NOTE: Release the gRPC's worker thread here.
Expand Down Expand Up @@ -96,9 +98,9 @@ class WithAuthenticationFilter : IClientFilter
{
private readonly string _signInId;
private readonly string _password;
private readonly GrpcChannel _channel;
private readonly ChannelBase _channel;

public WithAuthenticationFilter(string signInId, string password, GrpcChannel channel)
public WithAuthenticationFilter(string signInId, string password, ChannelBase channel)
{
_signInId = signInId ?? throw new ArgumentNullException(nameof(signInId));
_password = password ?? throw new ArgumentNullException(nameof(password));
Expand All @@ -121,12 +123,12 @@ public async ValueTask<ResponseContext> SendAsync(RequestContext context, Func<R

AuthenticationTokenStorage.Current.Update(authResult.Token, authResult.Expiration); // NOTE: You can also read the token expiration date from JWT.

context.CallOptions.Headers.Remove(new Metadata.Entry("auth-token-bin", Array.Empty<byte>()));
context.CallOptions.Headers.Remove(new Metadata.Entry("Authorization", string.Empty));
}

if (!context.CallOptions.Headers.Contains(new Metadata.Entry("auth-token-bin", Array.Empty<byte>())))
if (!context.CallOptions.Headers.Contains(new Metadata.Entry("Authorization", string.Empty)))
{
context.CallOptions.Headers.Add("auth-token-bin", AuthenticationTokenStorage.Current.Token);
context.CallOptions.Headers.Add("Authorization", "Bearer " + AuthenticationTokenStorage.Current.Token);
}

return await next(context);
Expand All @@ -141,12 +143,12 @@ class AuthenticationTokenStorage

private readonly object _syncObject = new object();

public byte[] Token { get; private set; }
public string Token { get; private set; }
public DateTimeOffset Expiration { get; private set; }

public bool IsExpired => Token == null || Expiration < DateTimeOffset.Now;

public void Update(byte[] token, DateTimeOffset expiration)
public void Update(string token, DateTimeOffset expiration)
{
lock (_syncObject)
{
Expand Down

This file was deleted.

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace JwtAuthApp.Server.Authentication
{
public class JwtTokenService
{
private readonly SymmetricSecurityKey _securityKey;

public JwtTokenService(IOptions<JwtTokenServiceOptions> jwtTokenServiceOptions)
{
_securityKey = new SymmetricSecurityKey(Convert.FromBase64String(jwtTokenServiceOptions.Value.Secret));
}

public (string Token, DateTime Expires) CreateToken(long userId, string displayName)
{
var jwtTokenHandler = new JwtSecurityTokenHandler();
var expires = DateTime.UtcNow.AddSeconds(10);
var token = jwtTokenHandler.CreateEncodedJwt(new SecurityTokenDescriptor()
{
SigningCredentials = new SigningCredentials(_securityKey, SecurityAlgorithms.HmacSha256),
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, displayName),
new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
}),
Expires = expires,
});

return (token, expires);
}
}

public class JwtTokenServiceOptions
{
public string Secret { get; set; }
}
}
9 changes: 5 additions & 4 deletions samples/JwtAuthentication/JwtAuthApp.Server/Hubs/TimerHub.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using JwtAuthApp.Server.Authentication;
using Grpc.Core;
using JwtAuthApp.Shared;
using MagicOnion.Server;
using MagicOnion.Server.Authentication;
using MagicOnion.Server.Hubs;
using Microsoft.AspNetCore.Authorization;

namespace JwtAuthApp.Server.Hubs
{
Expand All @@ -31,8 +32,8 @@ public async Task SetAsync(TimeSpan interval)
{
await Task.Delay(_interval, _cancellationTokenSource.Token);

var identity = Context.GetPrincipal().Identity as CustomJwtAuthUserIdentity;
BroadcastToSelf(_group).OnTick($"UserId={identity.UserId}; Name={identity.Name}");
var userPrincipal = Context.CallContext.GetHttpContext().User;
BroadcastToSelf(_group).OnTick($"UserId={userPrincipal.Claims.First(x => x.Type == ClaimTypes.NameIdentifier).Value}; Name={userPrincipal.Identity?.Name}");
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\MagicOnion.Server\MagicOnion.Server.csproj" />
<ProjectReference Include="..\..\..\src\MagicOnion.Server.Authentication\MagicOnion.Server.Authentication.csproj" />
<ProjectReference Include="..\JwtAuthApp.Shared\JwtAuthApp.Shared.csproj" />
</ItemGroup>

Expand Down
13 changes: 12 additions & 1 deletion samples/JwtAuthentication/JwtAuthApp.Server/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Hosting;

namespace JwtAuthApp.Server
Expand All @@ -16,7 +17,17 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();

webBuilder
.UseKestrel(options =>
{
// WORKAROUND: Accept HTTP/2 only to allow insecure HTTP/2 connections during development.
options.ConfigureEndpointDefaults(endpointOptions =>
{
endpointOptions.Protocols = HttpProtocols.Http2;
});
})
.UseStartup<Startup>();
});
}
}
Loading