How to use AuthenticationSchemeOptions.Events or AuthenticationSchemeOptionsEventsType? - asp.net-core

Ok, so as per usual, MSDN is now an automatically generated blob of useless documents, so maybe the developers lurk around here and can explain this to me.
I created a custom Authentication scheme based off of the AuthenticationHandler<TOptions> base class. I have two questions regarding this:
How do I define the type to use in AuthenticationSchemeOptions.EventsType in order to consume authentication-related events?
If the loggerFactory object a required object? Can't I just pass null to it? I want to control my output. I guess I could test this one myself. If you want to answer, go ahead, otherwise I'll test it at some point.
But what I have no clue whatsoever is for question 1. I see the class JwtBearerEvents as a sample, but I have no idea if I should be creating one exactly like that, or in general, how does this event system works at all???? I am utterly confused.
Thank you.
P. S.: I don't think it is important, but just so you know, the custom authentication handler basically validates a JWT created by a federated API server whose signing keys can be queried to verify signature. So basically it is a handler that makes a web request (then caches the keys) and uses those keys to validate the token and extract the claim data of interest, finally creating a ClaimsPrincipal user out of said claims.

Related

How to improve back-end urI security?

I'm using web api for my application on ASP.NET CORE
If someone see application soruce code, there is a backend url, isn't it?
Then, that guy can use my api if he succeed my application decompile
How protect that situation
I'm just stutdent, so... Just my curiosity
Authenticate your API
If you plan on having a private API (not open to everyone), then you should force users to authenticate themselves by using an API access token. Each token should be specific to a particular user, and there should be consequences for distributing a private key (such as revoking it and blocking the person associated with it) or else people will just share them without care. This will allow users to communicate with your server and run commands or queries as they please. Assuming you have written these functions correctly, they shouldn't allow an attacker to access much beyond his given scope of given API functions (which should be queries at most).
Document, document, document!
You shouldn't allow users access to your source code for this. You should document your API thoroughly regarding details which methods the user can use, what sort of data it expects to receive, and what sort of data you will get back from it (including all errors, possible problems with the users request, and how to fix their requests). Make sure you heavily test these too, and make sure that you can't perform any sort of malicious actions with your API. It's also a good idea to give your documentation to another person and ask them to read it. If you've missed something important, you will know afterwards because there will be a clear gap in their knowledge of the API.
What, not how
Users should know what a function should do, but not how it does it. For example, I could use /api/GetUserById. I should know that I can get a user - I shouldn't know how it gets the user. The only thing I need to know is that I perform this call and I get back a json object with details about the user. That is it.
As with any of my posts, if there's something I've missed or something you need further clarification on, please let me know in the comments and I'd be happy to explain further. I hope this helps

How to access the SignalR Hub arguments from [Authorize()]?

I'm making a signalr hub for a chat app (it's not really, but lets pretend it is).
I have my authorization set up so that user can be invited to a room by the creator of the room. So there's a table that stores who owns what, and who has been granted access.
This is good. Next steps were to add claims so that I didn't have to check who had access to what on every request. I check once when a user tries to join the chat room, add their claims, and send them to the page that starts the signalr connection.
Now I want to use the [authorize] decorator on my hubs, instead of throwing boilerplate
user.Claims.Any(x=> x.ClaimType == $"CanJoinRoom_{RoomId}");
everywhere.
I've read up on how to make custom policy based authorization here:
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies#security-authorization-policies-based
I have every piece I need except one: the actual arguments that specifies the room id. I have been able to hack something from
[MyCustomAuthorizeMethod(this.Context.Request.Form["data"])]
but this seems a bit ugly, and to make it work I have to serialize this json
{"H":"myhubname","M":"Initialize","A":[39],"I":0}
Which seems really hacky. I'd much prefer to pass the RoomId as a parameter.
It is just one line down but seems a world away. Is there an elegant way to do this?
If you want to authorize invoking a given method you can put the AuthorizeAttribute on the hub method. You may also find this post on hub authorization and authentication helpful.
This is impossible because attributes are computed at compile time and therefore cannot have variables. Thanks to Pawel for pointing that out.
https://stackoverflow.com/users/1168070/pawel

Spring secutiry custom authentication manager vs custom provider vs custom UserDetailsService

I've been knocking my head up against this problem for a few days now and after seeing dozens of examples all over the web I'm no closer to a solution.
I need to to various types of login, eventually. For right now I'd settle for one. I would like to login using fields other than username and password. Let's say I want to use name, last name and birthdate.
I thought the easiest way to go was to just implement my own UserDetailsService and plug it into my provider. But UserDetailsService only has one method, loadByUsername, which doesn't seem to be the most intuitive way to load my user.
So then I thought it would be better to implement my own AuthenticationProvider ... or simply extend DaoAuthenticationProvider, and override the authenticate() method. But that method takes an Authentication as a parameter ... can I used a POJO, with only name, last name and birthdate fields, as an Authentication object?
Ditto for Authentication Manager. In fact, in the api for AbstractUserDetailsAuthenticationProvider (where the authenticate() method lives) it says that it "Performs authentication with the same contract as AuthenticationManager.authenticate(Authentication)"
But people seem to implement Providers more than Managers. oddly enough, most examples of "custom" Providers and UserDetailsServices ... all implement authentication with username and password, which is was Spring Security does by default anyway!
Can anyone shed some light on this subject? As I said, there are tons of examples but they are all very similar and none that I can find use an Authentication Object that isn't username/password.
Bonus points if someone could also tell me the best way to go about having more than one Provider/Manager -- for example, one like the one described above, and another that authenticates using name and social security number, for example -- and to use one or the other (not both, and not the second one if the first one fails!) depending on a parameter pass from the url, for example.
I'm not sure if you had already solved this challenge. But, it seems that I have a similar case with you. My login page requires additional field 'organisation' aside from 'username' and 'password'. Here is what I did:
I've used custom AuthenticationManager and custom UsernameAndPasswordAuthenticationFilter.
The custom filter is for retrieving the additional field from HttpServletRequest. I added the field to the session and retrieved it inside custom AuthenticationManager.
Performed authentication with the three fields using another bean/service.

How To Disable Per Request (URL Based) Claims Authorization in WCF?

I have a WCF service which uses claims based authorization.
What I want to do is to attribute an operation with a ClaimsPrincipalPermissionAttribute and only have the authorization check trigger once in my custom ClaimsAuthorizationManager. However I am finding that this authorization check is being triggered twice; once for the URL and then a second time on the operation itself.
I can't find much information on this subject, but what I have found indicates that this is by design. Is it possible for me to overwrite this behavior and not perform any authorization on the URL, and only authorization based on the operation?
I have no interest in authorizing based on URLs, and would really rather avoid adding claims for each and every URL as I am likely to have a lot of them and they may change in future.
I have read several articles, and seen videos from Dominick Baier on this subject, and while I have learnt a lot from these I still can't find an answer to this. Is this simply not possible and I just have to deal with having to authorize based on the URL as well?
You can't change this behavior - what I did is to write a custom claims permission attribute that does emit different claim types. This way I could distinguish between the per-request invocation and the explicit attribute.
https://github.com/thinktecture/Thinktecture.IdentityModel.45/tree/master/IdentityModel/Thinktecture.IdentityModel/Authorization
or the Thinktecture.IdentityModel nuget package.

OOP Design: Where should reusable validation be?

I've got a wizard which needs to validate if a user is logged in and then at the end validate that all the details they have entered are correct.
The issue is I'm not sure where to put the validation logic.
At the moment I have a BuyMembership class which has validation on the Buy() method.
However this won't be called at the beginning of the wizard where I need to validate whether the user is unique and is eligible for buying a membership.
For this validation I've created a BuyMembershipValidation class which validates if the user is eligible.
The issue now is that I have to pass a different parameter object to the BuyMembershipValidation and the BuyMembership classes. This means the data is split.
Is there a better way of doing it. Should I only load part of the information into the BuyMembership class for the initial validation and then load the rest after?
Update:
I need to validate when they enter the wizard (check if they are logged in already) and if they aren't then they will register as a new user otherwise I have to check if they have the right settings to buy membership as all users can't buy a membership. That's why I need two sets of validation. One for whether they're eligible and another for the actual data they enter to register. However I would like to recheck that they are eligible when they make the final transaction just in case they somehow made it past the first wizard step or if the web service (where I'm doing the logic) is called from somewhere else at a later point.
Another Update:
I've added an answer with my decision.
TIA,
Jonathan.
You're actually talking about three very different things here, and like Allain said, you need to think along the lines of single-responsibility to do this right, OOP-like.
Authentication: making sure a user is known
Authorization: making sure a user can access certain logic in your application
Validation: making sure the data a user inputs is valid/safe/what's expected or needed
A validator is typically tasked with validating user supplied information, not authorization. The single responsibility principle dictates that in your case they should definitely be handed by two objects.
Passing different parameter objects is fine, but but I think the authorization one shouldn't really be passed in to the BuyMembership object, it sounds like something that should be handled externally to it.
My 2 cents.
User authentication is a broad topic. It really depends on what type of application you are building. If it is a web application, I would recommend using one of the standard methods for authentication: NTLM / kerberos
As to when to validate, I don't see any problem with holding off on the validation until the actual Buy method is called. As long as during the steps in the wizard, you are not releasing any information to them and are only collecting data from a form. The main time when you need to be concerned about authentication is when you are actually placing an order or releasing information to the user that should be locked away in a database somewhere.
If you provide more details to what you are trying to do, I will refine my answer to help you a bit more. It's a rather broad question though, so this is the best I can come up with for now.
I've decided to go with just the one class. The reason is that there is common logic / behaviour in the IsEligible and Buy methods. One determines if the inputs meet the eligibility requirements and the other validates that all the details needed to buy the membership are valid. I don't really see this as authentication related. The authentication is done in a separate web control and I just check the Identity.IsAuthenticated and Username to see if they are logged in. I then check their username and if they are eligible to buy then I let them continue, otherwise show an error message. In terms of input validation I already have validation controls on my webpage but the validation I'm concerned with here is server side business logic validation. For that reason I think it should be in the business logic class. Not some validation class separate from the logic that performs the payment. This may just be my way of looking at it but I think this fits well with the BDD ideas of keeping validation inside the entity that holds the data.