I am trying to call an api that uses Oauth 1a using OAuthRestTemplate from spring-security-oauth.
I saw that most of the examples set the consumer key and secret and then let the library get the access tokens.
I have the token and the token secret (which do not expire) and I want to set them on the OAuthRestTemplate and make calls, without going through the authentication flow.
Is that possible? if so, how?
AFAIK that's not possible (it is on the OAuth2 side but OAuth1 never got as much love). Contributions gratefully accepted.
This is possible, though a bit hacky. Example code below:
// Assume you have a preconfigured RestTemplate
OAuthRestTemplate template = new OAuthRestTemplate(resource);
OAuthConsumerToken accessToken = new OAuthConsumerToken();
accessToken.setAccessToken(true);
accessToken.setResourceId(template.getResource().getId());
accessToken.setValue(ACCESS_TOKEN);
OAuthSecurityContextImpl securityContext = new OAuthSecurityContextImpl();
securityContext.setAccessTokens(new HashMap<>());
securityContext.getAccessTokens().put(accessToken.getResourceId(), accessToken);
OAuthSecurityContextHolder.setContext(securityContext);
Ideally, you should check whether an existing security context exists, and add the token to the map if it's not already present.
Related
My Spring Boot app is attempting to use Auth0 to validate a JWT it receives. My problem is the JWKS endpoint I have to connect to provides all of key information at the root of the URL, versus the well-known endpoint. My code snippet looks like so:
DecodedJWT jwt = JWT.decode(jwt);
JwkProvider provider = new UrlJwkProvider(new URL(configProperties.getKeyUrl()), 5000, 2000);
Jwk jwk = provider.get(jwt.getKeyId());
Is there a way to adapt JwkProvider to look at a different URL? The javadoc seems to say /.well-known... is going to be appended no matter what I do. Perhaps there's another library I can use?
So I finally decided the simplest thing to do was to edit the source from UrlJwkProvider myself. I created a new class and removed the code that appends the well known URL. Easy-peasy.
My Guidelines
If followed this Google documentation about verifying Google-Account-Tokens on the server side, but I am kinda confused.
My Problem
GoogleIdTokenVerifier googleIdTokenVerifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new JacksonFactory())
.setAudience(Collections.singletonList(CLIENT_ID))
.build();
In this piece of code I figured out that the transport and jsonFactory arguments can be filled as new NetHttpTransport() and new JacksonFactory() here. It also describes how to get AudienceString, but I couldn't figure out what it is for. I couldn't test it, but my question is if I can use it without .setAudience() or if I need it and what it is for.
In .setAudience() you have to pass all client ID's. You can get the ID for your client from the Credentials Page. It's explained here.
Thanks to #StevenSoneff.
If you didn't get the basic concept
For every client you want your server to accept, you need to create a project in the `Developer Console`. Clients are differentiated by their `SHA-1` fingerprint. You can for example have a debug project (will take your debug fingerprint) and a release one. To make both work, you have to add both `ID`'s to your server's `GoogleIdTokenVerifier`'s `.setAudience()`.
In my case, If you're using Firebase to get the id token on Android or iOS. You should follow these instructions to verify it on your backend server.
Verify ID tokens using a third-party JWT library
For me, I'm using Google OAuth Client as the third-party library so it's easy to use.
But it's a little bit different from this document.
Verify the Google ID token on your server side
The CLIENT_ID is your firebase project ID.
The Issuer has to be set as https://securetoken.google.com/<projectId>.
You need to use GooglePublicKeysManager and call setPublicCertsEncodedUrl to set it as https://www.googleapis.com/robot/v1/metadata/x509/securetoken#system.gserviceaccount.com
GooglePublicKeysManager manager = new GooglePublicKeysManager.Builder(HTTP_TRANSPORT, JSON_FACTORY)
.setPublicCertsEncodedUrl(PUBLIC_KEY_URL)
.build();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(manager)
.setAudience(Collections.singletonList(FIREBASE_PROJECT_ID))
.setIssuer(ISSUER)
.build();
If you have multiple issuers, then you have to create GoogleIdTokenVerifier for each one.
I have the following code:
Class<OAuthHandler> _tempClass = (Class<OAuthHandler>) Class.forName(providerClass);
Constructor<OAuthHandler> oAuthHandlerConstructor = _tempClass.getDeclaredConstructor(Vertx.class);
OAuthHandler oAuthHandler = oAuthHandlerConstructor.newInstance(vertx);
OAuth2Auth oAuth2Auth = oAuthHandler.getoAuth2Auth();
/* AccessToken accessToken = */ oAuth2Auth.getToken(oAuthHandler.getTokenConfig(code), accessTokenResponse -> {
if (accessTokenResponse.failed()) {
System.out.println("Failed to obtain token");
} else {
AccessToken accessToken = accessTokenResponse.result();
// Return the token? Somehow.
}
});
The oAuthHandler is a provider specific implementation providing some config etc based on the provider name, and simply wraps around the methods provided by the vertx-auth-oauth2 library.
I would like to use the access token after it returns, but not inside the getToken Lambda, so I can get any information about the user I need.
Ive seen some things about Vert.x Futures, but unsure if I can even use them here, any suggestions or examples to solutions would be much appreciated!
Vert.x OAuth2 support is not vendor specific. According to the documentation http://vertx.io/docs/vertx-web/java/#_oauth2authhandler_handler you will see that the same code can handle the following providers:
Google
Twitter
Github
LinkedIn
Facebook
Keycloak
and as soon as 3.4 is released some small fixes will make it also compatible with:
Azure AD
Also the handler is generic so if you have your own provider you can also use it.
Now regarding the second part of the question how to use the the token directly, then you probably do not want the OAuth2Handler since it hides all this from you and you want to interact with OAuth2 client directly:
http://vertx.io/docs/vertx-auth-oauth2/java/#_getting_started
From the documentation above there is an getting started code example that allows you to interact with the get token without using reflection. This is way better since you will not be hurt if internal api's change.
I am trying to make a Java class which would call upon Google's API to recreate an access token to a user's account with new permissions/larger scope. This class is to be instantiated by a Java servlet I had created. I want a function within that class to return a new access token. For this class to do that, I am using the Scribe library.
In Scribe's quick guide, there are two steps which concern me and have me stumped:
Step Three: Making the user validate your request token
Let’s help your users authorize your app to do the OAuth calls. For
this you need to redirect them to the following URL:
String authUrl = service.getAuthorizationUrl(requestToken);
After this either the user will get a verifier code (if this is an OOB
request) or you’ll receive a redirect from Twitter with the verifier
and the requestToken on it (if you provided a callbackUrl)
Step Four: Get the access Token
Now that you have (somehow) the verifier, you need to exchange your
requestToken and verifier for an accessToken which is the one used to
sign requests.
Verifier v = new Verifier("verifier you got from the user");
Token accessToken = service.getAccessToken(requestToken, v); // the requestToken you had from step 2
It does not seem to specify how to get that verifier from the user. How am I supposed to do that? How do I redirect my user to the authURL, and how do I get it to send its verifier back to this class of mine, which initiated the request to begin with?
If this is unclear, let me structure the question differently, taking Scribe out of the equation: To get an authorization code from Google (which would be used to then get a refresh token and access token), I would execute the following URL connection from within the servlet (yes, I've tried to answer this problem without the Scribe library, and still can't figure it out):
URL authURL = new URL("https://accounts.google.com/o/oauth2/auth");
HttpsURLConnection authCon = (HttpsURLConnection) authURL.openConnection();
authCon.setRequestMethod("GET");
authCon.setDoOutput(false);
authCon.setConnectTimeout(100000);
authCon.setRequestProperty("response_type", "code");
authCon.setRequestProperty("client_id", CLIENT_ID);
authCon.setRequestProperty("redirect_uri",
"http://**************.com/parseAuth/");
authCon.setRequestProperty("scope", convertToCommaDelimited(scopes));
authCon.setRequestProperty("state", csrfSec);
authCon.setRequestProperty("access_type", "offline");
authCon.setRequestProperty("approval_prompt", "auto");
authCon.setRequestProperty("include_granted_scopes", "true");
What has me stuck is what I should be putting for the redirect URI. After getting the user's approval for the new scope, this authorization URL would return an authorization code to the redirect URI, and seemingly nothing to whatever called it. (Am I correct in this?) So if I have another servlet as the redirect URI to parse/extract the authorization code from the response, how in the world do I get that authorization code back to my first, initial servlet? It seems to me that there is no way to have it give back the value to the servlet, in the same position of the code from which the URL was called. It looks like the function has to end there, and all new action must take place within that new servlet. But if that is the case, and I send that auth code to Google's API which would send back a refresh token and access token to ANOTHER servlet I would make to be its redirect URI, how do I possibly get that information back to what it is which called the initial servlet to begin with? That seems to be the same problem at its core, with the problem I am having with Scribe.
I've been stuck on this for many hours, and can't seem to figure out what it is I am supposed to do. I feel like I am missing some key concept, element, or step. I need this clarified. If it is at all relevant, my servlet is hosted on a Jboss application server on OpenShift.
Applications such a Google's Chrome and IE can transparently handle Kerberos authentication; however I can not find a "simple" Java solution to match this transparency. All of the solutions I have found require the presence of a krb5.conf file and a login.conf file which nether of the above apps seem to require.
What is the best way to build a Java application with Kerberos SSO capabilities that just work?
[update]: to be clear I need a CLIENT side solution for creating tickets not validating them. Also, it seems that SPNEGO is the default "wrapper" protocol that will eventually delegate to Kerberos but I need to be able to handle the SPNEGO protocol as well.
There is now a simple solution for this using the Apache HTTP Components Client 4.5 or greater. This is still marked as experimental in 4.5 so your milage may vary, but this is working fine for me in an enterprise context.
In addition to the HC 4.5 client jars you will need to have the httpclient-win, jna and jna-platform jars on your classpath, as provided with http-component-client. You then construct a Kerberos enabled HC-client as follows:
CloseableHttpClient httpclient = WinHttpClients.createDefault();
Or using the builder:
HttpClientBuilder clientBuilder = WinHttpClients.custom();
Which can then be customised as required before building the client:
CloseableHttpClient client = clientBuilder.build();
This solution works without any external configuration, and most importantly solves the issue where the in-built JRE mechanism breaks for users with local Admin rights on Windows 7+. This is possible because the Kerberos ticket is being retrieved directly from the SSPI API via JNA, rather than going through the GSSAPI provided by the JRE.
Example code from the http-components team
This was all made possible by the good work of Daniel Doubrovkine Timothy Wall
and Ryan McKinley
Adding to David Roussels answer on url specific http based kerberos authentication:-
The reason why your code works is because your target SPN(server side principal) is configured to with HTTP/serverhostname.realm.com#DOMAIN.COM. In that case it will work because you are not explicitly setting the token. URLConnection internally sets a token with that SPN
1 Perform steps(from my previous answer) to get a subject
2 Use gss api init sec context to generate a context token. There are numerous tutorials out there for this step
3 Base 64 encode the token
4 Attach the token to urlconnection:-
URL url = new URL("http://myhost/myapp")
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(); =
urlConn.setRequestProperty("Authorization", "Negotiate " + encodedToken);
5 Implement a priviledged action:-
//this internally calls the getInputStream
public class PrivilegedGetInputStream implements PrivilegedExceptionAction<InputStream>
6 Wrap the whole thing in Subject.doAs
//use prev answer instructions to get subject
Subject.doAs(subject, new PrivilegedGetInputStream(urlConnection)
Oracle has an example using Java's SaslClient. I'm not a Java programmer, but when I pointed this out once to someone who is, they were able to make it work pretty quickly. It may still require a "conf" file somewhere (n.b. Kerberos uses environment variables, often starting with KRB5_, to know where to look for such files). Also note that Kerberos itself does not include a transport of any kind--your app needs to know how to send and receive the Kerberos payloads the way the server expects (and this is different depending on the server you are trying to authenticate with).
Edit: you edited your question, so here's a link related to SPNEGO in Java which might be of some use:
http://download.oracle.com/javase/6/docs/technotes/guides/security/jgss/lab/part5.html
You don't actually need to do anything. In Java 6, on a Windows client machine you can do this:
new URL("http://myhost/myapp").openStream();
And negotiate authentication just works. At least it does for me. And the server I tested on only supports Negotiate, not NTLM auth.
Ok if you want to avoid using a login.conf file you need to code differently:-
//define your own configuration
import javax.security.auth.login.Configuration;
public class CustomLoginConfiguration extends Configuration
//pass certain parameters to its constructor
//define an config entry
import javax.security.auth.login.AppConfigurationEntry;
private AppConfigurationEntry configEntry;
//define a map of params you wish to pass and fill them up
//the map contains entries similar to one you have in login.conf
Map<String, String> params = new HashMap<String, String>();
//define the configuration
configEntry = new AppConfigurationEntry(
"com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, params);
//implement getappconfig method
public AppConfigurationEntry[] getAppConfigurationEntry() {
return new AppConfigurationEntry[] { configEntry };
}
Now once you are done with this definition you can use this in you use this to fetch tickets from kdc
//get ticket in login context
LoginContext lc = null;
lc = new LoginContext("lc", null, callback, new CustomLoginConfiguration(argumentlist));
lc.login();
Now from here on you can fetch jaas subject and can basically do a ton of authentication stuff.
In case you need further pointers just leave a comment.
You can use system properties instead of config files to specify the KDC hostname and service name, but those things (at least) are mandatory....
Waffle will actually give you the information you need to set most of the properties, even if it won't get you a ticket. Look at the WindowsAuthProviderImpl class (the Waffle.chm help file shows the API).
I use JAAS do obtain a service ticket from Active Directory in two steps:
Use Krb5LoginModule to retrieve the cached TGT and add it to the Subject.
Use the Subject and GSS-API to retrieve a service ticket from the KDC.
There's a lot of good information and example code at The Java Way of Active Directory.
I created a small tool to simplify connecting with httpclient to kerberos, you might want to give it a try.
https://github.com/DovAmir/httpclientAuthHelper
DefaultHttpClient httpclient = new DefaultHttpClient();
AuthUtils.securityLogging(SecurityLogType.KERBEROS,true);
CredentialsUtils.setKerberosCredentials(client, new UsernamePasswordCredentials("xxx", "xxx"), "domain", "kdc");
client.executeMethod(httpget);
Use WAFFLE
Here's a good blog post on having a java client to use with Kerberos
http://sachithdhanushka.blogspot.com/2014/02/kerberos-java-client-configuration.html