I'm working on building a library for a client to integrate with LinkedIn's API and am currently working on the OAuth implementation. I am able to request the initial token's no problem and have the user grant the authentication to my app, but when I try to request the access token with the oauth_token and oauth_verifier (along with the rest of the oauth information that I send with ever request, I get a signature invalid error.
The OAuth settings that I send are as follows:
oauth_consumer_key
oauth_nonce
oauth_timestamp
oauth_signature_method
oauth_version
oauth_token
oauth_verifier
I also add in the oauth_signature which is a signed version of all of those keys. I sign the request with the following method:
public void function signRequest(any req){
var params = Arguments.req.getAllParameters();
var secret = "#Variables.encoder.parameterEncodedFormat(getConsumer().getConsumerSecret())#&#Variables.encoder.parameterEncodedFormat(Arguments.req.getOAuthSecret())#";
var base = '';
params = Variables.encoder.encodedParameter(params, true, true);
secret = toBinary(toBase64(secret));
local.mac = createObject('java', 'javax.crypto.Mac').getInstance('HmacSHA1');
local.key = createObject('java', 'javax.crypto.spec.SecretKeySpec').init(secret, local.mac.getAlgorithm());
base = "#Arguments.req.getMethod()#&";
base = base & Variables.encoder.parameterEncodedFormat(Arguments.req.getRequestUrl());
base = "#base#&#Variables.encoder.parameterEncodedFormat(params)#";
local.mac.init(local.key);
local.mac.update(JavaCast('string', base).getBytes());
Arguments.req.addParameter('oauth_signature', toString(toBase64(mac.doFinal())), true);
}
I know that it works, because I can use the same method to request the initial token (without the oauth_token or oauth_verifier parameters), so I am assuming that it is a problem with the parameters that I am signing. (And yes I am alphabetically ordering the parameters before I sign them)
So is there a parameter that I shouldn't be including in the signature or another one that I should be?
This is an example of a base string that gets encrypted:
POST&https%3A%2F%2Fwww.linkedin.com%2Fuas%2Foauth%2FaccessToken&oauth_consumer_key%3Dwfs3ema3hi9s%26oauth_nonce%3D1887241367210%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1331326503%26oauth_token%3D8b83142a-d5a6-452e-80ef-6e75b1b0ce18%26oauth_verifier%3D94828%26oauth_version%3D1.0
When sending a POST request, you need to put the authentication information in the header, not in the query parameters.
See this page for information (look for "Sending an Authorization Header"):
https://developer.linkedin.com/documents/common-issues-oauth-authentication
I suspect this is the issue you're running into.
Okay, so it was a stupid answer, but the problem was that I didn't see the oauth_token_secret come in when the user allowed access to my app, so I was still trying to sign the request using only the consumer secret and not both the consumer secret and oauth token secret.
Related
I am building an application. The client is built with Next.js and the backend with Django and Django REST framework.
In this application, I would like to have social login.
So far, my situation is this.
I have set up the OAuth on the Google dashboard
On the client, I am using next-auth - The client is successfully calling Google and getting an access token from there.
On the client, the callback that runs after getting the access token from Google makes a call my Django API.
I have set up the backend with dj_rest_auth - My settings are almost identical to the ones described here.
Once the client callback runs and calls my Django API with the access token from Google, I successfully get on the client an access token and a refresh token.
If it is a new user loggin in the first time, a new user is created in Djangos DB
const response = await fetch(`${djangoAPIurl}/api/social/login/google/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
access_token: accessToken,
id_token: idToken
})
});
const data = await response.json();
const { access_token, refresh_token } = data;
Both access_token and refresh_token are defined and appear to be valid tokens.
So far, everything happens as expected. My issue appears after this point.
In my api, I have another view defined.
#api_view(['GET'])
#authentication_classes([SessionAuthentication, BasicAuthentication, TokenAuthentication])
#permission_classes([IsAuthenticated])
def test_view(request):
current_user = request.user
print('current_user.auth: ', current_user.is_authenticated)
response = JsonResponse({"received": True})
return response
From my client, I am attempting to call this view in the following way.
const response = await fetch(`${djangoAPIurl}/api/test/test_view/`, {
headers: new Headers({
Authorization: `Bearer ${session.accessToken}`
})
});
The header is constructed correctly, with session.accessToken being the value I got from the api/social/login/google/ call and the request is routed correctly, however, it fails with Forbidden 403 because the user is not authenticated. I have removed the authentication and permission decrators and the request ends up being processed by the view, and there, upon inspection of the user, it is an Anonymous user. I have also tried changing Bearer to Token, to no avail.
Do you have any advice what I might be doing wrong or missing? Have I completely missunderstood how to use the token I get back from api/social/login/google/? All advice is much appreicated!
I think this is because your secret for hashing JWTS on the client side and server side is not same. Next-Auth automatically creates a secret key for hashing jwt's and dj_rest_auth does the same, unless you explicitly tell them both to use the same secret for hashing jwts. I'm a bit late to answer this, but Hope this will help future people😁😁.
I'm allowing users logged in an external application to jump into our application with their access token through Keycloak's identity brokering and external to internal token exchange.
Now I'd like to establish an SSO session in an embedded JxBrowser in our application similar to a regular browser login flow, where three cookies are set in the browser: AUTH_SESSION, KEYCLOAK_SESSION(_LEGACY) and KEYCLOAK_IDENTITY(_LEGACY).
KEYCLOAK_IDENTITY contains a token of type Serialized-ID which looks somewhat similar to an ID token.
Is it possible to create the KEYCLOAK_IDENTITY cookie using the exchanged (internal) access and/or ID token and, provided that the other two cookies are correctly created as well, would this establish a valid SSO session?
Basically all I am missing is how I could obtain or create the Serialized-ID type token.
One way to achieve this:
Implement a custom endpoint following this example
Note that the provider works fine for me without registering it in standalone.xml, I'm just adding the JAR to the Keycloak Docker image.
Add a method that validates a given access token, looks up the user, gets the user session and sets the cookies in the response (most error handling omitted for brevity):
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("sso")
public Response sso(#Context final HttpRequest request) {
final HttpHeaders headers = request.getHttpHeaders();
final String authorization = headers.getHeaderString(HttpHeaders.AUTHORIZATION);
final String[] value = authorization.split(" ");
final String accessToken = value[1];
final AccessToken token = Tokens.getAccessToken(accessToken, keycloakSession);
if (token == null) {
throw new ErrorResponseException(Errors.INVALID_TOKEN, "Invalid access token", Status.UNAUTHORIZED);
}
final RealmModel realm = keycloakSession.getContext().getRealm();
final UriInfo uriInfo = keycloakSession.getContext().getUri();
final ClientConnection clientConnection = keycloakSession.getContext().getConnection();
final UserModel user = keycloakSession.users().getUserById(token.getSubject(), realm);
final UserSessionModel userSession = keycloakSession.sessions().getUserSession(realm, token.getSessionState());
AuthenticationManager.createLoginCookie(keycloakSession, realm, user, userSession, uriInfo, clientConnection);
return Response.noContent().build();
}
Disclaimer: I am not completely certain this implementation does not imply any security issues, but since Tokens.getAccessToken(accessToken, keycloakSession) does full validation of the access token, setting the cookies should only be possible with a valid access token.
For CORS, add:
#OPTIONS
#Produces(MediaType.APPLICATION_JSON)
#Path("sso")
public Response preflight(#Context final HttpRequest request) {
return Cors.add(request, Response.ok("", MediaType.APPLICATION_JSON))
.auth()
.preflight()
.allowedMethods("GET", "OPTIONS")
.build();
}
and in sso():
return Cors.add(request, Response.ok("", MediaType.APPLICATION_JSON))
.auth()
.allowedMethods("GET")
.allowedOrigins(token)
.build();
What I am uncertain about is why Firefox preflights the GET request, making it necessary to handle that.
Im using version version 1.0.0 of the IdentityServer4 package.
"IdentityServer4": "1.0.0"
I've created a Client
new Client
{
ClientId = "MobleAPP",
ClientName = "Moble App",
ClientUri= "http://localhost:52997/api/",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
ClientSecrets =
{
new Secret("SecretForMobleAPP".Sha256())
},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api"
},
AllowOfflineAccess = true
}
And the scope/ApiResources
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api", "My API")
};
}
With the following user/TestUser
public static List<TestUser> GetUsers()
{
return new List<TestUser>
{
new TestUser
{
SubjectId = "2",
Username = "bob",
Password = "password",
Claims = new []
{
new Claim(JwtClaimTypes.Name, "Bob Smith")
}
}
};
}
I'm trying to test the IdentityServer that I have setup from Postman and determine the possible values for the grant_type key value pair.
I can successfully connect when I set the grant_type to client_credentials and wasn't sure if there were other options for the grant_type value.
Working Postman configuration with grant_type set to client_credentials
Short answer
client_credentials is the only grant_type value you can use directly against the token endpoint when using both hybrid and client credentials grant types.
Longer answer
The client credentials grant type is the only one allowing you to hit the token endpoint directly, which is what you did in your Postman example. In that case the authentication is done against the client itself - i.e. the application you registered.
When you use the hybrid grant type, the authentication will be done against the end-user - the user using your application. In that case, you cannot hit the endpoint token directly but you'll have to issue an authorization request to IdentityServer.
When you do so, you won't use the grant_type parameter but the response_type parameter, to instruct IdentityServer what you expect back.
The possible values for response_type when you use the hybrid grant type can be found in IdentityServer constants - they are the last 3 items in the dictionary:
code id_token, which will return an authorization code and an identity token
code token, returning an authorization code and an access token
code id_token token, giving you back an authorization code, an identity token and an access token
After you get the authorization code, you'll be able to exchange it for an access token and possibily a refresh token by hitting the token endpoint.
I getting back into Python and wanted to use the pyfoursquare package to access the Foursquare API. I'm trying to get information about venues using the venues method in the API class. I'm primarily trying to find out whether a venue page is verified with Foursquare or not. When I provide my client id, client secret, and venue id I keep getting back an error that states "Authentication required", which doesn't makes sense because I'm providing that information. Any help would be great. Thank you.
import pyfoursquare as foursquare
client_id = ""
client_secret = ""
callback = ""
auth = foursquare.OAuthHandler(client_id, client_secret, callback)
api = foursquare.API(auth)
result = api.venues("4e011a3e62843b639cfa9449")
print result[0].name
Let me know if you would like to see the error message. Thanks again.
I believe you are skipping the step of grabbing your OAuth2 access token, so you're not technically authenticated.
Have a look at the following instructions, under "How to Use It":
https://github.com/marcelcaraciolo/foursquare
The lines that might be useful to you are:
#First Redirect the user who wish to authenticate to.
#It will be create the authorization url for your app
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
#If the user accepts, it will be redirected back
#to your registered REDIRECT_URI.
#It will give you a code as
#https://YOUR_REGISTERED_REDIRECT_URI/?code=CODE
code = raw_input('The code: ').strip()
#Now your server will make a request for
#the access token. You can save this
#for future access for your app for this user
access_token = auth.get_access_token(code)
print 'Your access token is ' + access_token
I'm trying to follow this Oauth2 guide for Sign in With Twitter https://github.com/simplegeo/python-oauth2 - Everything is going great until between steps 2 and 3. I handle the the callback fine, but how do I pass along the oauth_token_secret? My confusion is that it seems like it's lost after the redirect back to my handler.
From what I can tell the parameters I get back are oauth_token and oauth_verifier, and yet I need the oauth_token_secret to receive the access token in these steps.
token = oauth.Token(request_token['oauth_token'],
request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, "POST")
access_token = dict(urlparse.parse_qsl(content))
Am I supposed to store it in a cookie to retrieve later?
I was able to do this by storing the oauth_token and oauth_token_secret in a session during step one. These values are stored from the created request token request_token['oauth_token']