canot call userinfo due to invalid scope error - asp.net

I am setting up identity server3 with Microsoft identity stored in ef 6
I can "login" at the /token end point but when I try to access the /userinfo I get a scope error.
when I try to add scopes to my /token login they do not work.
tried to edit the client to add the scopes and still stuck.
the client is the resource owner flow.
just need to get userinfo so I can get the name and the roles for the user.
1) what scope do I need to access the user info end point ? I get insufficient scope on all my attempts.
2) I have editied the sql database and the code to allow my client to have more scopes but it does not seem to work. how to debug that ?
also I am using asp.net identity stored in sql and the id server ef to store tokens, clients, scopes and secrets, well I am trying to but I am not sure it's right. the tables were created but I do not see any rows in the tokens table event though I was issued a token. I have two databases right now: one with the token/client/scope stuff and the other with aspnet users and roles.
do I need to make this one database ?
it looks like part of my problem is with the identity server sample for using entity framework to store the clients, scopes and related data.
it looks like some items are missing in the lists of scopes and or scope claims and or clients, so when I try to login with a scope parameter I get rejected when it can not find the row in the scopes table.
working on how to fix this and I hope get it working....
does a scope need scope claims ?? need to see if I can find info on that.

its 'openid' scope as docs say. https://identityserver.github.io/Documentation/docsv2/endpoints/userinfo.html

When in doubt I just download the current source code from Github and apply breakpoints, rather than using the Nuget package.
Just going from memory (So this may not be completely accurate).
I believe the UserInfoEndpoint makes a call to UserService.GetProfileDataAsync. The UserInfoEndpoint is accepting scopes but the GetProfileDataAsync only accepts claims as "RequestedClaimTypes". So somewhere in between it will be taking the scopes sent to endpoint and getting a list of all claim types that fall within the scopes.
The most important thing to keep in mind here is that the scopes you pass into the UserInfoEndpoint must be Identity scopes. The endpoint will not return claims belonging to resource scopes.
So just a quick rundown...
Server receives scopes sent to UserInfoEndpoint
Of the scopes received, it only looks at Identity Scopes
Find claim types that are assigned to the identity scopes
Passes down the list of claim types to GetProfileDataAsync as "context.RequestedClaimTypes".
At this point your custom logic determines how the RequestedClaimTypes translate into IssuedClaims.
My guess is that you are passing in resource scopes to the UserInfoEndpoint.

what finally got my problem fixed:
I needed more scopes in my sql database , the id server sample for v3 using entity framework did not have some of the same scope items that the identity server sample expects , this was making a login token call fail with invalid scope.
I edited the c# code for the scopes and clients to get what I needed and dropped and re-created the sql tables and then it started working.
I also added a new scope and scope claims to add in non standard claims that our app needs.
I did attach the source to let me debug that really helped as I could follow the logic and see where it did not work. that was a huge help.
I will see later if I can post to the source what the sample was missing that was the real problem.
it might also be good if we had some kind of guide on how to get the standard userinfo / profile claims to work. I got it but that also was a bit of source debugging to see how the id server calls to the stores to get the info so that I could understand how to tap in and give it the data to pass back to the caller.
bottom line is that the samples have different sets of scopes and claims in at least one place and that was the key problem.
the rest is learning how to use the scopes and scope claims to add to the user info endpoint for the applications needs.

Related

Understanding of OData services

This is a question to improve my understanding about OData and the process of OData services. I'm not sure about the process when an OData request is sent to the server from my Fiori app. The app is added to our Fiori Launchpad. When the user wants to create a new target group in the UI, a create request is sent. What happens then in detail? What I thought so far:
OData service checks the data
If the data is valid, a new entry in the database is created (HTTP POST)
If the data is not valid, the OData service sends an error
I'm not sure about what information is delivered by the OData service and what information is delivered directly from the database? Does the OData service work like a adjustor which transfers the messages sent from the database to the application?
I hope you can understand what I'm trying to figure out. Thank you for your time.
it depends how your backend-methods are implemented. Every Entityset usually has one of these Methods:
Get Entity
Get EntitySet
Create
Update
Delete
There are some more I guess, but these are mostly used by developers. You can redefine every single method and implement your own Business Logic in there.
So, let's assume you want to send data from the Frontend to your service and insert the data into a table inside your database. You have to redefine the create method of your entity and implement own logic. This could contain an insert into a database-table. You have to consider, that your oData Service will throw an Error if the types which are sent from the frontend do not match the Entity-Types (i.e. a String into an edm.Time type).
Here you can find all EDM.Types oData could consume and the correct mapping of the types:
https://help.sap.com/saphelp_gateway20sp12/helpdata/en/76/4a837928fa4751ab6e0a50a2a4a56b/frameset.htm
Hope this helps :)

Symfony2 invalid form still saves entity on flush

I currently have a form and on save I always make an API call to validate the form information against an external source (eg: is the company a VAT paying company etc.). I also want to store in the database the response I get from the external API, for which I have a post submit subscriber on the form.
In the subscriber, I call the API and set errors on the form where values do not match. That is where I call a service to handle all the business logic and somewhere in there I have
$em->persist($apiResponse);
$em->flush();
to hold onto the API response.
This ends up saving the entity values attached to the form (company) in the database even though these values are actually invalid and the user is returned to the form page saying that.
Please note this happens on edit, and I understand why it happens, because the entity is managed by Doctrine.
I also tried flushing only the entity I am interested in:
$em->persist($apiResponse);
$em->flush($apiResponse);
and this seems to work, but I read this can have an unexpected behavior.
Hence, my question is: what are the solutions for this ?
Thank you, and sorry for the lack of code samples!

Limiting data modification by User ASP.NET MVC4

I'm building an application in ASP.NET MVC4 as a learning exercise. I'm trying to understand
authentication and authorization. That seems fine, role based authorization seems fine for restricting certain controllers/actions to users who are part of a given role.
What I'm struggling with is how I can apply this to data which belongs to an individual user. Using a forum as a simple example how could the functionality be achieved whereby a user can only edit or remove posts that they have created but can view/add comments to posts of other users. Would this have to be done in code by checking the user associated with the post to be updated against the current user before allowing the update to take place, returning unauthorized if they don't match.
Is there a more elegant solution that can be applied rather than applying this kind of logic to multiple controllers/actions?
There's a wealth of information out there I'm just trying to narrow the search. Can anyone suggest a good tutorial/article on this. I've been looking at Forms authentication and Membership but I'd be interested in something using Identity too. I'm also using Entity Framework.
Thanks
Would this have to be done in code by checking the user associated with the post to be updated against the current user before allowing the update to take place, returning unauthorized if they don't match.
Yes, that's exactly what you do. While role-based authorization is a matter of a simple relation between users and roles, data-access level authorization is usually complex and involve custom business rules.
Of course, it could help a lot to create a thin layer of managers that will be commonly used as guards so that you keep all the code close together:
[HttpPost]
public ActionResult PostFoo( FooModel model )
{
// keep the access manager separate from the
// domain layer. operate on IDs.
if ( new UserAccessManager( this.User ).
CanOperateOnFoo( model.IdSomething, model.IdWhateverElse ) )
{
}
else
// return 403 or a meaningful message
}
or
[HttpPost]
public ActionResult PostFoo( FooModel model )
{
// switch to the domain layer
Foo foo = Mapper.Map( model );
// make the access manager part of the domain layer
if ( foo.CanBeOperatedBy( this.User ) )
{
}
else
// return 403 or a meaningful message
}
Would this have to be done in code by checking the user associated with the post to be updated against the current user before allowing the update to take place, returning unauthorized if they don't match.
No, you want to avoid hard-coding authorization logic into your code. Doing so leads to:
authorization silos
poor visibility
a chance there might be errors in the authorization logic
hard-to-maintain logic
Is there a more elegant solution that can be applied rather than applying this kind of logic to multiple controllers/actions?
Yes, there is. Much like you wouldn't hard-code authentication or logging into your app, you want to externalize authorization. This is called Externalized Authorization Management (EAM). There are several frameworks that help you do that from Spring Security in Java to Claims-based authorization in .NET to XACML-based solutions.
There are 2 fundamental authorization models you want to consider:
role-based access control (RBAC)
attribute-based access control (ABAC)
You can read about both on NIST's website (RBAC | ABAC).
Given the sample rule you gave:
A user can only edit or remove posts that they have created but can view/add comments to posts of other users.
RBAC will not be enough. You will need to use ABAC (and XACML) to be able to implement the relationship between the user and the data requested. XACML, the eXtensible Access Control Markup Language is a standard that provides you with:
a standard architecture.
a request/response scheme, and
a policy language.
With the XACML policy language, you can rewrite your example as:
A user can do the action==edit or the action==remove if and only if the post.owner==user.id
A user can do the action==view on any post
A user can do the action==comment on any post
Then, from your code, all you have to do is send an authorization request: Can Alice view post #123?. The authorization engine (also called policy decision point or PDP) will determine who owns the post and will reach a decision, either of a Deny or a Permit.
A key benefit to using externalized authorization and XACML is that you can apply the same consistent authorization to any layer (presentation tier, business tier, ESB, APIs, databases...) and any technology (Java, .NET, Python...).
Other benefits include:
modular architecture
configuration-driven authorization that is easy to grow as requirements change
easy-to-audit authorization
centrally-managed authorization
cheaper to develop and onboard new applications than writing code over and over again
standards-based.
There are several open-source and vendor solutions out there that address this market. Have a look at Axiomatics (disclaimer: I work for Axiomatics) or SunXACML (open source).
HTH,
David.

Why aren't authentication and login functions part of the same class in Firebase?

In Firebase, authentication happens on a new Firebase reference. But logging in happens on a new FirebaseAuthClient reference.
Authenticating a user:
var dataRef = new Firebase('some_firebase_url');
dataRef.auth(auth_token, callback_function);
Signing a user in:
var authClient = new FirebaseAuthClient(dataRef, callback_function);
authClient.login('password', some_email, some_password, function(error, token, user) {...});
Why is this? Wouldn't it make more sense to have all authentication/login/signup functions be part of the same class? Especially since the class called FirebaseAuthClient (notice the Auth right there in the middle) doesn't even actually have the authentication method assigned to it?
This is a little confusing to me and I'm hoping some insight can help me understand better.
Here's the difference between the two and why they exist on separate classes:
Firebase.auth() is the "low-level" API that must be called in order to authenticate a Firebase client with the Firebase servers. You provide it with a valid authentication token, which could come from a variety of sources (you might generate it from your backend server code, you might get it from a 3rd-party auth provider like Singly, etc.).
FirebaseAuthClient is the API for Firebase Simple Login, which is a simple authentication service that comes bundled with Firebase. It's by far the easiest way to get basic authentication working (using Facebook, Twitter, email/password, etc.). It's been optimized to integrate seamlessly with the Firebase client and, as such, it hides the details of getting an authentication token and calling Firebase.auth(). But that's what it does under the covers. You could think of it as a wrapper around Firebase.auth().
So if you're using Simple Login, you only need to use FirebaseAuthClient and can ignore Firebase.auth(). But for people generating their own tokens (e.g. so they can integrate with their existing user database), they'll deal directly with Firebase.auth() instead.
After further reading and thinking, I have realized that although it's still in the documentation, dataRef.auth is no longer necessary. Creating a new FirebaseAuthClient essentially replaces it.
Before recent changes, new FirebaseAuthClient did not take a callback function. To authenticate, you had to call dataRef.auth.
Now, when you instantiate a new FirebaseAuthClient, the attempt to authenticate happens at that moment. The information that was previously available to the dataRef.auth callback is now available to the new callback that you provide to new FirebaseAuthClient.
It is slightly different however. The dataRef.auth version was like this:
dataRef.auth(authtoken, function(success) { ... });
The FirebaseAuthClient version is like this:
var authClient = new FirebaseAuthClient(dataRef, function(error, user) { ... });
So in the new method of doing things, you don't just get a success boolean (which is replaced instead by an error object), you also get back a user object if the authentication was successful.
Before this change, if a user had authenticated successfully and you wanted to get their information, you would have had to pull it out of localStorage or something. Now it's just provided for you in the callback, which is a good change.
In addition, the token parameter that used to be passed to the authClient.login function is now a part of the user data, as user.firebaseAuthToken.
Hand-in-hand with this update is the change to how authClient.login works. It no longer takes a callback, and instead fires the callback that was passed to new FirebaseAuthClient.
Indeed, that callback seems to be the only callback that you will ever need to set for any FirebaseAuthClient function that changes authentication state. Specific FirebaseAuthClient functions like login and logout will just change the authentication state, and will rely on that original callback.
Additionally, it seems that you no longer have to keep track of a user's authToken to authenticate them. It used to be the case that authClient.login would call its callback with a token param, and then you'd store that token, and use it for dataRef.auth(token, some_callback), but that's no longer necessary, since dataRef.auth itself is no longer necessary.
So in summary, to answer the original question, all authentication methods now actually are part of the same class - FirebaseAuthClient. dataRef.auth is no longer necessary, though it's still in the documentation, which is confusing.
Replace dataRef.auth with new FirebaseAuthClient, and replace dataRef.auth with authClient.logout and you should be set.
Any feedback from Firebase staff on the validity of these claims would be much appreciated.

Enterprise Library Policy Injection Logging Managed Security Context Information in ASP.NET

I am using The Policy Injection Application Block to log methods that are called in my ASP.NET application. I would like these log entries to include information like the current user identity, whether the user is authenticated and so forth. All of this information is provided by the ManagedSecurityContextInformationProvider, but I can't figure out how to get the PIAB to use that provider and how to get that information into my log file.
I may be missing something obvious, but I can't quite figure out what it is.
Sorry to say, it looks like there is no way to get the ManagedSecurityContextInformationProvider information into method call logs. That information is usually logged in extended properties but the LogCallHandler.GetLogEntry method dumps out all of the method parameters and assigns them to the TraceLogEntry ExtendedProperties.
It seems to me that you could either modify the block to add that information or (even better) create your own Custom Call Handler based on LogCallHandler that adds the information that you require. Either option is not that much work.

Resources