I can't seem to find any documentation on how to restrict the login to my web application (which uses OAuth2.0 and Google APIs) to only accept authentication requests from users with an email on a specific domain name or set of domain names. I would like to whitelist as opposed to blacklist.
Does anyone have suggestions on how to do this, documentation on the officially accepted method of doing so, or an easy, secure work around?
For the record, I do not know any info about the user until they attempt to log in through Google's OAuth authentication. All I receive back is the basic user info and email.
So I've got an answer for you. In the OAuth request you can add hd=example.com and it will restrict authentication to users from that domain (I don't know if you can do multiple domains). You can find hd parameter documented here
I'm using the Google API libraries from here: http://code.google.com/p/google-api-php-client/wiki/OAuth2 so I had to manually edit the /auth/apiOAuth2.php file to this:
public function createAuthUrl($scope) {
$params = array(
'response_type=code',
'redirect_uri=' . urlencode($this->redirectUri),
'client_id=' . urlencode($this->clientId),
'scope=' . urlencode($scope),
'access_type=' . urlencode($this->accessType),
'approval_prompt=' . urlencode($this->approvalPrompt),
'hd=example.com'
);
if (isset($this->state)) {
$params[] = 'state=' . urlencode($this->state);
}
$params = implode('&', $params);
return self::OAUTH2_AUTH_URL . "?$params";
}
I'm still working on this app and found this, which may be the more correct answer to this question. https://developers.google.com/google-apps/profiles/
Client Side:
Using the auth2 init function, you can pass the hosted_domain parameter to restrict the accounts listed on the signin popup to those matching your hosted_domain. You can see this in the documentation here: https://developers.google.com/identity/sign-in/web/reference
Server Side:
Even with a restricted client-side list you will need to verify that the id_token matches the hosted domain you specified. For some implementations this means checking the hd attribute you receive from Google after verifying the token.
Full Stack Example:
Web Code:
gapi.load('auth2', function () {
// init auth2 with your hosted_domain
// only matching accounts will show up in the list or be accepted
var auth2 = gapi.auth2.init({
client_id: "your-client-id.apps.googleusercontent.com",
hosted_domain: 'your-special-domain.example'
});
// setup your signin button
auth2.attachClickHandler(yourButtonElement, {});
// when the current user changes
auth2.currentUser.listen(function (user) {
// if the user is signed in
if (user && user.isSignedIn()) {
// validate the token on your server,
// your server will need to double check that the
// `hd` matches your specified `hosted_domain`;
validateTokenOnYourServer(user.getAuthResponse().id_token)
.then(function () {
console.log('yay');
})
.catch(function (err) {
auth2.then(function() { auth2.signOut(); });
});
}
});
});
Server Code (using googles Node.js library):
If you're not using Node.js you can view other examples here: https://developers.google.com/identity/sign-in/web/backend-auth
const GoogleAuth = require('google-auth-library');
const Auth = new GoogleAuth();
const authData = JSON.parse(fs.readFileSync(your_auth_creds_json_file));
const oauth = new Auth.OAuth2(authData.web.client_id, authData.web.client_secret);
const acceptableISSs = new Set(
['accounts.google.com', 'https://accounts.google.com']
);
const validateToken = (token) => {
return new Promise((resolve, reject) => {
if (!token) {
reject();
}
oauth.verifyIdToken(token, null, (err, ticket) => {
if (err) {
return reject(err);
}
const payload = ticket.getPayload();
const tokenIsOK = payload &&
payload.aud === authData.web.client_id &&
new Date(payload.exp * 1000) > new Date() &&
acceptableISSs.has(payload.iss) &&
payload.hd === 'your-special-domain.example';
return tokenIsOK ? resolve() : reject();
});
});
};
When defining your provider, pass in a hash at the end with the 'hd' parameter. You can read up on that here. https://developers.google.com/accounts/docs/OpenIDConnect#hd-param
E.g., for config/initializers/devise.rb
config.omniauth :google_oauth2, 'identifier', 'key', {hd: 'yourdomain.com'}
Here's what I did using passport in node.js. profile is the user attempting to log in.
//passed, stringified email login
var emailString = String(profile.emails[0].value);
//the domain you want to whitelist
var yourDomain = '#google.com';
//check the x amount of characters including and after # symbol of passed user login.
//This means '#google.com' must be the final set of characters in the attempted login
var domain = emailString.substr(emailString.length - yourDomain.length);
//I send the user back to the login screen if domain does not match
if (domain != yourDomain)
return done(err);
Then just create logic to look for multiple domains instead of just one. I believe this method is secure because 1. the '#' symbol is not a valid character in the first or second part of an email address. I could not trick the function by creating an email address like mike#fake#google.com 2. In a traditional login system I could, but this email address could never exist in Google. If it's not a valid Google account, you can't login.
Since 2015 there has been a function in the library to set this without needing to edit the source of the library as in the workaround by aaron-bruce
Before generating the url just call setHostedDomain against your Google Client
$client->setHostedDomain("HOSTED DOMAIN")
For login with Google using Laravel Socialite
https://laravel.com/docs/8.x/socialite#optional-parameters
use Laravel\Socialite\Facades\Socialite;
return Socialite::driver('google')
->with(['hd' => 'pontomais.com.br'])
->redirect();
Related
Probleme
I want to create a server application that modifies playlists on spotify, deezer and youtube (to create multi-platform playlists). My problem is that these different services require OAuth2 authentication to manipulate playlists, and that this authentication requires human intervention
What I've tried
I tried to use the api key, but it did not allow me to edit the playlist (access_key needed).
My Research
from what I understood from the different documentation, the api key is made for server applications (like my case) and that the OAuth2 authentication is more made to authenticate a client.
Question
how to authenticate a server side application with an OAuth2 flow. or how to allow a server application to modify/manipulate playlists on youtube, spotify, deezer.
Details
i use node server.
The first thing you need to under stand is the difference between public and private data. Private data is data that is not owned by anyone that any one has access to. Public videos on YouTube for example can be read by anyone. Private user data is data that is owned by a user that being their play lists for example.
API keys will only give you access to public data not private user data.
The only flow available to you to read YouTube private user data is Ouath2. What you should do is follow the official node.js sample.
When you run this sample it is single user it will store the user credentials in TOKEN_DIR. Then it will use the refresh token that was generated in order to request a new access token when ever it needs one. So you will need to authorize your code once then it will be able to run on your server without you having to grant it permissions.
var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the YouTube API.
authorize(JSON.parse(content), getChannel);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* #param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* #param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) throw err;
console.log('Token stored to ' + TOKEN_PATH);
});
}
/**
* Lists the names and IDs of up to 10 files.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function getChannel(auth) {
var service = google.youtube('v3');
service.channels.list({
auth: auth,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers'
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.data.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
'it has %s views.',
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount);
}
});
}
You may want to monitor it there are some instances where a refresh token will be expired in the event that happens you will need to authorize the application again.
An OAuth 2 application delegates the authentication to services (eg. Google, Spotify, Amazon, Github, LinkedIn, etc.) that host a user account and asks for (limited) authorization from those services, after the user has given consent.
There is a difference between authentication and authorization.
Authentication makes sure a user is who they're claiming to be. Whereas Authorization governs what the user has access to.
So your OAuth2 application is leveraging Spotify social account integration to delegate authentication to Spotify and in turn receiving limited authorization to modify playlists (only).
To answer your question: To be able to perform any action (eg. modify Spotify playlists) you'd need the access token from Spotify API. Here's what the process looks like:
User logs in to your website using their Spotify account.
User is redirected to the consent screen. They give approval for the permissions your application is asking for (i.e., modify playlist permission).
Once the user consents, your application receives an access token (along with a refresh token, and profile information).
Your application then uses the provided access token to modify the user playlists.
Passportjs is a very well built library around OAuth2 and it has support for Spotify OAuth2. I have recently documented about the complete process to implement multi-provider OAuth2 in node.js along with the explanations.
I am working on a flutter application, and I want to implement social login (Google and Facebook).
My API is implemented with Laravel and uses Laravel-socialite to authenticate users, there is the backend, web frontend (using VueJs) and now I am working on the mobile application using flutter.
The web application is working good (using the vue-social-auth package).
What I have done till now:
Used flutter_google_sign_in to handle authentication on the flutter app.
Did configure the package and I can successfully get user info through that package.
Problem I am facing:
What I don't seem to get working is to send the user that just logged in to the backend in order to provide an in-app user experience.
This is what the vue-social-auth package provides and what I send to the backend, which is working fine:
{code: "4/0AY0e-g442SMxdtLb_MVdQ63u1ydp48bbCRQco5Azoyf3y1rvYybDabyZGOvwAs7ZFJDQHA", scope: "email+profile+openid+https://www.googleapis.com/au…le+https://www.googleapis.com/auth/userinfo.email", authuser: "0", prompt: "consent"}
And this is what flutter_google_sign_in gives (aside of the user profile data:
idToken: "",
accessToken: "",
serverAuthCode: "",
serverAuthCode is always null.
How can I make it so that, using the same API logic, log-in users on flutter through social accounts?
Thank you.
Apparently, google sign in doesn't work on flutter except with Firebase/some cloud API backend service. I was using a local Laravel API for user auth so adding google sign in functionality requires setting up a firebase account/profile, downloading and adding the googleservices.json file to flutter project as explained in google_sign_in package installation manual. You also need to import firebase-auth package
Flutter Code (I use flutter modular pattern but same applies with Bloc/Provider if you get the idea as explained by Hamza Mogni above)
import 'package:google_sign_in/google_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<LoginResponseModel> googleLoginResponse() async {
String url = env['API_BASE_URL'] + '/api/auth/google';
//click on google sign in. Get accessToken from google through googlesignin
plugin.
//Send accessToken to socialite in backend to request/create user data
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
if (googleSignInAccount == null) {
print('Google Signin ERROR! googleAccount: null!');
return null;
}
GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
//this is user access token from google that is retrieved with the plugin
print("User Access Token: ${googleSignInAuthentication.accessToken}");
String accessToken = googleSignInAuthentication.accessToken;
//make http request to the laravel backend
final response =
await http.post(
url,
body: json.encode({"token": accessToken}),
headers: {"Content-Type": "application/json"});
if (response.statusCode == 200 || response.statusCode == 422) {
return LoginResponseModel.fromJson(
json.decode(response.body), // {'message':'Google signin successful'}
);
} else {
throw Exception('Failed to load data!');
}
}
For Logout function, you need to signout of both firebase and google account instance or you will always be logged in by the first known/used google account in subsequent login attempts.
Future<LogoutResponseModel> logout() async {
try {
await _auth.signOut();
await _googleSignIn.disconnect();
} catch (e) {
print('Failed to sign out ' + e.toString());
}
//api route to destroy sanctum token. santum token is added as authorization header
var url = env['API_BASE_URL'] + "/api/logout";
final response =
await http.post(Uri.tryParse(url), headers: {'Bearer ' $sanctumtoken});
if (response.statusCode == 200 || response.statusCode == 422) {
return LogoutResponseModel.fromJson(
json.decode(response.body),
);
} else {
throw Exception('Failed to load data!');
}
}
Laravel Code (route to controller method is api/auth/google, method expects to receive google access token from flutter app)
public function requestTokenGoogle(Request $request) {
// Getting the user from socialite using token from google
$user = Socialite::driver('google')->stateless()->userFromToken($request->token);
// Getting or creating user from db
$userFromDb = User::firstOrCreate(
['email' => $user->getEmail()],
[
'email_verified_at' => now(),
'first_name' => $user->offsetGet('given_name'),
'last_name' => $user->offsetGet('family_name'),
'avatar' => $user->getAvatar(),
]
);
// Returning response
$token = $userFromDb->createToken('Laravel Sanctum Client')->plainTextToken;
$response = ['token' => $token, 'message' => 'Google Login/Signup Successful'];
return response($response, 200);
}
I have solved it, after some digging I found out Laravel-Socialite has the functionality to log in users using their token built-in:
Quoting Socialite documentation:
If you already have a valid access token for a user, you can retrieve their details using Socialite's userFromToken method.
const { google } = require('googleapis')
const privatekey = require('./a.json')
const scopes = ['https://www.googleapis.com/auth/chat.bot'];
const a = async () => {
try {
const jwtClient = new google.auth.JWT(
privatekey.client_email,
null,
privatekey.private_key,
scopes,
'adminEmail#org.com'
);
await jwtClient.authorize();
const chat = google.chat({ version: 'v1', auth: jwtClient });
const res = await chat.spaces.messages.get({name:'spaces/XXX/messages/XX.XX'})
console.log(res)
}
catch(e) {
console.log(e)
}
}
a()
Error: Request contains an invalid argument
I am unable to find the invalid argument
Thanks in advance
Many Hangouts API request require the usage of a service account
You can consult in the documentation which type of requests are affected
For the requests requiring the usage of a service account - it is meant that the service account acts on its own behalf
Impersonation means that the service account acts on behalf of another user
Thus, impersonation is not allowed for requests that need to be carried out by a service account
Also mind that https://www.googleapis.com/auth/chat.bot is the scope to be used by the service account without domain-wide delegation
Users or impersonated service accounts need to use the scope https://www.googleapis.com/auth/chat instead - see also here
Last but not least, chat bots are not allowed to delete messages of other users
In the Single Sign-On for Teams
I have the call microsoftTeams.authentication.getAuthToken(authTokenRequest); working; that is, it successfully returns a token resolving to my Azure Active Directory (AAD) successfully. All good. Surprisingly easy. JWT returns with correct audience and scopes (as I have set in my tenant's AAD)
However what I get back when I decode the JWT this seems to just be an Authentication Token, not an Access Token.
Looking at the sample at Task Meow/teams.auth.service.js Does not seem to show how to swap the Auth for the Access Token.
I assume the code will look something like the method getToken() ... but since I have already spent 10+ working days on auth (old ADAL OH MY GOODNESS WAS THIS HORRIBLE) ...
Question:
I was wondering if there are any other good samples of MicrosoftTeams.js Authenticate / Auth Token / MSAL Access token out there?
Anyway, I did solve my problem by the following
Follow TaskMeow example through the abstractions ofauth.service.js > sso.auth.service.js > teams.auth.service.js
As I wanted additional AAD scopes (Files.ReadWrite.All to access the Sharepoint Online files in Teams and Groups.ReadWrite.All - to add Tabs) my getToken() method in teams.auth.service.js is something like the following:
getToken() {
if (!this.getTokenPromise) {
this.getTokenPromise = new Promise((resolve, reject) => {
this.ensureLoginHint().then(() => {
this.authContext.acquireToken(
'https://graph.microsoft.com',
(reason, token, error) => {
if (!error) {
resolve(token);
} else {
reject({ error, reason });
}
}
);
});
});
}
return this.getTokenPromise;
}
Editorial Comment:
Authentication in Microsoft Teams is too difficult
There seems to be many "approaches" in the documentation
The present "SSO" flow still has flaws, and is in "Developer Preview"
If you are an SPA developer it is just too difficult. I am (obviously) not an expert on Authentication -- so current "recipes" are imperative.
This is especially the case if you want more than the default "scopes" as described in Single Sign-on ... and most of the "good stuff" in Microsoft Graph is outside of these default scopes.
Also, this snippet may help.
If you follow the recommended Taskmeow in your Microsoft Teams app, you will get a quick appearance of the Redirect URI (aka /tab/silent-start)
To solve this, adal.js caches the user and access token.
So you can add a check in login()
login() {
if (!this.loginPromise) {
this.loginPromise = new Promise((resolve, reject) => {
this.ensureLoginHint().then(() => {
// Start the login flow
let cachedUser = this.authContext.getCachedUser();
let currentIdToken = this.authContext.getCachedToken(this.applicationConfig.clientId);
if (cachedUser && currentIdToken) {
resolve(this.getUser());
} else {
microsoftTeams.authentication.authenticate({
url: `${window.location.origin}/silent-start.html`,
width: 600,
height: 535,
successCallback: result => {
resolve(this.getUser());
},
failureCallback: reason => {
reject(reason);
}
});
}
});
});
}
return this.loginPromise;
}
I am getting invalid signature while using jwt.io to validate my azure ad access token. My id token, however, validates just fine!
I have seen and tried the solutions suggested in
Invalid signature while validating Azure ad access token
and
https://nicksnettravels.builttoroam.com/post/2017/01/24/Verifying-Azure-Active-Directory-JWT-Tokens.aspx
but neither works for my access token.
The access and Id token is generated via Adal.js:
var endpoints = {
"https://graph.windows.net": "https://graph.windows.net"
};
var configOptions = {
tenant: "<ad>.onmicrosoft.com", // Optional by default, it sends common
clientId: "<app ID from azure portal>",
postLogoutRedirectUri: window.location.origin,
endpoints: endpoints,
}
window.authContext = new AuthenticationContext(configOptions);
Why can I validate my ID token, but not my access token?
Please refer to thread : https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/609
but if look at the Jwt.Header you will see a 'nonce'. This means you need special processing. Normal processing will fail.
So if nonce includes in access token , validate signature with JWT.io or JwtSecurityToken won't success .
If anyone else has invalid signature errors, you should check this comment : https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/521#issuecomment-577400515
Solved the issue for my configuration.
Essentially, if you are getting access tokens to access your own resource server and not the Graph API, your scopes parameter should be [CLIENT_ID]/.default (and if you are using the access token to access the Graph API, you don't need to validate the token yourself)
Thanks to Nan Yu I managed to get token that can be validated by any public jwt validator like jwt.io
(couldn't put my comment in the comments section under Nan Yu's answer because its too long).
So as I understand the point from the discussion mentioned by Nan Yu that by default Azure AD generates tokens for Microsoft Graph and these tokens use special signing mechanism so that it is not possible to validate signature using public validators (except jwt.ms Microsoft's validator which most probably knows what mysterious special handling means :) ).
To get access token not for Microsoft Graph that can be validated using public validators I had to:
Remove any Microsoft Graph related scopes (by default I had only one scope configured User.Read so removed it in appConfig > API permissions)
create a custom scope for your application (appConfig > Expose an API > Add scope ...) this scope will look like api://{application-id}/scope-name
add just created scope in the application API permissions (appConfig > API permissions > Add api permission > My APIs > select your application > Delegated Permissions > Check your scope > Add permission)
then use this scope in your openid client scopes, in my case I have: openid offline_access {application-id}/scope-name
Note that in the openid client config newly created scope is used without api:// prefix (offline_access I have to enable refresh_token can be ignored if refresh token mechanism is not used)
Well thanks to #Antoine I fix my code. Here I will let my personal vue.js plugin that is working for everybody else reference:
import { PublicClientApplication } from '#azure/msal-browser'
import { Notify } from 'quasar'
export class MsalService {
_msal = null
_store = null
_loginRequest = null
constructor (appConfig, store) {
this._store = store
this._msal = new PublicClientApplication(
{
auth: {
clientId: appConfig.auth.clientId,
authority: appConfig.auth.authority
},
cache: {
cacheLocation: 'localStorage'
}
})
this._loginRequest = {
scopes: [`${appConfig.auth.clientId}/.default`]
}
}
async handleResponse (response) {
await this._store.dispatch('auth/setResponse', response)
const accounts = this._msal.getAllAccounts()
await this._store.dispatch('auth/setAccounts', accounts)
if (accounts.length > 0) {
this._msal.setActiveAccount(accounts[0])
this._msal.acquireTokenSilent(this._loginRequest).then(async (accessTokenResponse) => {
// Acquire token silent success
// Call API with token
// let accessToken = accessTokenResponse.accessToken;
await this._store.dispatch('auth/setResponse', accessTokenResponse)
}).catch((error) => {
Notify.create({
message: JSON.stringify(error),
color: 'red'
})
// Acquire token silent failure, and send an interactive request
if (error.errorMessage.indexOf('interaction_required') !== -1) {
this._msal.acquireTokenPopup(this._loginRequest).then(async (accessTokenResponse) => {
// Acquire token interactive success
await this._store.dispatch('auth/setResponse', accessTokenResponse)
}).catch((error) => {
// Acquire token interactive failure
Notify.create({
message: JSON.stringify(error),
color: 'red'
})
})
}
})
}
}
async login () {
// this._msal.handleRedirectPromise().then((res) => this.handleResponse(res))
// await this._msal.loginRedirect(this._loginRequest)
await this._msal.loginPopup(this._loginRequest).then((resp) => this.handleResponse(resp))
}
async logout () {
await this._store.dispatch('auth/setAccounts', [])
await this._msal.logout()
}
}
// "async" is optional;
// more info on params: https://quasar.dev/quasar-cli/boot-files
export default ({
app,
store,
Vue
}) => {
const msalInstance = new MsalService(
app.appConfig, store
)
Vue.prototype.$msal = msalInstance
app.msal = msalInstance
}
PD: using quasar framework
If you are using msal.js library with react, add this to your auth configuration.
scopes: [`${clientId}/.default`]
Editing scopes fixed issue for me