Skip to content

Commit

Permalink
refactor:merged ID4 into API host
Browse files Browse the repository at this point in the history
  • Loading branch information
thangchungnt committed Oct 12, 2017
1 parent 5806db2 commit edc39c6
Show file tree
Hide file tree
Showing 65 changed files with 157 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ public static IApplicationBuilder UseSwaggerUiForBlog(this IApplicationBuilder a
c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Blog Core APIs");
c.ConfigureOAuth2("swagger", "secret".Sha256(), "swagger", "swagger");
c.ConfigureOAuth2("local_swagger", "secret".Sha256(), "local_swagger", "local_swagger");
// c.ConfigureOAuth2("swagger", "secret".Sha256(), "swagger", "swagger");
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using Autofac.Extensions.DependencyInjection;
using BlogCore.Infrastructure.EfCore;
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -73,7 +72,7 @@ public static void AddIdentityServerForBlog(this IServiceCollection services, Fu
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "http://localhost:8483";
options.Authority = "http://localhost:8484";
options.Audience = "blogcore_api_resource";
options.RequireHttpsMetadata = false;

Expand Down Expand Up @@ -121,12 +120,13 @@ public static IServiceCollection AddSwaggerForBlog(this IServiceCollection servi
Version = "v1",
Description = "Blog Core APIs"
});

options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
TokenUrl = "http://localhost:8483/connect/token",
AuthorizationUrl = "http://localhost:8483/connect/authorize",
Flow = "password", // "implicit",
TokenUrl = "http://localhost:8484/connect/token",
AuthorizationUrl = "http://localhost:8484/connect/authorize",
Scopes = new Dictionary<string, string>
{
{"blogcore_api_scope", "The Blog APIs"}
Expand Down
10 changes: 9 additions & 1 deletion src/Hosts/BlogCore.Api/BlogCore.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
</PropertyGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
<Compile Remove="wwwroot\**" />
<Content Remove="wwwroot\**" />
<EmbeddedResource Remove="wwwroot\**" />
<None Remove="wwwroot\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
Expand All @@ -22,13 +25,18 @@
<PackageReference Include="IdentityServer4" Version="2.0.0-rc1-update1" />
<PackageReference Include="IdentityServer4.AspNetIdentity" Version="2.0.0-rc1-update1" />
<PackageReference Include="IdentityServer4.EntityFramework" Version="2.0.0-rc1" />
<PackageReference Include="BundlerMinifier.Core" Version="2.4.337" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Framework\BlogCore.Core\BlogCore.Core.csproj" />
<ProjectReference Include="..\..\Framework\BlogCore.Infrastructure\BlogCore.Infrastructure.csproj" />
<ProjectReference Include="..\..\Framework\BlogCore.Infrastructure.AspNetCore\BlogCore.Infrastructure.AspNetCore.csproj" />
<ProjectReference Include="..\..\Framework\BlogCore.Infrastructure.EfCore\BlogCore.Infrastructure.EfCore.csproj" />
<ProjectReference Include="..\..\Modules\BlogCore.AccessControlContext\BlogCore.AccessControlContext.csproj" />
<ProjectReference Include="..\..\Modules\BlogCore.BlogContext\BlogCore.BlogContext.csproj" />
<ProjectReference Include="..\..\Modules\BlogCore.PostContext\BlogCore.PostContext.csproj" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Collections.Generic;
using System.Linq;

namespace BlogCore.Api.Posts.ListOutPostByBlog
namespace BlogCore.Api.Features.Posts.ListOutPostByBlog
{
public class ListOutPostByBlogPresenter
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using BlogCore.Api.Posts.ListOutPostByBlog;
using BlogCore.Api.Features.Posts.ListOutPostByBlog;
using BlogCore.Core;
using BlogCore.Core.Helpers;
using BlogCore.PostContext.Domain;
Expand All @@ -8,7 +8,7 @@
using System;
using System.Threading.Tasks;

namespace BlogCore.Api.Posts
namespace BlogCore.Api.Features.Posts
{
[Route("api/public/blogs")]
public class PostPublicApiController : Controller
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Microsoft.AspNetCore.Mvc;

namespace BlogCore.Api.Tags
namespace BlogCore.Api.Features.Tags
{
[Route("api/tags")]
public class TagApiController : Controller
Expand Down
121 changes: 116 additions & 5 deletions src/Hosts/BlogCore.Api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
#region libs

using BlogCore.AccessControl;
using BlogCore.Api.Posts;
using BlogCore.Api.Posts.ListOutPostByBlog;
using BlogCore.AccessControlContext.Domain;
using BlogCore.AccessControlContext.Infrastructure;
using BlogCore.Api.Features.Posts.ListOutPostByBlog;
using BlogCore.BlogContext;
using BlogCore.BlogContext.Infrastructure;
using BlogCore.Core;
using BlogCore.Infrastructure.AspNetCore;
using BlogCore.Infrastructure.EfCore;
using BlogCore.PostContext;
using IdentityModel;
using IdentityServer4;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -48,6 +57,38 @@ public Startup(IHostingEnvironment env)

public IServiceProvider ConfigureServices(IServiceCollection services)
{
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

// Add framework services.
services.AddDbContext<IdentityServerDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MainDb")));

services.AddIdentity<AppUser, IdentityRole>()
.AddEntityFrameworkStores<IdentityServerDbContext>()
.AddDefaultTokenProviders();

services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(Configuration.GetConnectionString("MainDb"),
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(Configuration.GetConnectionString("MainDb"),
sql => sql.MigrationsAssembly(migrationsAssembly));

// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30;
})
.AddConfigurationStoreCache()
.AddAspNetIdentity<AppUser>()
.AddProfileService<IdentityWithAdditionalClaimsProfileService>();

services.AddCorsForBlog()
// .AddAuthorizationForBlog()
.AddMvcForBlog(RegisteredAssemblies());
Expand Down Expand Up @@ -82,9 +123,20 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
ctx.Context.Response.Headers[HeaderNames.CacheControl] =
"public,max-age=" + maxAge.TotalSeconds.ToString("0");
}
})
.UseCors("CorsPolicy")
.UseMvc();
});

var fordwardedHeaderOptions = new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
};
fordwardedHeaderOptions.KnownNetworks.Clear();
fordwardedHeaderOptions.KnownProxies.Clear();

app.UseForwardedHeaders(fordwardedHeaderOptions);
app.UseIdentityServer();

app.UseCors("CorsPolicy")
.UseMvcWithDefaultRoute();

if (env.IsDevelopment())
app.UseSwaggerUiForBlog();
Expand Down Expand Up @@ -129,4 +181,63 @@ private static async Task OnTokenValidated(TokenValidatedContext context)
await Task.FromResult(0);
}
}

public class IdentityWithAdditionalClaimsProfileService : IProfileService
{
private readonly IUserClaimsPrincipalFactory<AppUser> _claimsFactory;
private readonly UserManager<AppUser> _userManager;

public IdentityWithAdditionalClaimsProfileService(UserManager<AppUser> userManager,
IUserClaimsPrincipalFactory<AppUser> claimsFactory)
{
_userManager = userManager;
_claimsFactory = claimsFactory;
}

public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var sub = context.Subject.GetSubjectId();

var user = await _userManager.FindByIdAsync(sub);
var principal = await _claimsFactory.CreateAsync(user);

var claims = principal.Claims.ToList();

claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();

claims.Add(new Claim(JwtClaimTypes.Name, user.UserName));
claims.Add(new Claim(JwtClaimTypes.FamilyName, user.FamilyName));
claims.Add(new Claim(JwtClaimTypes.GivenName, user.GivenName));
claims.Add(new Claim("bio", user.Bio));
claims.Add(new Claim("company", user.Company));
claims.Add(new Claim("location", user.Location));
claims.Add(new Claim(JwtClaimTypes.Role, "blogcore_blogs"));

var isAdmin = claims.Any(claim => claim.Type == "role" && claim.Value == "admin");
if (isAdmin)
{
claims.Add(new Claim(JwtClaimTypes.Role, "admin"));
}
else
{
claims.Add(new Claim(JwtClaimTypes.Role, "user"));
}

if (user.BlogId.HasValue)
{
claims.Add(new Claim("blog_id", user.BlogId.Value.ToString()));
}

claims.Add(new Claim(IdentityServerConstants.StandardScopes.Email, user.Email));

context.IssuedClaims = claims;
}

public async Task IsActiveAsync(IsActiveContext context)
{
var sub = context.Subject.GetSubjectId();
var user = await _userManager.FindByIdAsync(sub);
context.IsActive = user != null;
}
}
}
1 change: 1 addition & 0 deletions src/Hosts/BlogCore.Api/tempkey.rsa
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"KeyId":"55ec433b001382069c816bf0b14eaa45","Parameters":{"D":"A5/Nert2Ns6rzNxqZfq+zpfShGUughKDrOw5CI4ceXCNL6CZH/s756Uv9GNh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bFvcucqr8795oIc7sASHe+LUYJmd5UM4sOqOkHIUstIXbAHW9nDUQ/YARHsQ4410xSr8Y5lG3m94rP5tvA/1zCih0ZQ+FE0j/tFdc6eKy5CVUQ==","P":"wiEYb207wpug+XJxDKxiL7ZWxx8HwgpXnyGa1h4Qi+handCo6OalkAov7gRQeLGFxHzQh42T3sCXYHh32BZPJqyfZsv34SfOI5pxZmld+LAlul55P2fntJ8Zytsmf/9Xj3sppUZL9F7/x8BfWxO7UY9tpbP8c8BNo2L/6l/wIzU=","Q":"8Ou8IuDPbAt/XS3moJ6jECFQmfv2DkfnPBT2K5cfNAFpKLrotao3Dw+qVp+utBqXRSPoQk7nAgu5MYdagUGms6bdAd7TvxMsc5vXYOdWURn7M/D5tVwYP9YsvgnB6UooWcKwfZUshnuNcMvfl6wsfA5iZK3mCjBSzVtm2b2QcS0="}}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,26 @@ public static IEnumerable<Client> GetClients()
"blogcore_identity_scope",
"blogcore_api_scope"
}
},

// swagger UI
new Client
{
ClientId = "local_swagger",
ClientName = "local_swagger",
ClientSecrets = new List<Secret> {new Secret("secret".Sha256())},
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
AccessTokenType = AccessTokenType.Jwt,
AllowedScopes =
{
"openid",
"profile",
"role",
"user",
"admin",
"blogcore_identity_scope",
"blogcore_api_scope"
}
}
};
}
Expand Down

0 comments on commit edc39c6

Please sign in to comment.