Error: Scope IdentityServerApi not found in store - .net-core

While trying to add routing to additional endpoints within my project built with IdentityServer4, I ran into the following issue:
Error: Scope IdentityServerApi not found in store.
I followed IdentityServer4's documentation for adding more API Endpoints exactly, so I wasn't sure why I was getting this error.

It turns out that in v4 IdentityServer is moving away from ApiResources and toward ApiScopes. For anyone just learning about IdentityServer4, it can be a little confusing navigating all of these changes, so hopefully this clarification will be helpful to someone else as well.
Solution: as opposed to what it says in the documentation included in my question, register your "LocalApi" as an ApiScope not an ApiResource. Following in an example of my setup for a local API:
Your config file:
// Add to your ApiScopes (not ApiResources)
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope(IdentityServerConstants.LocalApi.ScopeName)
};
// Then add to your client's allowed scopes:
// ... extraneous code omitted ...
AllowedScopes = new string[]
{
IdentityServerConstants.LocalApi.ScopeName
}
Your startup/program.cs:
// Register IdentityServer, then:
builder.Services.AddLocalApiAuthentication();
Your "LocalApi" controller class:
[ApiController]
[Authorize(LocalApi.PolicyName)]
[Route("api/[controller]/[action]")]
public class YourController : ControllerBase
{
// ...
}

Related

Shopware 6 backend controller path

In Shopware 6, I want to call a backend (/admin) API controller from a backend / admin page using JavaScript. What is the correct way to use a relative path, probably with a built-in getter function?
Fetching /api/v1 only works if the shop is on /, but not when it is in a sub-folder.
fetch('/api/v1/my-plugin/my-custom-action', ...)
The best practice would be to write your own JS service that handles communication with your api endpoint.
We have an abstract ApiService class, you can inherit from. You can take a look at the CalculatePriceApiService for an example in the platform.
For you an implementation might look like this:
class MyPluginApiService extends ApiService {
constructor(httpClient, loginService, apiEndpoint = 'my-plugin') {
super(httpClient, loginService, apiEndpoint);
this.name = 'myPluginService';
}
myCustomAction() {
return this.httpClient
.get('my-custom-action', {
headers: this.getBasicHeaders()
})
.then((response) => {
return ApiService.handleResponse(response);
});
}
}
Notice that your api service is preconfigured to talk to your my-plugin endpoint, in the first line of the constructor, which means in all the following request you make you can use the relative route path.
Keep also in mind that the abstract ApiService will take care of resolving the configuratuion used for the Requests. Especially this means the ApiService will use the right BaseDomain including subfolders and it will automatically use an apiVersion that is supported by your shopware version. This means the apiVersion the ApiService uses in the route will increase every time a new api version is available, that means you need to work with wildcards in your backend route annotations for the api version.
Lastly keep in mind you need to register that service. That is documented here.
For you this might look like this:
Shopware.Application.addServiceProvider('myPluginService', container => {
const initContainer = Shopware.Application.getContainer('init');
return new MyPluginApiService(initContainer.httpClient, Shopware.Service('loginService'));
});
If you are talking about custom action that you implemented, you need to define route (use annotation) and register controller in routes.xml in your Resources\config\routes.xml.
Please follow that documentation
https://docs.shopware.com/en/shopware-platform-dev-en/how-to/api-controller

JpaSagaStore in conjunction with Jackson unable to properly store state

In a SpringBoot application, I have the following configuration:
axon:
axonserver:
servers: "${AXON_SERVER:localhost}"
serializer:
general: jackson
messages: jackson
events: jackson
logging.level:
org.axonframework.modelling.saga: debug
Downsizing the scenario to bare minimum, the relevant portion of Saga class:
#Slf4j
#Saga
#ProcessingGroup("AuctionEventManager")
public class AuctionEventManagerSaga {
#Autowired
private transient EventScheduler eventScheduler;
private ScheduleToken scheduleToken;
private Instant auctionTimerStart;
#StartSaga
#SagaEventHandler(associationProperty = "auctionEventId")
protected void on(final AuctionEventScheduled event) {
this.auctionTimerStart = event.getTimerStart();
// Cancel any pre-existing previous job, since the scheduling thread might be lost upon a crash/restart of JVM.
if (this.scheduleToken != null) {
this.eventScheduler.cancelSchedule(this.scheduleToken);
}
this.scheduleToken = this.eventScheduler.schedule(
this.auctionTimerStart,
AuctionEventStarted.builder()
.auctionEventId(event.getAuctionEventId())
.build()
);
}
#EndSaga
#SagaEventHandler(associationProperty = "auctionEventId")
protected void on(final AuctionEventStarted event) {
log.info(
"[AuctionEventManagerSaga] Current state: {scheduleToken={}, auctionTimerStart={}}",
this.scheduleToken,
this.auctionTimerStart
);
}
}
In the final compiled class, we will end up having 4 properties: log (from #Slf4j), eventScheduler (transient, #Autowired), scheduleToken and auctionTimerStart.
For reference information, here is a sample of the general approach I've been using for both Command and Event classes:
#Value
#Builder
#JsonDeserialize(builder = AuctionEventStarted.AuctionEventStartedBuilder.class)
public class AuctionEventStarted {
AuctionEventId auctionEventId;
#JsonPOJOBuilder(withPrefix = "")
public static final class AuctionEventStartedBuilder {}
}
When executing the code, you get the following output:
2020-05-12 15:40:01.180 DEBUG 1 --- [mandProcessor-4] o.a.m.saga.repository.jpa.JpaSagaStore : Updating saga id c8aff7f7-d47f-4616-8a96-a40044cb7e3b as {}
As soon as the general serializer is changed to xstream, the content is serialized properly, but I face another issue during deserialization, since I have private static final class Builder classes using Lombok.
So is there a way for Axon to handle these scenarios:
1- Axon to safely manage Jackson to ignore #Autowired, transient and static properties from #Saga classes? I've attempted to manually define #JsonIgnore at non-state properties and it still didn't work.
2- Axon to safely configure XStream to ignore inner classes (mostly Builder classes implemented as private static final)?
Thanks in advance,
EDIT: I'm pursuing a resolution using my preferred serializer: JSON. I attempted to modify the saga class and extend JsonSerializer<AuctionEventManagerSaga>. For that I implemented the methods:
#Override
public Class<AuctionEventManagerSaga> handledType() {
return AuctionEventManagerSaga.class;
}
#Override
public void serialize(
final AuctionEventManagerSaga value,
final JsonGenerator gen,
final SerializerProvider serializers
) throws IOException {
gen.writeStartObject();
gen.writeObjectField("scheduleToken", value.eventScheduler);
gen.writeObjectField("auctionTimerStart", value.auctionTimerStart);
gen.writeEndObject();
}
Right now, I have something being serialized, but it has nothing to do with the properties I've defined:
2020-05-12 16:20:01.322 DEBUG 1 --- [mandProcessor-0] o.a.m.saga.repository.jpa.JpaSagaStore : Storing saga id c4b5d94c-7251-40a5-accf-332768b1cacd as {"delegatee":null,"unwrappingSerializer":false}
EDIT 2 Decided to add more insight into the issue I experience when I switch general to use XStream (even though it's somewhat unrelated to the main issue described in the title).
Here is the issue it complains to me:
2020-05-12 17:08:06.495 DEBUG 1 --- [ault-executor-0] o.a.a.c.command.AxonServerCommandBus : Received command response [message_identifier: "79631ffb-9a87-4224-bed3-a957730dced7"
error_code: "AXONIQ-4002"
error_message {
message: "No converter available\n---- Debugging information ----\nmessage : No converter available\ntype : jdk.internal.misc.InnocuousThread\nconverter : com.thoughtworks.xstream.converters.reflection.ReflectionConverter\nmessage[1] : Unable to make field private static final jdk.internal.misc.Unsafe jdk.internal.misc.InnocuousThread.UNSAFE accessible: module java.base does not \"opens jdk.internal.misc\" to unnamed module #7728643a\n-------------------------------"
location: "1#600b5b87a922"
details: "No converter available\n---- Debugging information ----\nmessage : No converter available\ntype : jdk.internal.misc.InnocuousThread\nconverter : com.thoughtworks.xstream.converters.reflection.ReflectionConverter\nmessage[1] : Unable to make field private static final jdk.internal.misc.Unsafe jdk.internal.misc.InnocuousThread.UNSAFE accessible: module java.base does not \"opens jdk.internal.misc\" to unnamed module #7728643a\n-------------------------------"
}
request_identifier: "2f7020b1-f655-4649-bbe0-d6f458b3c2f3"
]
2020-05-12 17:08:06.505 WARN 1 --- [ault-executor-0] o.a.c.gateway.DefaultCommandGateway : Command 'ACommandClassDispatchedFromSaga' resulted in org.axonframework.commandhandling.CommandExecutionException(No converter available
---- Debugging information ----
message : No converter available
type : jdk.internal.misc.InnocuousThread
converter : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
message[1] : Unable to make field private static final jdk.internal.misc.Unsafe jdk.internal.misc.InnocuousThread.UNSAFE accessible: module java.base does not "opens jdk.internal.misc" to unnamed module #7728643a
-------------------------------)
Still no luck on resolving this...
I've worked on Axon systems where the only used Serializer implementation was the JacksonSerializer too. Mind you though, this is not what the Axon team recommends. For messages (i.e. commands, events and queries) it makes perfect sense to use JSON as the serialized format. But switching the general Serializer to jackson means you have to litter your domain logic (e.g. your Saga) with Jackson specifics "to make it work".
Regardless, backtracking to my successful use case of jackson-serialized-sagas. In this case we used the correct match of JSON annotations on the fields we desired to take into account (the actual state) and to ignore the one's we didn't want deserialized (with either transient or #JsonIgnore). Why both do not seem to work in your scenario is not entirely clear at this stage.
What I do recall is that the referenced project's team very clearly decided against Lombok due to "overall weirdnes" when it comes to de-/serialization. As a trial it thus might be worth to not use any Lombok annotations/logic in the Saga class and see if you can de-/serialize it correctly in such a state.
If it does work at that moment, I think you have found your culprit for diving in further search.
I know this isn't an exact answer, but I hope it helps you regardless!
Might be worthwhile to share the repository where this problems occurs in; might make the problem clearer for others too.
I was able to resolve the issue #2 when using XStream as general serializer.
One of the Sagas had an #Autowired dependency property that was not transient.
XStream was throwing some cryptic message, but we managed to track the problem and address it.
As for JSON support, we had no luck. We ended up switched everything to XStream for now, as the company only uses Java and it would be ok to decode the events using XStream.
Not the greatest solution, as we really wanted (and hoped) JSON would be supported properly out of the box. Mind you, this is in conjunction with using Lombok which caused for the nuisance in this case.

Asp.net .core web api versioning does not work for Url path segment

I searched for my problem beforehand in various sources but the answers did not provide me with a solution.
I implemetend Url based web api versioning in a .net core 2.2 project with the way presented here. The version that I used for versioning is the latest Microsoft.AspNetCore.Mvc.Versioning 3.1.2.
I also tried to understand how it works from the following sources: source1, source2, source3, source4.
I am having a ValueController with a GET method in a folder called Initial and a Value2Controller in a folder called New. Both folders are subfolders of the 'Controllers' folder.
The structure is as follows:
The routing in ValueController is
[Route("api/v{version:apiVersion}/[controller]")]
and in Value2Controller is:
[Route("api/v{version:apiVersion}/value")]
I have also set options.EnableEndpointRouting = false; in the Startup.cs and I tried calling api/v1/value or api/v2/value. Both times I get the error: Multiple actions matched. It cannot differentiate between the two controllers actions.
I tried using services.AddApiVersioning(); with no options at all and remove AddVersionedApiExplorer. It does not work. The only thing that works is
putting
[Route("api/v{version:apiVersion}/[controller]")]
in both controllers and make the following api calls:
api/v1/value and api/v2/value2.
The configuration in my startup.cs is as follows:
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ApiVersionReader = new UrlSegmentApiVersionReader();
options.UseApiBehavior = true;
});
services.AddVersionedApiExplorer(
options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
});
What am I missing to call either api/v1/value or api/v2/value and go to the correct request?
After some more debugging, I finally figured out why it wasn't working, so I am posting the solution to anyone who will face a similar problem. The problem was within the Controller Inheritance.
I had created a CustomBaseController (which I had completely disregarded as problematic for some reason) with some methods for global exception handling, the inheritance goes as follows:
[ApiVersionNeutral]
[Route("api/[controller]")]
[ApiController]
CustomBaseController : Controller
and
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
ValuesController : CustomBaseController { // http method implementations}
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/values")]
[ApiController]
ValuesController : CustomBaseController { // updated http method implementations}
The versioning mechanism did not agree with [ApiVersionNeutral] attribute even though it made sense to me that the the base controller would not need to change at all. Moreover I only had the basic routing in the base controller.
Thus I got the error with "Multiple actions matched".
I also found out that the version 1 controller, can inherit the routing from the base controller and had no reason to have a routing there. For all subsequent controllers, the routing must be:
[Route("api/v{version:apiVersion}/values")].
The working solution along with the initial configuration posted above, is the following:
[Route("api/v{version:ApiVersion}/[controller]")]
[ApiController]
CustomBaseController: Controller {}
[ApiVersion("1.0")]
[ApiController]
ValuesController: CustomBaseController { //code }
[ApiVersion("2.0")]
[ApiController]
[Route("api/v{version:ApiVersion}/values")]
Values2Controller: CustomBaseController { //code }
[ApiVersion("3.0")]
[ApiController]
[Route("api/v{version:ApiVersion}/values")]
Values3Controller: CustomBaseController { //code }
Getting values from the following urls:
api/v1/values
api/v2/values
api/v3/values
Even though my issue was resolved, I still don't understand why [ApiVersionNeutral] would cause the routing to not be able to detect the versions of the other controllers correctly. Any explanation would be highly appreciated.
Thank you #Matt Stannett for your comments, they led me to the right direction.

aspnet-api-versioning - backward compatibility

I need to сlarify.
I have .net mvc app and I use Microsoft/aspnet-api-versioning (for ASP.NET Core).
And I have 2 controllers:
[ApiVersion("1.0")]
[Route("[controller]")]
public class OneController : Controller
{
[HttpGet]
public string Get()
{
return "Hello. I'm OneController";
}
}
and
[ApiVersion("1.1")]
[Route("[controller]")]
public class TwoController : Controller
{
[HttpGet]
public string Get()
{
return "Hello. I'm TwoController";
}
}
TwoController I added after release API with OneController.
And now if I try to use "http://localhost:59719/One?api-version=1.1" i see error:
The HTTP resource that matches the request URI 'http://localhost:59719/test?api-version=1.1' does not support the API version '1.1'.
Should I use different versions for different controllers or there is way to use one (latest) version for any request?
I understand I can add [ApiVersion("1.1")] to ALL controllers, but if I have 20 controllers...
Thanks for help.
You can define a default api version using the ApiVersioningOptions class and use this default version if none is specified:
`services.AddApiVersioning(o =>
{
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(1 , 0);
});`
Besides, you should take a look at this excellent post on API versioning in ASP.NET from Scott Hanselman:
https://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx
In your example above, you have two different controllers with two different API versions. There is no direct relationship between these two. If you're trying to apply API versions in a centralized manner, you can achieve this using the Conventions API. You can even author and apply your own conventions via the IControllerConvention interface.
// same result as the attributes above
options.Conventions.Controller<OneController>().HasVersion(1,0);
options.Conventions.Controller<TwoController>().HasVersion(1,1);
// can also be achieved using only controller types
options.Conventions.Controller(typeof(OneController)).HasVersion(1,0);
options.Conventions.Controller(typeof(TwoController)).HasVersion(1,1);
// register your own convention that applies API versions to all controllers
options.Conventions.Add(new MyCustomApiVersionConvention());
You can also use an approach similar to what #arnaudauroux suggested, which would be:
services.AddApiVersioning(options =>
{
options.AssumeDefaultVersionWhenUnspecified = true;
options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
});
Now any request without an API version will select the current (or highest) API version available. Beware that this could break clients.

Structure Map violates the constraint of type parameter 'CONCRETETYPE'

I have a web application developed in ASP.NET 2010. I have used the Dependency Injection with StructureMap in ASP.NET MVC. I'm trying to get started with Structure Map. I'm using
I've built a simple boot strapper, but when I run the website I get the following error:
StructureMap.Configuration.DSL.Expressions.CreatePluginFamilyExpression`1[System.Web.Mvc.IActionInvoker].Use:
type argument
'TestWebsite.Web.Controllers.Factories.InjectingActionInvoker'
violates the constraint of type parameter 'CONCRETETYPE'.
Code Block:
public static void ConfigureStructureMap()
{
ObjectFactory.Initialize(x =>
{
//registry per assembly recommended
x.AddRegistry<WebRegistry>();
x.AddRegistry<ServiceRegistry>();
x.AddRegistry<SHARE.Data.DataRegistry>();
});
//if a class needs configuring on load then this is done here. Inherit from IStartUpTask
ObjectFactory.GetAllInstances<IStartUpTask>()
.Where(x => x.IsEnabled).ToList()
.ForEach(t => t.Configure());
//This checks all is well. Not ideal to do in application_start though cause of calls to request object....
//ObjectFactory.AssertConfigurationIsValid();
}
public class WebRegistry : Registry
{
public WebRegistry()
{
For<IFormsAuthentication> ().Use<FormsAuthenticationService>();
For<IAuthentication>().Use<BasicMembership>();
Scan(x =>
{
x.AssemblyContainingType<IStartUpTask>();
x.AddAllTypesOf<IStartUpTask>();
x.WithDefaultConventions();
});
For<IActionInvoker>().Use<InjectingActionInvoker>();
SetAllProperties(c =>
{
c.OfType<IActionInvoker>();
c.WithAnyTypeFromNamespaceContainingType<UserService>(); //our services
c.WithAnyTypeFromNamespaceContainingType<AdminCookies>(); //cookie services
});
}
Could anyone please suggest on this issue. how it could be resolved? I am really getting troubled with it and need to resolve it asap. Any help would be greatly appreciated.
Thanks
Deepak
I do the following changes to run:
Remove the reference of MVC 3.0 DLL from website
Add the reference of MVC 2.0 DLL in website
Run the project and its working fine

Resources