Are login/register commands or queries in CQRS - authentication

So for the login, since it doesn't really make anything new in the database but rather just returns if we've logged in, and possibly some user data, should it be a command or query?
And as for the register, since it creates a new user, should it be a command then? What if i want to return the users data or a jwt?
Should i run my commands and once the client receives a response run a query right after them?

As with most design related questions, I’d answer this one with ‘it depends’. I have seen both solutions implemented in different situations.
The main question you’d need to ask is whether you consider a user logging in as a state change of the system or not. Note that whether it changes state in de database isn’t relevant. The system is more than the database.
Log in as a command
For some systems, it’s important to know which users had been logged in and when, from where, etc. One example I had seen was a medical system that needed to record which doctor logged in when and where, and which medical records had been accessed. Also, logging in on one machine would stop tbe session on another. A reliable trace of these actions was essential to the application. As such, log in was implemented as a command which generated events that were stored in the Event Store. Projections kept the current logged in state for each user.
Log in as a query
Most systems I have seen, however, simple beed to know whether any given credentials can ve mapped to a user account. If that is the case, a token is generated containing the ‘proof’ of authentication. The system itself doesn’t really care who is logged in. It’s just that each request needs to be validated by checking the ‘proof’. In this case, logging in is a query.

Related

Restrict access of a connected app (Salesforce)

What is the best way to restrict the scope of a connected app to a set of objects? My current solution is to use the Manage user data via APIs scope but that still grants more access than required.
A solution I see frequently is to create a user with a restricted profile and connect with that user but then you lose context of actions made by users in the connected app so this solution doesn't work
Tricky, you typically don't. (consider posting on https://salesforce.stackexchange.com/, there might be a clever way I didn't think of).
You can flip the connected app from "all users can self authorise" to "admin-approved users are preauthorised" and then allow only certain profiles / permission sets to use the app. But the bulk of it is "just" enabling the connection via API and cutting it to say Chatter only or OpenId identifiers. And that's already an improvement compared to SOAP APIs where you don't have scopes and the app can completely impersonate the user, do everything they can do in UI.
Profiles/permission sets/sharing rules are "the" way even in not immediately obvious situations like Lighting Connect Salesforce to Salesforce or Named Credentials access to another org.
If you can't restrict the visibility with profiles and access to all tables user can see is not acceptable...
you could create series of Apex classes exposing certain queries, updates etc and grant profile access to these classes - but without full api access? You could even let them pass any SOQL (evil) but use with sharing, WITH SECURITY_ENFORCED, stripInaccessible + custom restriction on tables before returning results
you could look into https://developer.salesforce.com/docs/atlas.en-us.238.0.apexref.meta/apexref/apex_class_Auth_ConnectedAppPlugin.htm although I suspect it's run only on connect, not on every request. So at best you could deny access if user has right to see some sensitive data, not great
if there are few objects you need to block updates if done via app - Quiddity might be the way to go. Throw error in a trigger if action started from REST context?
give the Transaction Security trailhead a go. If it looks promising (there's way to check "application" and "queried entities" according to this) - might be a solution. You'll likely have to cough up $ though, last time I checked the cool bits of event monitoring & transaction security were hidden behind an extra paid addon (standalone or bundled with platform encryption and Field Audit Track into Salesforce Shield solution)
2 logins? dedicated user for querying stuff but inserts/updates running as your end user?

Testing Best Practices possibly with regard to Gherkin but probably not

A coworker and I are having an argument about the proper way to test. I'll lay them out as neutrally as I can, and won't give my opinion in this post.
This is written in gherkin. Substitute whatever pseudocode you want to.
Given I am a registered user
When I submit my credentials
Then I can login
Case one:
Given I am a registered user
(instantiates the user,
stores the user to scenario-global memory,
adds the user to the db with an API endpoint
stores the API endpoint result to scenario-global memory [200, "Success message"])
When I submit my credentials
(test the result of the previous step [200],
fills the credential field(s),
clicks submit, stores the result to scenario-global memory [200, "Success message"])
Then I can login
(tests the results of the previous step)
Case two:
Given I am a registered user
(instantiates the user,
stores the user in scenario-global memory,
adds the user to the db, tests the result of the db command)
When I submit my credentials
(fills the UI credential field(s),
clicks submit)
Then I can login
(perform some operation that only a logged-in user could do [see the my profile button/call some api endpoint])
​
The contention is whether or not the Then step can rely on the result from a previous operation.
It depends. First of all, as a tester, i would never directly write something to DB, instead i register the user in UI for UI testing or call endpoints to cover API testing scenarios.
Also, IMO, not every step is responsible for testing its own step, otherwise there is no need for 'Then' Gherkin syntax. This way of writing user stories makes it more understandable to non-technical but business people very clearly about the scenario under test.
For both cases above, i vote for case one and your co-worker's suggestion.
Overall, one should aim for declarative BDD scenarios, when trying to cover the features from end-user perspective. Pushing your how down is vital part of it. Employing Back door manipulation is great, but ask youself this - does your end user (or stakeholder) really care about technicalities?
adds the user to the db with an API endpoint
is something that is best used, when the register user flow is covered at least once through the UI. Mixing APIs and UI in the scenarios, can lead to a mess and maintenance issues. A proper DSL should handle that for you.
As to
each step is responsible for testing its own results. It is not responsible for what happened in the past or what is about to happen in the future
Cucumber-ish frameworks do use DI of context/state, exactly for this - share steps execution run in the current World instance.

User Auth in EventSourcing applications

I'm looking into crafting an app with DDD+CQRS+EventSourcing, and I have some trouble figuring out how to do user auth.
Users are intrinsically part of my domain, as they are responsible for clients. I'm using ASP.NET MVC 4, and I was looking to just use the SimpleMembership. Since logging in and authorising users is a synchronous operation, how is this tackled in an eventually consistent architecture?
Will I have to roll my own auth system where I keep denormalized auth tables on the read side? How to handle the security of this? Will I end up storing password hashes in both my event store and my view tables?
So many questions, if anyone can shed some light, I would be very thankful :)
tldr; How do you do User Auth in EventSource-applications?
Not every "Domain" or business component has to use DDD or CQRS. In most cases, user information is really cruddy, so you can usually not use DDD for that. Other domains don't really depend on the actual user. There's usually a correlation id (UserId) that gets shared by the various domains.
If using messaging in your system, one option is to register and manage users without CQRS, then send a command (RegisterUser { UserId } ). This would publish an event User Registered. Other domains can listen to this event to kick-off any workflows or ARs that are needed.
For our MVC CQRS app, we originally started off keeping all the user related information in the domain, and, like somebody mentioned, there was a RegisterUserCommand and a UserRegisteredEvent. After storing the user information in the domain, that event got published and picked up on the read side, which also created a user and generated all the password hashes, etc. We then done the authentication on the read side: the controller would make a call out to a 'read model authentication service' to authenticate against.
Later on down the road, we ended up completely refactoring this. It turned out that we needed access to the user related information to build in security for authorising our commands, which we done on the command processing side (our app is a distributed app that sends 'fire and forget' asynchronous commands to a queue, with an autonomous listener on the other side). The security component then needed a reference to our domain to go and get the user profile, which led to cumbersome referencing issues.
We decided to put the user security stuff into a separate database that we considered to be more of a central component, rather than belonging to the domain or read model. We still maintain user profile related information in the domain and read models (e.g. job title, twitter account URL etc.), but all the security related stuff, like password hashes, are stored in this central database. That's then accessible with a service, that's available to both MVC and the command authoriser.
We didn't actually have to change anything in the UI for this refactor, as we just called the service to register the users from the register user command handler. If you're going to do it that way, you need to be careful here to make your user service related operations idempotent. This is so that you can give your commands the opportunity to be retried without side effects, because you're updating 2 sources of information (the ES and the user database).
Finally, you could of course use the membership providers for this central component, but there can be pitfalls with that. We ended up just writing our own - it's pretty simple to do. That article links to this, which provides a good example of how to implement it.
You should consider creating separate entities like: visitor (just visited your site), user (registered), customer (bought something), etc. Try to split your system in this way, even if it causes a little bit of data redundancy. Disk space is not an issue but ability to modify different components of the system independently is usually very critical.
People create denormalized auth tables only for the purpose of scaling and only if your auth read side is a performance bottleneck. If not - usual 3rd normal form is a way to go.
In SimpleMembership scenario all tables created by SimpleMembership can be viewed as snapshot of "user" aggregate. And yes, they will duplicate some data in your event store.
You may have events like: UserCreated, UserUpdated, UserAssignedToRole, etc.
And don't be tricked by the name of that membership provider. It's not so simple and usually has lots of things that you can easily live without (depends on your domain). So, maybe you can use something like this: https://gist.github.com/Kayli/fe73769f19fdff40c3a7

Implementing anonymous authentication and double voting prevention

I am thinking for ways to implement a mechanism which enables a user to vote,without logging any of his details. Each user has a set of attributes that enable him to vote. For eg. Id,name,email-id.
Using these attributes we must guarantee that the user can vote for the first time. During this time,complete anonymity is guaranteed.
But if the user comes for a second time to vote,he should not be allowed to vote. Is this remotely possible?We are not storing any of the information related to the user.No ip adddress,email-id or student id. They are just used as a means of authentication.
I read many research papers for this but not able to find anything specific.
a mechanism which enables a user to vote,without logging any of his
details
Sure you can. Just don't log anything. But you do need to store information about which user has voted. You actually need info of the user not even the machine the user used as the user could vote from another machine.

Website Permissions: Changing a user's rights while they're logged in

I could be wrong about this, but it is my understanding that it is a very common practice to handle permissions like so:
The user goes to the login page and provides a username and password.
The username and password are verified. If valid, the user's information (including permissions) is set to a session variable.
As the logged in user navigates the site, certain features are available to the user based on their permissions, which are referenced in the session.
This makes sense since it would be impractical to frequently query the database for the user's permissions. However, from a security standpoint, I'm not sure what the best approach is. A simple example would be if you were to remove a certain permission from a user while they're logged in. An extreme example would be if you were to mark a user account as inactive while they're logged in. I don't know how you could get that user's web browser to know about the change other than to code database permission checks (as opposed to session permission checks) into every part of the website. Again, that seems like overkill, but is that really the only way if you want a secure website?
Thanks!
I believe you've got it stated correctly:
I don't know how you could get that user's web browser to know about the change other than to code database permission checks (as opposed to session permission checks) into every part of the website.
Depending upon how your site is designed, it might make sense to invalidate the user's session when you perform drastic enough modifications to the user's privileges. Deleting sessions mean the user will be faced with a new request to log in, but if you've just disabled their account or severely downgraded their privileges, that might be acceptable.
But you wouldn't want to invalidate the session for every little thing and certainly not for almost any permission enhancement operations.
If you expire all sessions N seconds after the last authentication you can place an upper limit on the amount of time that your application code would grant permissions that have actually been revoked. This might be suitable when the stakes are not very high anyway.