I was using Firebase SMS auth, generate a JWT, and use the Firebase auth token as the user token in SupaBase:
Supabase.instance.client.auth.setAuth(theCustomJWTtoken);
In the 1.x version of the supabase_flutter package setAuth has been removed, and the documentation is not helping me figure out how I can continue to use custom JWTs in Flutter.
Any ideas (preferably with code)?
final supabase = SupabaseClient(supabaseUrl, supabaseKey, headers: {
'Authorization': 'Bearer $access_token',
});
This worked. Was posted on GitHub here:
Related
What is the best practice to post data to a server, currently my database is a PostgreSql.
I would be posting to a REST Api and I want to be safe, to post I was going to use a token to verify that they are from the app but then if someone decompiles the app they will see the verification token and could then post to the API
String token = esR3bJM9bPLJoLgTesR3bJM9bPLJoLgT;
String apiUserLikes = current_server_address + "/api/user-likes/?token=$token";
final response = await http.post(
Uri.parse(apiUserLikes?token=$token),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'userID': '1234567969855478',
'UserDisplayName': 'John Jones',
'liked': 'true',
'dateLiked': '2022/12/05 00:00:00',
'eventLiked': 'Music concert at The stadium',
}),
);
What is the best way to protect users details and still post to the server
Thanks
You could never verify that the user is from the app because he can send the same request with just the command line. Even with authentication, it is still impossible to confirm. The only way to make it safe is to validate the data sent and add restriction against abuse like how many times per minute an IP/user could send data or how much could it send/download.
Instead of using static token you can use OAuth2 compliant security mechanism where token expires and new refresh token is generated/issued,
You can use firebase Auth or something like to make your App Compliant with OAuth.
For firebase Auth you can check the following link:
https://firebase.google.com/docs/auth/
I want to provide Microsoft auth in my flutter app along with Google and Facebook. I found documentation for Google and Facebook, but could not find any resource or document for Microsoft auth. Any help will be appreciable.
Sorry if this answer is late, it may help others who are facing the same issue.
I followed a simple technique to overcome Microsoft authentication, at the end you will receive the user mail ID, and other details as per permissions set while declaring the app.
There is a flutter package https://pub.dev/packages/flutter_web_auth
Before proceeding you need to register an application with the Azure Active Directory https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/CreateApplicationBlade/isMSAApp~/false
configure the flutter login method
final url = Uri.https('login.microsoftonline.com', '/your-tenant ID/oauth2/v2.0/authorize', {
'response_type': 'token',
'client_id': 'your Client ID',
'redirect_uri': redirectUrl,
'scope': 'https://graph.microsoft.com/openid',
});
// This method will return the authorization code which needs to exchanged for user details
final result = await FlutterWebAuth.authenticate(url: url.toString(), callbackUrlScheme: redirectUrl);
// Extract code from resulting url
you can get either access code or token based on security level. More explanation can be found at: https://learn.microsoft.com/en-us/azure/active-directory/develop/app-sign-in-flow
for my approach, I took tokens from the Azure AD and exchange with this API to get user details
final details = await http.get(Uri.parse("https://graph.microsoft.com/oidc/userinfo"),
headers: {
"Authorization" : "Bearer "+accessCode,
});
You can use these details to authenticate the user and enable functions.
In Azure AD you can define who can use the login mechanism such as organization or general.
Hope this helps.
I see some questions about this with solutions that seem to be deprecated in the Google APIs Node.js Client OAuth API (e.g., this and this).
There's no documentation I can see regarding using the refresh token to get a new access token (docs section). In an issue from early 2017, someone mentions getting off the oauth2Client.credentials property, but it looks like that's within a call to one of the other APIs wrapped in the package.
In my use case, I'm querying the Google My Business (GMB) API, which is not wrapped in there, but I'm using the OAuth piece of this package to authenticate and get my tokens.
My request to the GMB API (using the request-promise module), looks something like this:
function getLocations () {
return request({
method: 'POST',
uri: `${gmbApiRoot}/accounts/${acct}/locations:batchGet`,
headers: {
Authorization: `OAuth ${gmbAccessToken}`
}
})
.then(function (response) {
console.log(response);
})
.catch(function (err) {
// ...
});
}
I don't think I can pass the oauth2Client into the headers for authorization like in the issue response. Is there a way to directly request a new access_token given that I have my refresh token cached in my app?
Update: Solved! Thanks to Justin for the help. Here's what my working code is looking like:
oauth2Client.setCredentials({
refresh_token: storedRefreshToken
});
return oauth2Client.refreshAccessToken()
.then(function (res) {
if (!res.tokens && !res.credentials) {
throw Error('No access token returned.');
}
const tokens = res.tokens || res.credentials;
// Runs my project-level function to store the tokens.
return setTokens(tokens);
});
If you have an existing oauth2 client, all you need to do is call setCredentials:
oauth2client.setCredentials({
refresh_token: 'REFRESH_TOKEN_YALL'
});
On the next call that goes through the client, it will automatically detect there is no access token, notice the refresh token, and go snag a new access token along with it's expiration date. I outlined some docs and code around this in the issue you opened up on GitHub :P
https://github.com/google/google-api-nodejs-client/pull/1160/files
Hope this helps!
I wanted to add in my learning, to the community, in case it helps anyone out there struggling with this too. The above answers were correct, but I discovered one other attribute.
Namely, I was calling my credentials like this:
oAuth2Client.setCredentials(JSON.parse(authResults));
my authResults, is defined as this:
const authResults = fs.readFileSync(TOKEN_PATH);
This results in several fields being filled in to the results variable:
[
'access_token',
'refresh_token',
'scope',
'token_type',
'expiry_date'
]
Now here's the nuance...if the access_token AND the refresh_token are both given to the setCredentials call, the refresh-token is ignored. Changing to the above answer, where I send in only the refresh token:
oAuth2Client.setCredentials({ refresh_token: creds['refresh_token'] });
Worked like a champ! Hope this finds its way and helps someone else.
I'm using rest to authenticate users to Bluemix using an API key. I would also like to implement username and password authentication.
def auth(self):
self.log.debug('Authenticating to CloudFoundry')
url = self.info['authorization_endpoint'] + '/oauth/token'
headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'Accept': 'application/x-www-form-urlencoded;charset=utf-8',
'Authorization': 'Basic Y2Y6'
}
if self.api_auth:
data = 'grant_type=password&username=apikey&password={}'.format(self.api_key)
elif self.userpass_auth:
data = 'grant_type=password&username={}&password={}'.format(self.username, self.password)
else:
raise ValueError()
# send request ...
However, when I attempt to make the request using username and password, I receive the response:
{"error_description":"BMXLS0202E: You are using a federated user ID,
please use one time code to login with option --sso.","error":"unauthorized"}
So I can send my users to the SSO web page to get a token, but what REST api do I need to make when they have the SSO token? Or, do I use the same rest api as I am doing above, but instead provide a different parameter?
Why do you want to support username and password (I feel like I'm missing a piece of the puzzle here)?
I'd recommend using API tokens as a general good practice - some of the federated logins require a web-based token step which isn't great when working with integrations.
I'm developing a small react node application with JWT passport for authentication. I've tested all the endpoint through postman(by passing token with authorization header) and they are working properly.
This is the call im making from the front-end
export const getUsersDetails=()=>{
console.log( localStorage.getItem('jwtToken'));
return (dispatch) => {
return axios.get('http://localhost:3030/users',
{ headers: { 'Authorization': localStorage.getItem('jwtToken') } }
).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
I have enable CORS by using the the CORS module. this is the how the network calls looks like from the browser
the authorization header looks like
authorization:[object Object], eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Should this be like authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Is this the reason why im facing this issue? How to overcome this?
I was able to solve a similar issue on a MERN stack, by configuring axios globally in the react application, by adding Bearer and one space, in front of the token that is assigned globally.
axios.defaults.headers.common['Authorization'] =Bearer ${token};
initially, it was without Bearer and i kept getting a 401 status code.
axios.defaults.headers.common['Authorization'] = token;
When you want authorization in your app, it depends on how you have done your back end. If everything is ok trough postman, show how your headers in postman look when you have tasted. I use xsrf token and here is how my request header look:
{headers:
{"Access-Control-Allow-Headers" : "*",
"X-XSRF-TOKEN": this.$cookie.get('XSRF-TOKEN')}
}
Maybe you should just put "Access-Control-Allow-Headers" : "*"