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

VCST-1415: Platform as authorization server #2809

Open
wants to merge 23 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Routing;

namespace VirtoCommerce.Platform.Web.ActionConstraints;

public sealed class FormValueRequiredAttribute : ActionMethodSelectorAttribute
{
private readonly string _name;
private readonly string[] _forbiddenMethods = ["GET", "HEAD", "DELETE", "TRACE"];

public FormValueRequiredAttribute(string name)
{
_name = name;
}

public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
var request = routeContext.HttpContext.Request;

if (_forbiddenMethods.Contains(request.Method, StringComparer.OrdinalIgnoreCase))
{
return false;
}

if (string.IsNullOrEmpty(request.ContentType))
{
return false;
}

if (!request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
return false;
}

return !string.IsNullOrEmpty(request.Form[_name]);
}
}

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions src/VirtoCommerce.Platform.Web/Model/AuthorizeViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;

namespace VirtoCommerce.Platform.Web.Model;

public class AuthorizeViewModel
{
[Display(Name = "Application")]
public string ApplicationName { get; set; }

[Display(Name = "Scope")]
public string Scope { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using OpenIddict.Validation.AspNetCore;
using VirtoCommerce.Platform.Core.Caching;
using VirtoCommerce.Platform.Core.Security;
using VirtoCommerce.Platform.Security.Authorization;
Expand Down Expand Up @@ -49,7 +50,7 @@ private Dictionary<string, AuthorizationPolicy> GetDynamicAuthorizationPoliciesF
{
resultLookup[permission.Name] = new AuthorizationPolicyBuilder().AddRequirements(new PermissionAuthorizationRequirement(permission.Name))
//Use the three schemas (JwtBearer, ApiKey and Basic) authentication for permission authorization policies.
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme, BasicAuthenticationOptions.DefaultScheme)
.AddAuthenticationSchemes(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme, BasicAuthenticationOptions.DefaultScheme)
.Build();
}
return resultLookup;
Expand Down
125 changes: 70 additions & 55 deletions src/VirtoCommerce.Platform.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
Expand All @@ -33,7 +30,7 @@
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OpenIddict.Abstractions;
using OpenIddict.Validation.AspNetCore;
using VirtoCommerce.Platform.Core;
using VirtoCommerce.Platform.Core.Common;
using VirtoCommerce.Platform.Core.DynamicProperties;
Expand Down Expand Up @@ -73,8 +70,8 @@
using VirtoCommerce.Platform.Web.Security.Authentication;
using VirtoCommerce.Platform.Web.Security.Authorization;
using VirtoCommerce.Platform.Web.Swagger;
using static OpenIddict.Abstractions.OpenIddictConstants;
using JsonSerializer = Newtonsoft.Json.JsonSerializer;
using MsTokens = Microsoft.IdentityModel.Tokens;


namespace VirtoCommerce.Platform.Web
Expand Down Expand Up @@ -248,7 +245,7 @@ public void ConfigureServices(IServiceCollection services)
options.MinimumSameSitePolicy = SameSiteMode.None;
});

var authBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
var authBuilder = services.AddAuthentication(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)
//Add the second ApiKey auth schema to handle api_key in query string
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationOptions.DefaultScheme, options => { })
//Add the third BasicAuth auth schema
Expand All @@ -269,9 +266,10 @@ public void ConfigureServices(IServiceCollection services)
// which saves you from doing the mapping in your authorization controller.
services.Configure<IdentityOptions>(options =>
{
options.ClaimsIdentity.UserNameClaimType = OpenIddictConstants.Claims.Subject;
options.ClaimsIdentity.UserIdClaimType = OpenIddictConstants.Claims.Name;
options.ClaimsIdentity.RoleClaimType = OpenIddictConstants.Claims.Role;
options.ClaimsIdentity.UserNameClaimType = Claims.Name;
options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
options.ClaimsIdentity.RoleClaimType = Claims.Role;
options.ClaimsIdentity.EmailClaimType = Claims.Email;
});

services.ConfigureOptions<ConfigureSecurityStampValidatorOptions>();
Expand Down Expand Up @@ -308,31 +306,31 @@ public void ConfigureServices(IServiceCollection services)
// register it as a singleton to use in external login providers
services.AddSingleton(defaultTokenHandler);

authBuilder.AddJwtBearer(options =>
{
options.Authority = Configuration["Auth:Authority"];
options.Audience = Configuration["Auth:Audience"];

if (WebHostEnvironment.IsDevelopment())
{
options.RequireHttpsMetadata = false;
options.IncludeErrorDetails = true;
}

MsTokens.X509SecurityKey publicKey = null;

var publicCert = ServerCertificate.X509Certificate;
publicKey = new MsTokens.X509SecurityKey(publicCert);
options.MapInboundClaims = false;
options.TokenValidationParameters = new MsTokens.TokenValidationParameters
{
NameClaimType = OpenIddictConstants.Claims.Subject,
RoleClaimType = OpenIddictConstants.Claims.Role,
ValidateIssuer = !string.IsNullOrEmpty(options.Authority),
ValidateIssuerSigningKey = true,
IssuerSigningKey = publicKey
};
});
//authBuilder.AddJwtBearer(options =>
//{
// options.Authority = Configuration["Auth:Authority"];
// options.Audience = Configuration["Auth:Audience"];

// if (WebHostEnvironment.IsDevelopment())
// {
// options.RequireHttpsMetadata = false;
// options.IncludeErrorDetails = true;
// }

// MsTokens.X509SecurityKey publicKey = null;

// var publicCert = ServerCertificate.X509Certificate;
// publicKey = new MsTokens.X509SecurityKey(publicCert);
// options.MapInboundClaims = false;
// options.TokenValidationParameters = new MsTokens.TokenValidationParameters
// {
// NameClaimType = OpenIddictConstants.Claims.Subject,
// RoleClaimType = OpenIddictConstants.Claims.Role,
// ValidateIssuer = !string.IsNullOrEmpty(options.Authority),
// ValidateIssuerSigningKey = true,
// IssuerSigningKey = publicKey
// };
//});

services.AddOptions<Core.Security.AuthorizationOptions>().Bind(Configuration.GetSection("Authorization")).ValidateDataAnnotations();
var authorizationOptions = Configuration.GetSection("Authorization").Get<Core.Security.AuthorizationOptions>();
Expand All @@ -350,19 +348,25 @@ public void ConfigureServices(IServiceCollection services)
// Register the ASP.NET Core MVC binder used by OpenIddict.
// Note: if you don't call this method, you won't be able to
// bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
var builder = options.UseAspNetCore().
EnableTokenEndpointPassthrough().
EnableAuthorizationEndpointPassthrough();

var builder = options.UseAspNetCore()
.EnableAuthorizationEndpointPassthrough()
.EnableLogoutEndpointPassthrough()
.EnableTokenEndpointPassthrough()
.EnableUserinfoEndpointPassthrough()
.EnableStatusCodePagesIntegration();
// Enable the authorization, logout, token and userinfo endpoints.
options.SetTokenEndpointUris("connect/token");
options.SetUserinfoEndpointUris("api/security/userinfo");
options.SetTokenEndpointUris("/connect/token")
.SetUserinfoEndpointUris("/connect/userinfo")
.SetAuthorizationEndpointUris("/connect/authorize")
.SetLogoutEndpointUris("/connect/logout");

// Note: the Mvc.Client sample only uses the code flow and the password flow, but you
// can enable the other flows if you need to support implicit or client credentials.
options.AllowPasswordFlow()
options
.AllowPasswordFlow()
.AllowRefreshTokenFlow()
.AllowClientCredentialsFlow()
.AllowAuthorizationCodeFlow()
.AllowCustomFlow(PlatformConstants.Security.GrantTypes.Impersonate)
.AllowCustomFlow(PlatformConstants.Security.GrantTypes.ExternalSignIn);

Expand Down Expand Up @@ -410,8 +414,16 @@ public void ConfigureServices(IServiceCollection services)
{
privateKey = new X509Certificate2(ServerCertificate.PrivateKeyCertBytes, ServerCertificate.PrivateKeyCertPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.EphemeralKeySet);
}

options.AddSigningCertificate(privateKey);
options.AddEncryptionCertificate(privateKey);
})
.AddValidation(options =>
{
// Import the configuration from the local OpenIddict server instance.
options.UseLocalServer();
// Register the ASP.NET Core host.
options.UseAspNetCore();
});

services.Configure<IdentityOptions>(Configuration.GetSection("IdentityOptions"));
Expand All @@ -425,30 +437,33 @@ public void ConfigureServices(IServiceCollection services)
//always return 401 instead of 302 for unauthorized requests
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = ".VirtoCommerce.Identity.Application";

options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.CompletedTask;
};
options.Events.OnRedirectToAccessDenied = context =>
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return Task.CompletedTask;
};
options.LoginPath = "/";
//TODO: Temporary comment return status codes instead of redirection. It is required for
//normal authorization code flow. We should implement login form as server side view.
//This logic is used to handle 401 errors when token is expired to force redirect to angular login form
//in case we have server side login form, this logic is no longer needed and can be removed.
//options.Events.OnRedirectToLogin = context =>
//{
// context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
// return Task.CompletedTask;
//};
//options.Events.OnRedirectToAccessDenied = context =>
//{
// context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
// return Task.CompletedTask;
//};
});

services.AddAuthorization(options =>
{
//We need this policy because it is a single way to implicitly use the three schemas (JwtBearer, ApiKey and Basic) authentication for resource based authorization.
var multipleSchemaAuthPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme, BasicAuthenticationOptions.DefaultScheme)
.AddAuthenticationSchemes(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme, BasicAuthenticationOptions.DefaultScheme)
.RequireAuthenticatedUser()
// Customer user can get token, but can't use any API where auth is needed
.RequireAssertion(context =>
authorizationOptions.AllowApiAccessForCustomers ||
!context.User.HasClaim(OpenIddictConstants.Claims.Role, PlatformConstants.Security.SystemRoles.Customer))
!context.User.HasClaim(Claims.Role, PlatformConstants.Security.SystemRoles.Customer))
.Build();
//The good article is described the meaning DefaultPolicy and FallbackPolicy
//https://scottsauber.com/2020/01/20/globally-require-authenticated-users-by-default-using-fallback-policies-in-asp-net-core/
Expand Down
22 changes: 22 additions & 0 deletions src/VirtoCommerce.Platform.Web/Views/Shared/Authorize.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
@using Microsoft.Extensions.Primitives
@model VirtoCommerce.Platform.Web.Model.AuthorizeViewModel
@{
Layout = null;
}
<div class="jumbotron">
<h1>Authorization</h1>

<p class="lead text-left">Do you want to grant <strong>@Model.ApplicationName</strong> access to your data? (scopes requested: @Model.Scope)</p>

<form asp-controller="Authorization" asp-action="Authorize" method="post">
@* Flow the request parameters so they can be received by the Accept/Reject actions: *@
@foreach (var parameter in Context.Request.HasFormContentType ?
(IEnumerable<KeyValuePair<string, StringValues>>) Context.Request.Form : Context.Request.Query)
{
<input type="hidden" name="@parameter.Key" value="@parameter.Value" />
}

<input class="btn btn-lg btn-success" name="submit.Accept" type="submit" value="Yes" />
<input class="btn btn-lg btn-danger" name="submit.Deny" type="submit" value="No" />
</form>
</div>
20 changes: 17 additions & 3 deletions src/VirtoCommerce.Platform.Web/wwwroot/js/app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
modules.query().$promise.then(function (results) {
moduleHelper.modules = results;
moduleHelper.onLoaded();

var modulesWithErrors = _.filter(results, function (x) { return _.any(x.validationErrors) && x.isInstalled; });
if (_.any(modulesWithErrors)) {
$scope.platformError = {
Expand All @@ -61,7 +61,14 @@
var moduleErrors = "<br/><br/><b>" + x.id + "</b> " + x.version + "<br/>" + x.validationErrors.join("<br/>");
$scope.platformError.detail += moduleErrors;
});
$state.go('workspace.modularity');
var query = new URLSearchParams(window.location.search);
var returnUrl = query.get('ReturnUrl');
if (returnUrl) {
window.location.href = returnUrl;
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed
}
else {
$state.go('workspace.modularity');
}
}
});

Expand Down Expand Up @@ -438,7 +445,14 @@
}
});
} else if (!currentState.name || currentState.name === 'loginDialog') {
$state.go('workspace');
var query = new URLSearchParams(window.location.search);
var returnUrl = query.get('ReturnUrl');
if (returnUrl) {
window.location.href = returnUrl;
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed
}
else {
$state.go('workspace');
}
}
}, 500);
});
Expand Down
Loading