Spring-Security-OAuth2 - how to add fields to access token request? - spring-security-oauth2

I have a Spring Boot application, that is using Spring Security with OAuth 2.0. Currently, it is operating against an Authentication Server based on Spring Example code. However, running our own Auth Server has always been a short-term target to facilitate development, not a long-term goal. We have been using the authorization_code grant type and would like to continue using that, irrespective of the Auth Server implementation.
I am attempting to make changes to use OAuth 2.0 Endpoints in Azure Active Directory, to behave as our Authentication Server. So far, I have a successful call to the /authorize endpoint. But the call to get the /token fails with an invalid request error. I can see the requests going out.
It appears that parameters that Azure states as mandatory are not being populated in the POST request. Looking at the Azure doco, it expects the client_id to be defined in the body of the message posted to the endpoint, and that is not added, by default, by Spring.
Can anyone point me in the right direction for how I can add fields to the Form Map that is used when constructing the Access Token request? I can see where the AccessTokenRequest object is being setup in OAuth2ClientConfiguration....
#Bean
#Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
protected AccessTokenRequest accessTokenRequest(#Value("#{request.parameterMap}")
Map<String, String[]> parameters, #Value("#{request.getAttribute('currentUri')}")
String currentUri) {
DefaultAccessTokenRequest request = new DefaultAccessTokenRequest(parameters);
request.setCurrentUri(currentUri);
return request;
}
Should I be trying to define the map in a request.parameterMap spring property? If so, I'm not too sure how that works.
Or should I be using one of the interfaces defined in the AuthorizationServerConfigurerAdapter class?
I have the information to include when sending the AccessTokenRequest, I just don't know the best way to configure Spring to include it? Thanks for any help.

Actually, I found this out. I needed to change the client authentication scheme. Simply adding the following to my application properties added the client_id to the form....
security.oauth2.client.clientAuthenticationScheme=form
If you're using yaml, then yaml-ize it. Thank you Spring!

Related

Endpoint authorization for service to service call

I have a .net core API with multiple endpoint. I am using Identity Server 4 for authentication. Token will be generated based on correct user name and password.
In the Same API, I want to add another endpoint which should only be accessed by API call only and normal user should not be able to access the end point.
I am thinking of Policy based authorization for the endpoint.
Is it a correct approach?
There's a couple things you could do.
As you mention you can use authorization policies. If you're using OAuth; your source API can use client credential grant type to obtain a M2M token (a.k.a. machine-to-machine token). In the target service can do a check the gty claim is equal to client_credentials, and if not; return HTTP 403 response.
Use the API gateway and only expose public APIs/operations on internal services - don't expose public routes for APIs/operations that should be restricted to service-to-service calls.
Do both #1 and #2.
Yes, you need to configure your policies. For that you need to understand the difference between authentication and authorization, and setup them both. For example in our project we use several different authentication sources, and then map them to authorization policies
services.AddAuthentication()
.AddScheme<...>("scheme1", ...)
.AddScheme<...>("scheme2", ...)
...;
services.AddAuthorization(opts =>
{
opts.AddPolicy("policy1", policy => policy.AddAuthenticationSchemes("scheme1")
.<some other requirements specific to this policy>
.RequireAuthenticatedUser());
opts.AddPolicy("policy2", policy => policy.AddAuthenticationSchemes("scheme2")
.<some other requirements specific to this policy>
.RequireAuthenticatedUser());
}
After which you could just use [Authorize("policy1")] and [Authorize("policy2")]. Or you could make one policy the default by adding
opts.DefaultPolicy = new Microsoft.AspNetCore.Authorization
.AuthorizationPolicyBuilder()
.<requirements go here>
and then use [Authorize] to use the default policy, and [Authorize("policy1")] for special cases.

Implementing a SAML assertion flow with Spring Oauth2

I need to implement a SAML assertion flow using Spring OAuth2 Authorization Server. I'm struggling with how to tie these two projects up.
I've tried importing the SAML securityContext into my OAuth project as well, however it seems that the SAML flow will always take precedence. Is there a way to do this where it would look at the grant_type to determine if it should use the saml flow.
Also, when it does process the saml assertion, would that tie into the ResourceOwnerPasswordTokenGranter, or would I have to register a custom token granter with something like this?
With OAuth2, we have a way of registering different TokenGranters through something like this:
List<TokenGranter> tokenGranters = new ArrayList<TokenGranter>();
tokenGranters.add( endpoints.getTokenGranter());
tokenGranters.add(new SamlTokenGranter(authenticationManager,tks,cds,endpoints.getOAuth2RequestFactory()));
CompositeTokenGranter ctg = new CompositeTokenGranter(tokenGranters);
endpoints.tokenGranter(ctg);
thanks ahead of time for any help you can provide
You might need to register a custom TokenGranter. The CompositeTokenGranter (the default) can handle multiple grant types by doing what you suggest (comparing the incoming requested grant_type to the one supported by each granter). If you are using Spring SAML as a service provider to check the assertion, then I guess you also need to set that up as a separate security filter on the /token endpoint (with a very specific request matcher so it only intercepts SAML grants).

Implementing Authorization in a Self Hosted SignalR Server accessed from Web

I'm looking for some guidance on how to implement authorization security for SignalR on a back end service running in a self-hosted (non-IIS) environment, that is called from a Web application. The backend app is basically a monitor that fires SignalR events back to the HTML based client. This all works fine (amazingly well actually).
However, we need to restrict access to the server for authenticated users from the Web site. So basically if a user is authenticated on the Web site, we need to somehow pick up the crendentials (user name is enough) and validation state in the backend app to decide whether to allow the connection as to avoid unauthorized access.
Can anybody point at some strategies or patterns on how to accomplish this sort of auth forwarding?
I am having similar issues here, as in my web app I use a simple cookie authentication system which uses an AoP style approach to check for any controllers with an attribute, then will get the current context (be it from the static HttpContext.Current or from the target invocation object depending on the type of interceptor) and then verify the cookie exists, it contains right data, then finally verify the token with the db or cache etc.
Anyway this approach can also be used for Signalr, although its a bit more long winded and you are using dependency injection. You would basically wrap the hub calls with the desired attribute, then set up your DI/IoC configuration to intercept these calls, then either get the hub instance within your interceptor and get the cookie (or your custom authentication mechanism) from the request, verify it is all valid or not, and if not then throw a new HttpException("403", "Not authenticated"); which should kick the user out and return back before it even hits your hub method, this way you can put the logic in one place (your interceptor, or a class the interceptor consumes) then just wrap any method that needs to use this authentication using your attribute.
I use Ninject and the interception extension, but most major DI frameworks these days have some form of IoC plugin/extensions, such as Autofac, Windsor, Spring etc.
If you were not happy going down the route of introducing DI and/or AOP to your current project, then maybe you could just create a custom hub instance which contains your authentication logic and then just use that in your hubs, so ok you will still be manually calling some authentication logic from within each hub method you want to protect, but its less code, so something like:
public class AuthorisableHub : Hub
{
private ISomeAuthenticationToken GetSomeAuthenticationTokenFromRequest(Request request) // probably a SignalR specific request object
{
// Get your token from the querystring or cookie etc
}
private bool IsAuthenticationTokenValid(ISomeAuthenticationToken token)
{
// Perform some validation, be it simple or db based and return result
}
protected void PerformUserAuthentication()
{
var token = GetSomeAuthenticationTokenFromRequest(Context.Request);
var isRequestValid = IsAuthenticationTokenValid(token);
if(!isRequestValid)
{ throw new HttpException(403, "<Some forbidden message here>"); }
}
}
public class MyFancyPantsHub : AuthorisableHub
{
public void TellAllClientsSomethingSecret(ISecret secret)
{
PerformUserAuthentication();
// Do stuff with the secret as it should have bombed the user out
// before it reaches here if working correctly
}
}
It is not perfect but would work (I think), also I am sure I once read somewhere that Hubs are newly instantiated for each request, and if this is indeed true, you could possibly just put this logic in your constructor if you want to apply the authentication to every action within the hub.
Hope that helps, or gives you ideas... would be interested in knowing how you did solve it in the end.
SignalR does not provide any additional features for authentication. Instead, it is designed to work with the authentication mechanism of your application.
Hubs
You should do authentication as you normally would and then use the Authorize attribute provided by SignalR to enforce the results of the authentication on the Hubs.
The Authorize attribute can be applied to an entire Hub or particular methods in the Hub. Some examples:
[Authorize] – only authenticated users
[Authorize(Roles = "Admin,Manager")] – only authenticated users in the specified .NET roles
[Authorize(Users = "user1,user2")] – only authenticated users with the specified user names
You can also require all Hubs to require authentication by adding the following method in the Application_Start method:
GlobalHost.HubPipeline.RequireAuthentication();
Persistent Connections
You can use the user object in the request to see if the user is authenticated:
request.User.IsAuthenticated

Passing Auth to API calls with Web Service References

I am new to web services. The last time I dealt with SOAP was when I created a bunch of wrapper classes that sent requests and received responses back per some response objects/classes I had created. So I had an object to send certain API requests and likewise a set of objects to hold the response back as an object so I could utilize that 3rd party API.
Then someone came to me and said why not just use the wsdl and a web service. Ok, so today I went and created a "Service Reference". I see that this is what's called a "Proxy Class". You just instantiate an instance of this and then walla you have access to all the methods from the wsdl.
But this leaves me with auth questions. Back when I created my own classes manually, I had a class which exposed properties that I would set then access for things like signature, username, password that got sent along with the Http request that were required by whatever 3rd party API I was using to make API calls.
But then with using a Service Reference, how then would I pass this information just like I had done in my custom classes? For instance I'm going to be working with the PayPal API. It requires you to send a signature and a few other pieces of information like username and password.
// Determins if API call needs to use a session based URI
string requestURI = UseAuthURI == true ? _requestURIAuthBased + aSessionID : _requestURI;
byte[] data = XmlUtil.DocumentToBytes(doc);
// Create the atual Request instance
HttpWebRequest request = CreateWebRequest(requestURI, data.Length);
So how do I pass username, password, signature, etc. when using web service references for each method call? Is it as simple as specifying it as a param to the method or do you use the .Credentials and .URL methods of your proxy class object? It seems to me Credentials means windows credentials but I could be wrong. Is it limited to that or can you use that to specify those required header values that PayPal expects with each method call/API request?
Using Web Service or Web Service Reference

Custom HTTP Basic Authentication for ASP.NET Web Services on .NET 3.5/VS 2008

I am refactoring a working ASP.NET Web Application to expose Web Services interface using ASP.NET Web Service. According to Web Services authentication - best practices, Basic Auth over https is the way to go. Let's assume it is, as opposed to doing WS-Security, X509, etc..
On .NET 3.5/VS 2008, what's the simplest way of implementing custom http Basic Authentication (non-Windows account), for example, accepting only if user name is "foo" and password is "bar". Ultimately, I'd like Thread.CurrentPrincipal set.
Do I write my own HttpModule or can this be done simpler?
Likely using Custom Basic Authentication for IIS, written by Dominick Baier is the way to go. As he points out WCF 3.5's usernames over transport security cannot be used on IIS-hosted service, although my question was regarding ASP.NET Web Services not WCF.
There's another implementation of HTTP Module called Basic authentication in ASP.NET against custom datasource by Santosh Sahoo.
Although it's not what I wanted, I found QuickStart Tutorial's SOAP Headers sample to be informative workaround. Sending password in plain text over http is clearly insecure, but this example could be extended to add more security, for instance running on https or sending hash of "password + one-time GUID + timestamp".
Grab the value of the Authorization header, parse it and validate the username/password.
The value is username:password, encoded as a Base64 string.
See http://en.wikipedia.org/wiki/Basic_access_authentication for details.
Edit: if you want this done for every request, using the custom auth scheme, then it would be easier to write an HttpModule to handle parsing the header and setting the thread's principal.
If you are considering WCF, you can use usernameOverTransport security for basicHttpBinding. i.e. username and passowrd reside in the SOAP header of the request and all the traffic are protected by SSL encryption over the wire.
A custom UserNamePasswordValidator validator can be used to authenticate the incoming credentials against e.g. database.
You can set the thread principal within a custom IAuthorizationPolicy in the service behavior.
e.g. Evaluate method implementation for IAuthorizationPolicy for setting current principal
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
Object obj;
if( evaluationContext.Properties.TryGetValue( "Identities", out obj ))
{
// get the authenticated identity
IIdentity client = (obj as IList<IIdentity>)[0];
evaluationContext.Properties["Principal"] = ... // create principal obj here for the identity
// this will set thread's current principal
}
return true;
}

Resources