Skip to content

Instantly share code, notes, and snippets.

@bioyeneye
Created May 30, 2020 16:16
Show Gist options
  • Save bioyeneye/cf4eb585c74667ca88d6b3d2620d0cb9 to your computer and use it in GitHub Desktop.
Save bioyeneye/cf4eb585c74667ca88d6b3d2620d0cb9 to your computer and use it in GitHub Desktop.
Resolving openiddict/openiddict-core request null
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Primitives;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Abstractions;
using OpenIddict.Core;
using OpenIddict.EntityFrameworkCore.Models;
using OpenIddict.Server.AspNetCore;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace IdentityProvider.API.Controllers
{
public class AuthorizationController : Controller
{
private readonly OpenIddictApplicationManager<OpenIddictEntityFrameworkCoreApplication> _applicationManager;
public AuthorizationController(OpenIddictApplicationManager<OpenIddictEntityFrameworkCoreApplication> applicationManager)
=> _applicationManager = applicationManager;
//var request = HttpContext.GetOpenIddictServerRequest();
[HttpPost("~/connect/token"), Produces("application/json")]
public async Task<IActionResult> Exchange(OpenIddictRequest request)
{
if (request.IsClientCredentialsGrantType())
{
// Note: the client credentials are automatically validated by OpenIddict:
// if client_id or client_secret are invalid, this action won't be invoked.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId);
if (application == null)
{
throw new InvalidOperationException("The application details cannot be found in the database.");
}
// Create a new ClaimsIdentity containing the claims that
// will be used to create an id_token, a token or a code.
var identity = new ClaimsIdentity(
TokenValidationParameters.DefaultAuthenticationType,
Claims.Name, Claims.Role);
var clientDetails = await _applicationManager.GetClientIdAsync(application);
var clientName = await _applicationManager.GetDisplayNameAsync(application);
// Use the client_id as the subject identifier.
identity.AddClaim(Claims.Subject, clientDetails, Destinations.AccessToken, Destinations.IdentityToken);
identity.AddClaim(Claims.Name, clientName, Destinations.AccessToken, Destinations.IdentityToken);
return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
throw new NotImplementedException("The specified grant type is not implemented.");
}
}
}
using IdentityProvider.DataAccess.Databases;
using IdentityProvider.DataAccess.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace IdentityProvider.API.Extensions
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddApplicationIdentityService(this IServiceCollection services, string connectionString)
{
services.AddDbContext<IdentityDbContext>(options =>
{
options.UseOpenIddict<Guid>();
options.UseSqlServer(connectionString, sqlServerOptionsAction: sqlOptions => { sqlOptions.EnableRetryOnFailure(); });
});
services.AddIdentity<IdentityApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<IdentityDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = Claims.Name;
options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
options.ClaimsIdentity.RoleClaimType = Claims.Role;
});
services.AddOpenIddict()
.AddCore(options =>
{
options.UseEntityFrameworkCore()
.UseDbContext<IdentityDbContext>()
.ReplaceDefaultEntities<Guid>();
})
.AddServer(options =>
{
options.SetAuthorizationEndpointUris("/connect/authorize")
.SetDeviceEndpointUris("/connect/device")
.SetLogoutEndpointUris("/connect/logout")
.SetTokenEndpointUris("/connect/token")
.SetUserinfoEndpointUris("/connect/userinfo")
.SetVerificationEndpointUris("/connect/verify");
options.AllowAuthorizationCodeFlow()
.AllowClientCredentialsFlow()
.AllowDeviceCodeFlow()
.AllowPasswordFlow()
.AllowRefreshTokenFlow();
options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles, "demo_api");
options.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
options.UseAspNetCore()
.EnableTokenEndpointPassthrough()
.EnableStatusCodePagesIntegration()
.EnableAuthorizationEndpointPassthrough()
.EnableLogoutEndpointPassthrough()
.EnableTokenEndpointPassthrough()
.EnableUserinfoEndpointPassthrough()
.EnableVerificationEndpointPassthrough()
.DisableTransportSecurityRequirement(); // During development, you can disable the HTTPS requirement.
options.AcceptAnonymousClients();
})
.AddValidation(options =>
{
options.UseLocalServer();
options.UseAspNetCore();
options.EnableAuthorizationEntryValidation();
options.EnableTokenEntryValidation();
});
return services;
}
public static IServiceCollection AddApplicationCorsService(this IServiceCollection services, string corsPolicyName = "applicationcorspolicy")
{
services.AddCors(options =>
{
options.AddPolicy(name: corsPolicyName,
builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
//builder.AllowCredentials();
});
});
return services;
}
public static IServiceCollection AddApplicationSSlEnforce(this IServiceCollection services, bool enforceSSl = true)
{
if (enforceSSl)
{
services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(60);
//options.ExcludedHosts.Add("example.com");
//options.ExcludedHosts.Add("www.example.com");
});
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 5001;
});
}
return services;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityProvider.API.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace IdentityProvider.API
{
public class Startup
{
public static readonly ILoggerFactory MyLoggerFactory
= LoggerFactory.Create(builder => { builder.AddConsole(); });
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationCorsService();
services.AddApplicationSSlEnforce(false);
services.AddApplicationIdentityService(Configuration.GetConnectionString("IdentityDbContext"));
services.AddControllersWithViews();
services.AddHostedService<IdentitySeedWorker>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseApplicationSSlEnforce(env, false);
app.UseHttpsRedirection();
app.UseRouting();
app.UseApplicationCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapDefaultControllerRoute();
});
app.UseWelcomePage();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment