Error: Argument error: username and password are required unless use_unauthenticated is set - ibm-watson

I'm attempting to use STT service with the iam apikey.
If I set the IAM credentials like the documentation shows (below) I get the error: username and password are required unless use_unauthenticated is set
let speech_to_text = new SpeechToTextV1({
iam_apikey: STT_credentials.apikey,
iam_url: STT_credentials.url
});
If I pass the use_anauthenticated value I get a 401 response:
let speech_to_text = new SpeechToTextV1({
iam_apikey: STT_credentials.apikey,
iam_url: STT_credentials.url,
use_unauthenticated: true
});
response:
Error! Code:401 Type: undefined Message: Unauthorized
If I look at the file in the error:
/Users/jward/Desktop/speech_lab_assets/STT/node_mod
ules/watson-developer-cloud/lib/base_service.js:73:13
I see that it will throw an error if there is no username/password param:
if (!options.use_unauthenticated) {
if (!options.username || !options.password) {
throw new Error('Argument error: username and password are required unless use_unauthenticated is set');
}
How am I supposed to use IAM if the username/password is a requirement of the watson-developer-cloud tooling? Is this an issue with the node module or am I doing something wrong?
I am using watson-developer-cloud#2.42.0

The endpoint is specified as url and not iam_url as you have it.
This works for me -
const STTV1 = require('watson-developer-cloud/speech-to-text/v1');
let sttService = new STTV1({
url: url,
iam_apikey = apikey
});

Related

inpage.js:1 MetaMask - RPC Error: Invalid parameters: must provide an Ethereum address

I'm facing an issue when I try to transfer ether from one account to another account. For now I'm using ganache locally and import ganache wallets into metamask.
`
let unformatEther = ethers.utils.parseEther("1");
const account = await window.ethereum.request({
method: "eth_accounts",
});
console.log(account[0])
let sendEth = await window.ethereum.request({
method: "eth_sendTransaction",
params: [
{
form: account[0],
to: "0x2972E7f02dA9f5078D37E126C6bEEFA883B3819C",
gasPrice: "0x09184e72a000",
gas: "0x2710",
value: unformatEther._hex,
},
],
});
`
There I'm getting the error into my console that is
I search everything on google, read metamask documentation here
Also add address manually on from key but not resolved this one.
you have typo here
form: account[0],
should be
from: account[0],

How to update the password of a Supabase user on a NextJs project?

I'm facing an issue updating a password for a supabase user on a BlitzJs (NextJs) project.
Basically, I have a reset password method that works perfectly. First I send an email with a reset link, that opens a page where the user can update his password like so:
const { error, data } = await supabase.auth.api.updateUser(token, { password: password.trim() })
the token being the one in the url, provided in the email link.
So far, so good, but when I try to update the password for a logged in user, using the exact same method supabase.auth.api.updateUser, it fails to find the user;
The difference is the token is the session.access_token
So I've tried to use the supabase.auth.api.updateUserById method, but it gives me another error: { message: 'User not allowed', status: 401 }
Any ideas? I feel the supabase docs about this is not very clear, and probably outdated as it doesn't show all the available methods :/
Update password for authenticated user.
const { user, error } = await supabase.auth.update({password: 'new password'})
For more informations check: Supabase references

Getting Error while uploading file to S3 with Federated Identity using aws-amplify in React

While the user with Facebook federated Identity trying to upload Image, I'm getting an error: AWSS3Provider - error uploading Error: "Request failed with status code 403"
Status Code: 403 Forbidden
Noticed that URL in request, while user authenticated with Federated Identity (Facebook), looks:
Request URL: https://my-gallery-api-dev-photorepos3bucket-XXXX.s3.us-east-2.amazonaws.com/private/undefined/1587639369473-image.jpg?x-id=PutObject
The folder where the uploaded image will be placed is 'undefined' instead of being a valid user identity like for users authenticated with from AWS UserPool, see:
Request URL: https://my-gallery-api-dev-photorepos3bucket-XXXX.s3.us-east-2.amazonaws.com/private/us-east-2%3Aa2991437-264a-4652-a239-XXXXXXXXXXXX/1587636945392-image.jpg?x-id=PutObject
For Authentication and upload I'am using React aws dependency "aws-amplify": "^3.0.8"
Facebook Authentication (Facebook Button):
async handleResponse(data) {
console.log("FB Response data:", data);
const { userID, accessToken: token, expiresIn } = data;
const expires_at = expiresIn * 1000 + new Date().getTime();
const user = { userID };
this.setState({ isLoading: true });
console.log("User:", user);
try {
const response = await Auth.federatedSignIn(
"facebook",
{ token, expires_at },
user
);
this.setState({ isLoading: false });
console.log("federatedSignIn Response:", response);
this.props.onLogin(response);
} catch (e) {
this.setState({ isLoading: false })
console.log("federatedSignIn Exception:", e);
alert(e.message);
this.handleError(e);
}
}
Uploading:
import { Storage } from "aws-amplify";
export async function s3Upload(file) {
const filename = `${Date.now()}-${file.name}`;
const stored = await Storage.vault.put(filename, file, {
contentType: file.type
});
return stored.key;
}
const attachment = this.file
? await s3Upload(this.file)
: null;
I'm understand that rejection by S3 with 403, because of the IAM role, I have for authenticated users:
# IAM role used for authenticated users
CognitoAuthRole:
Type: AWS::IAM::Role
Properties:
Path: /
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Principal:
Federated: 'cognito-identity.amazonaws.com'
Action:
- 'sts:AssumeRoleWithWebIdentity'
Condition:
StringEquals:
'cognito-identity.amazonaws.com:aud':
Ref: CognitoIdentityPool
'ForAnyValue:StringLike':
'cognito-identity.amazonaws.com:amr': authenticated
Policies:
- PolicyName: 'CognitoAuthorizedPolicy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Action:
- 'mobileanalytics:PutEvents'
- 'cognito-sync:*'
- 'cognito-identity:*'
Resource: '*'
# Allow users to invoke our API
- Effect: 'Allow'
Action:
- 'execute-api:Invoke'
Resource:
Fn::Join:
- ''
-
- 'arn:aws:execute-api:'
- Ref: AWS::Region
- ':'
- Ref: AWS::AccountId
- ':'
- Ref: ApiGatewayRestApi
- '/*'
# Allow users to upload attachments to their
# folder inside our S3 bucket
- Effect: 'Allow'
Action:
- 's3:*'
Resource:
- Fn::Join:
- ''
-
- Fn::GetAtt: [PhotoRepoS3Bucket, Arn]
- '/private/**${cognito-identity.amazonaws.com:sub}/***'
- Fn::Join:
- ''
-
- Fn::GetAtt: [PhotoRepoS3Bucket, Arn]
- '/private/**${cognito-identity.amazonaws.com:sub}**'
It works fine for users registered in AWS User Pool (Email, Password), but for federated users, there is no record in AWS User Pool only in Federated Identities, so there will be no cognito-identity.amazonaws.com:sub found for those users and directory 'undefined' not falling in role allowance for user identified with Federated Identity.
Please advise:
1. Where/how to fix this 'undefined' in URL?
2. Also, I would like, probably, to replace thouse Id's in upload URL to genereted user Id's from user database I'm going to add in near future. How to fix IAM Role to use custom Id's?
I stumbled with the same problem when doing Serverless Stack tutorial
This error arises when you do the Extra Credit > React > Facebook Login with Cognito using AWS Amplify, as you have notice uploading a file fails if you're authenticated with Facebook.
The error comes up when sending a PUT to:
https://<bucket>.s3.amazonaws.com/private/<identity-id>/<file>
...the <identity-id> is undefined so the PUT fails.
You can track down the source of this undefinition if you log what you get when running the login commands. For example, when you login using your email and password, if you do:
await Auth.signIn(fields.email, fields.password);
const currCreds = await Auth.currentCredentials();
console.log('currCreds', currCreds);
...you can see that identityId is set correctly.
On the other hand when you login with Facebook through Auth.federatedSignIn if you log the response you don't get identityId. Note: In the case you've previously logged in using email and password, it will remain the same, so this misconfiguration will also make uploading fail.
The workaround I've used is adding a simple lambda which returns the identityId for the logged in user, so once the user logs in with facebook, we ask for it and we can send the PUT to the correct url using AWS.S3().putObject
In the case you want to try this out, take into account that you should host your React app in https as Facebook doesn't allow http domains. You can set this adding HTTPS=true to your React .env file.
You can check my repos as example:
API
Frontend

Json Web Token - jose4j - SyntaxError: Unexpected token e in JSON at position 0

I have a controller which tries to get a token.
I got this error in postman when I execute it in the view PRETTY
Unexpected 'e'
But if I go to the view RAW I can see the token like this.
eyJraWQiOiIxIiwiYWxnIjoiUlMyNTYifQ.eyJpc3MiOiJJc3N1ZXIiLCJhdWQiOiJBdWRpZW5jZSIsImV4cCI6MTQ3NTQ1OTMyNiwianRpIjoiTmF3d000bDVGRmFRZ0dBQkwzS3N5USIsImlhdCI6MTQ3NTQ1ODcyNiwibmJmIjoxNDc1NDU4NjA2LCJzdWIiOiJzdWJqZWN0IiwiZW1haWwiOiJtYWlsQGV4YW1wbGUuY29tIn0.f97SFDaAjUyUDK_UQgwgnCTewd0yw6tWK6DFLzpALFq177f1QMTYPbVdiIG1ViJ0FNJ6fUCleCd8BmrToUn25VSmRv799dtcz-xaN1kOgw90NQ00kPUhnDXG01-7hImkHfbmZZWORukP2yPK1sHWzpdjg9fJOvRZpZ6ZWli4HeuYRJqsFOv7PvwmGH9JnfRTf_2tboL-oAYBpT367eh60TggrvMgmrO_Taj5M7qGG0GpbwuVh_HTAkaKv7T2WmuZ2JPANhe5JvY_DDaqChtwd0IPREAhK3Xr-nTOIuwbQ0Y1hhOGfvDmikQj6DXnCERYixP6eR1dhC8n3bKvXyaVmA
This is the code of my controller.
#Path("/demo")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response testMethod() throws JSONException, IOException {
RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
rsaJsonWebKey.setKeyId("k1");
JwtClaims claims = new JwtClaims();
claims.setIssuer("Issuer");
claims.setAudience("Audience");
claims.setExpirationTimeMinutesInTheFuture(10);
claims.setGeneratedJwtId();
claims.setIssuedAtToNow();
claims.setNotBeforeMinutesInThePast(2);
claims.setSubject("subject");
claims.setClaim("email","mail#example.com");
JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(rsaJsonWebKey.getPrivateKey());
jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
String jwt = jws.getCompactSerialization();
if(jwt == null){
return Response.status(204).entity(jwt).build();
}
return Response.status(200).entity(jwt).build();
}
I ignore the error in postman but I get the same error when try to execute it in Chrome.
I try to call my RESTful controller with angular like this, but I always get into the onError method with the message within the response parameter.
angular.min.js:118 SyntaxError: Unexpected token e in JSON at position 0
This is the code in angular
app.service('TokenService', function($http){
this.getToken = function(){
function onSuccess(response){
console.log('got it');
}
function onError(response){
console.log('fail');
}
return $http({
method : 'GET',
url : 'http:localhost:8080/rest/demo',
header: {'Content-Type' : 'application/json'}
}).then(onSuccess, onError);
}
}
My reference of the code for the token is from here with Jose4j
UPDATE
I solved this. I still think the way I did it initially it should work also, but I don't still understand why I get the error.
I created a pojo named Token with a property token as String then I changed this
return Response.status(200).entity(jwt).build();
to this:
Token token = new Token();
token.setToken(jwt);
return Response.status(200).entity(token).build();
This is my workaround to return a real json object.
I know it's much too late now, but I've faced the same problem and got it fixed with your solution, so Thanks.
Just for the sake of whoever came across this issue later. In my case I do it like this.
HashMap<String, String> credential = new HashMap<>();
credential.put("token", jwtToken);
apiResp = ResponseEntity.ok(jwtToken);
Btw, I also seem to figured out the problem which is Angular might expect that response from server is JSON object by default then parse it to JavaScript object for us.
So we got our error because we return string as a response entity and it can't parse string to an object. That's why putting the token in POJO solved it.
The other way around is setting return type from client-side like this.
login(username: string, password: string): Observable<any> {
let body = {username, password};
let res = this.http.post(
`${API.AUTHENTICATION}`, body, {
responseType: 'text'
});
return res;
}
Now, JS will know that the response is of string type and it won't try to parse it to an object anymore.

angular ngressource issue TypeError: Cannot read property 'get' of undefined

I'm new to angular and I'm trying to to create a service to register and login users using a spring rest controller, below is the Angular code to retrive Json data
.factory('accountService', function($resource) {
var service = {};
service.register = function(account, success, failure) {
var Account = $resource("/mywebapp/rest/account");
Account.save({}, account, success, failure);
};
service.userExists = function(account, success, failure) {
var Account = $resource("/mywebapp/rest/account");
var data = account.get({email:'email'}, function() {
var accounts = data.accounts;
if(accounts.length !== 0) {
success(accounts[0]);
} else {
failure();
}
},
failure);
};
return service;
})
the problem is that i'm getting two type of error message in chrome and FireFox when trying to connect (service.userExists):
TypeError: Cannot read property 'get' of undefined
at Object.service.userExists (http://localhost:8080/mywebapp/resources/js/account.js:42:27)
at h.$scope.login (http://localhost:8080/mywebapp/resources/js/account.js:56:24)
at http://localhost:8080/mywebapp/resources/lib/angular/angular.js:178:68
at f (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:195:177)
at h.$eval (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:113:32)
at h.$apply (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:113:310)
at HTMLFormElement.<anonymous> (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:195:229)
at http://localhost:8080/mywebapp/resources/lib/angular/angular.js:31:225
at r (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:7:290)
at HTMLFormElement.c (http://localhost:8080/mywebapp/resources/lib/angular/angular.js:31:207)
and in firefox:
"Error: account is undefined
service.userExists#http://localhost:8080/mywebapp/resources/js/account.js:42:13
$scope.login#http://localhost:8080/mywebapp/resources/js/account.js:56:1
gb.prototype.functionCall/<#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:178:66
jc[c]</<.compile/</</f#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:195:177
Yd/this.$get</h.prototype.$eval#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:113:28
Yd/this.$get</h.prototype.$apply#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:113:305
jc[c]</<.compile/</<#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:195:227
ne/c/<#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:31:223
r#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:7:288
ne/c#http://localhost:8080/mywebapp/resources/lib/angular/angular.js:31:207
i'm also getting this error when trying to register a new account:
[HTTP/1.1 415 Type de Support Non Supporté 98ms]
Would you please help me.
ng-resource seems to never receive the account parameter which means the get request is not returning the account. Check the network tools to see what the userExists request is returning from the server.
The message your are receiving for the register could be a hint, I would say it means the API doesn't support your type of client, maybe you're using an old browser or a the server API is very old.

Resources