I am using Keycloak-connect, the Keycloak adapter for nodejs. In my express app, there is an app.post('/routes/login') endpoint that the login form posts to. In that endpoint there is an authentication method that I am trying to replace with Keycloak. That method just takes the username and password (and request and response object), authenticates, and returns true if the authentication was successful. Is there an equivalent I can use in the Keycloak-connect-api? I was looking but the documentation was rather poor for that adapter.
In the end I am trying to use my own login page to log in to Keycloak.
Maybe with Keycloak.grantmanager.obtainDirectly ?
You can use
keycloak.grantManager.obtainDirectly(username, password) like that way and return the token to client.
or you can use rest api provided by keycloak
let tokenObject = await axios.post(`http://localhost:8080/auth/realms/${realmName}/protocol/openid-connect/token`, requestBody );
if(tokenObject.status === 200){
accessToken = tokenObject.data.access_token;
}
Related
I am using the OpenID client to authenticate the user, what I would like to do is call a protected route on an express API.
I am trying to share the authorization cookie obtained with the react app with OpenID, and the xenter image description here
I tried:
simply passport.authenticate(), with the openID strategy, but does redirection which isnt necessary
Not sure if this is the correct way but, this is how I kinda did it:
const user = await auth0Client.getUser();
// Attach token
const accessToken = await auth0Client.getTokenSilently();
axios.defaults.headers.common.Authorization = `Bearer ${accessToken}`;
Then I just used the passport JWT strategy combined with jwks-rsa library to obtain the secret.
I am working on AWS Lambda using node.js. I am using node-salesforce to connect to SF App using OAuth. I am not able to get refresh token after login.
var conn = new sf.Connection({
oauth2 : {
clientId : 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
clientSecret : 'XXXXXXXXXXXXXXXX',
redirectUri : 'https://localhost/callback'
}
});
conn.login('Username', 'XXXXXXXXX', function(err, userInfo) {
if (err) { return console.error(err); }
console.log(userInfo);
console.log(conn);
});
In the output I am expecting a refresh Token that is coming undefined. I am able to get accessToken which I am using for further operation. Now how do i update access token in case of change of access token.
I have gone through its documentation(https://www.npmjs.com/package/node-salesforce). It has a way in which they have used express.js and redirect to salesforce page for authorisation. Since this is written in lambda so I will not prefer to use express.js here or redirection for authorisation.
My problem is how to get refresh token here. Is there any way to do this. Please let me know if I am doing anything wrong.
In order to get a refresh token, you need to specify that you will be using this accessToken offline. This is typically done via a header, but sometimes done via a URL param.
I need to log on through OAuth 2 how can I do that without using WebView in Android?
Thanks.
In the latest v4.5.7 of ServiceStack you'll be able to login into Twitter, Facebook or Github using their SDKs and previous saved access tokens.
Authentication via AccessToken is also made available to OAuth2 providers in the same way where you can authenticate directly by adding the AccessToken to the Authenticate Request DTO, e.g:
var request = new Authenticate
{
provider = "GoogleOAuth",
AccessToken = GoogleOAuthAccessToken,
};
var response = client.Post(request);
response.PrintDump();
Although you will first need to retrieve the AccessToken which typically requires opening a WebView to capture Users consent.
For other OAuth2 providers other than Google Auth you will need to provide an implementation of VerifyAccessToken that returns a boolean that determines whether the AccessToken is valid or not, e.g:
new MyOAuth2Provider {
VerifyAccessToken = accessToken => MyValidate(ConsumerKey,accessToken),
}
This is different for each OAuth provider where some don't provide an API that lets you determine whether the AccessToken is valid with your App or not.
I am creating an Android/iOS app which communicates with a Node.js server and would like to identify them securely on my server using Google (and/or Facebook) and OAuth2. I've looked at the following documentation: https://developers.google.com/+/web/signin/server-side-flow
I do not need authorization, I only need authentication (I only want to make sure that the person calling my Node.js service is the person they say they are). To achieve this, if I understand properly, I have to let the user log in using Google on the client side, this will give them an authorization_code which they can then give to my server. My server can then exchange that code for an access_token, and therefore retrieve information about the user. I am then guaranteed that the user is the person they say they are.
The Google documentations (link above) says: "In the Authorized redirect URI field, delete the default value. It is not used for this case.", however, for my server to exchange the authorization_code for an access_token, it needs to provide a redirect_uri, am I missing something?
The redirect_uri is useless for Unity games, for instance (since logging in with Google simply opens a new "window", which is closed when logged in, no redirection involved).
TL;DR
How do you use OAuth2 to authenticate users between my client and my server without redirection?
TL;DR How do you use OAuth2 to authenticate users between my client and my server without redirection?
You can't. OAuth requires that the user is directed to an authorization (and possibly login) screen, and then redirected back to your app.
EDIT 20/12/22. See comment below regarding latest status
Have you looked at this documentation? https://developers.google.com/accounts/docs/OAuth2InstalledApp#choosingredirecturi
Choosing a redirect URI
When you create a client ID in the Google Developers Console, two
redirect_uris are created for you: urn:ietf:wg:oauth:2.0:oob and
http://localhost. The value your application uses determines how the
authorization code is returned to your application.
http://localhost
This value signals to the Google Authorization Server that the
authorization code should be returned as a query string parameter to
the web server on the client. You may specify a port number without
changing the Google Developers Console configuration. To receive the
authorization code using this URL, your application must be listening
on the local web server. This is possible on many, but not all,
platforms. If your platform supports it, this is the recommended
mechanism for obtaining the authorization code.
I had this problem and it took me ages to find the "postmessage" solution that Nepoxx mentions in the comments of the accepted answer here.
For clarification, here's what worked for me.
Follow steps 1-6 here: https://developers.google.com/identity/sign-in/web/server-side-flow
Install googleapis library npm install --save googleapis
For the server-side token exchange do this:
var googleapis = require('googleapis');
var OAuth2 = googleapis.auth.OAuth2;
var oauth2Client = new OAuth2(
GOOGLE_SSO_CLIENT_ID,
GOOGLE_SSO_CLIENT_SECRET,
'postmessage' // this is where you might otherwise specifiy a redirect_uri
);
oauth2Client.getToken(CODE_FROM_STEP_5_OF_INSTRUCTIONS, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
});
The redirect_uri can be a URL with a custom URL scheme for which the client registered a handler. This is described here: What's a redirect URI? how does it apply to iOS app for OAuth2.0?. It is not so much about "redirecting" it is about a callback endpoint to your app.
And it become really easy if you use VueJS with https://github.com/guruahn/vue-google-oauth2
Client side
import GAuth from 'vue-google-oauth2'
Vue.use(GAuth, {
clientId: 'xxxxxxx.apps.googleusercontent.com',
scope: 'profile',
})
async signWithGoogle() {
const code = await this.$gAuth.getAuthCode() //
console.log(code ) // { code: 'x/xxxxxxxxxx' }
// send the code to your auth server
// and retrieve a JWT or something to keep in localstorage
// to send on every request and compare with database
}
Server side
import { google } from 'googleapis'
const oauth2Client = new google.auth.OAuth2(GOOGLE_ID, GOOGLE_SECRET, 'postmessage')
google.options({ auth: oauth2Client })
async function getAccount(code) {
// the code you sent with the client
const { tokens } = await oauth2Client.getToken(code)
oauth2Client.setCredentials(tokens)
const oauth2 = google.oauth2({ version: 'v2' })
const { data: { id } } = await oauth2.userinfo.get()
// there you have the id of the user to store it in the database
// and send it back in a JWT
}
Lets say I have a web client (i.e. MVC 4 client) that authenticates users using an oAuth provider (i.e. Facebook, Google etc).
I want to call another web service in my client logic, and that web service also authenticates with oAuth providers.
What would the web service request look like from the client? What do I need to pass to the web service?
I suggest you review this question, How do I authorize access to ServiceStack resources using OAuth2 access tokens via DotNetOpenAuth?. The poster provided his final solution, including a link to a sample solution, which he has graciously open sourced. The client side code, for his solution, looks like this:
// Create the ServiceStack API client and the request DTO
var apiClient = new JsonServiceClient("http://api.mysite.com/");
var apiRequestDto = new Shortlists { Name = "dylan" };
// Wire up the ServiceStack client filter so that DotNetOpenAuth can
// add the authorization header before the request is sent
// to the API server
apiClient.LocalHttpWebRequestFilter = request => {
// This is the magic line that makes all the client-side magic work :)
ClientBase.AuthorizeRequest(request, accessTokenTextBox.Text);
}
// Send the API request and dump the response to our output TextBox
var helloResponseDto = apiClient.Get(apiRequestDto);
Console.WriteLine(helloResponseDto.Result);
A similar solution is provided here: https://stackoverflow.com/a/13791078/149060 which demonstrates request signing as per OAuth 1.0a
var client = new JsonServiceClient (baseUri);
client.LocalHttpWebRequestFilter += (request) => {
// compute signature using request and a previously obtained
// access token
string authorization_header = CalculateSignature (request, access_token);
request.Headers.Add ("Authorization", authorization_header);
};
var response = client.Get<MySecuredResponse> ("/my/service");
You will, of course, need to adjust to fit the requirements of your OAuth providers, i.e. signing, token, etc.