Invalid access to resource - Speech To Text API - speech-to-text

I am getting the following error when I try to open a websocket.
Invalid access to resource -
/speech-to-text/api/v1/recognize?model=en-US_BroadbandModel&watson-token=
User access not Authorized.
Gateway Error Code : ERCD04-NOAUTHHDR-PLTFRMREQ
Unable to communicate with Watson.
Request URL :
/speech-to-text/api/v1/recognize?model=en-US_BroadbandModel&watson-token=
Error Id : stream-dp01-47767984
Date-Time : 2016-03-26T16:05:04-04:00
I have no idea what this error means. I am using this client code in Golang to open the websocket.
// Simplified code to get token
baseURL, _ := url.Parse("https://stream.watsonplatform.net/authorization/api/v1/token")
params := url.Values{}
params.Add("url", "https://stream.watsonplatform.net/speech-to-text/api")
baseURL.RawQuery = params.Encode()
req, _ := http.NewRequest(http.MethodGet, baseURL.String(), nil)
req.SetBasicAuth(IBMUsername, IBMPassword)
resp, _ := http.DefaultClient.Do(req)
token, _ := ioutil.ReadAll(resp.Body)
// Simplified code to open websocket
baseURL, _ := url.Parse("wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize")
params := url.Values{}
params.Add("watson-token", token)
params.Add("model", "en-US_BroadbandModel")
baseURL.RawQuery = params.Encode()
ws, _ := websocket.Dial(baseURL.String(), "", "http://localhost:8000")

The service is experiencing some issues right now; the team is aware and working on it. Sorry for the trouble, please try again in a little while.

Related

How to specify x509 certificate for Azure SDK in Golang

I am trying to connect to use the Azure SDK for Golang to download files from a container online to my device and am using the connection string provided from azure to connect. For context this is running on a version of embedded Linux
I have two questions, first how do I pass a specific certificate to the azure SDK to use to connect, as currently when I connect, I get this issue
Get "https://transaction.blob.core.windows.net/transactions?comp=list&restype=container": x509: certificate signed by unknown authority
or failing that how do I generate the correct certificate to put it in /etc/ssl? Which I think is where go is looking for certificates as far as I understand.
Also second question what function from the azure sdk for go should I be using to download from a blob online if my folder structure looks like /transaction/my-libs/images/1.0.0/libimage.bin where transaction is my blob container.
func testConnection(){
Println("TESTING CONNECTION")
connStr := "..." // actual connection string hidden
serviceClient, err := azblob.NewServiceClientFromConnectionString(connStr, nil)
// crashes here <------------
//ctx := context.Background()
//container := serviceClient.NewContainerClient("transactions")
//
//_, err = container.Create(ctx, nil)
//
//blockBlob := container.NewBlockBlobClient("erebor-libraries")
//_, err = blockBlob.Download(ctx, nil)
//Open a buffer, reader, and then download!
downloadedData := &bytes.Buffer{}
reader := get.Body(RetryReaderOptions{}) // RetryReaderOptions has a lot of in-depth tuning abilities, but for the sake of simplicity, we'll omit those here.
_, err = downloadedData.ReadFrom(reader)
err = reader.Close()
if data != downloadedData.String() {
err := errors.New("downloaded data doesn't match uploaded data")
if err != nil {
return
}
}
pager := container.ListBlobsFlat(nil)
for pager.NextPage(ctx) {
resp := pager.PageResponse()
for _, v := range resp.ContainerListBlobFlatSegmentResult.Segment.BlobItems {
fmt.Println(*v.Name)
}
}
• You can use the following Azure SDK for Go command for passing a specific certificate to the Azure SDK to connect to other Azure resources by creating a service principal for it: -
‘ type ClientCertificateConfig struct {
ClientID string
CertificatePath string
CertificatePassword string
TenantID string
AuxTenants []string
AADEndpoint string
Resource string
} ‘
For more information on the creation of the client certificate and its usage, please refer to the documentation link below for more details: -
https://pkg.go.dev/github.com/Azure/go-autorest/autorest/azure/auth#ClientCertificateConfig
Also, even if your folder structure is ‘/transaction/my-libs/images/1.0.0/libimage.bin’, but the blob URL is unique with folder hierarchy mentioned in the blob URL, thus when connecting to the Azure storage account to download the blob, mention the URL in single inverted comma notation for the blob path to be specific.
Please refer to the sample code below for downloading the blobs through Azure SDK for Go: -
https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/storage/azblob#example-package
https://pkg.go.dev/github.com/Azure/azure-storage-blob-go/azblob#pkg-examples

unable to create session: control: unable to connect to initial hosts: Invalid Cosmos DB account or key

I have been trying to connect to cosmos cassandra db using gocql.
func GetSession(cosmosCassandraContactPoint, cosmosCassandraPort, cosmosCassandraUser, cosmosCassandraPassword string) *gocql.Session {
clusterConfig := gocql.NewCluster(cosmosCassandraContactPoint)
port, err := strconv.Atoi(cosmosCassandraPort)
if err != nil {
log.Fatal(err)
}
clusterConfig.Port = port
clusterConfig.ProtoVersion = 4
clusterConfig.Authenticator = gocql.PasswordAuthenticator{Username: cosmosCassandraUser, Password: cosmosCassandraPassword}
clusterConfig.SslOpts = &gocql.SslOptions{Config: &tls.Config{MinVersion: tls.VersionTLS12}}
clusterConfig.ConnectTimeout = 10 * time.Second
clusterConfig.Timeout = 10 * time.Second
clusterConfig.DisableInitialHostLookup = true
// uncomment if you want to track time taken for individual queries
//clusterConfig.QueryObserver = timer{}
// uncomment if you want to track time taken for each connection to Cassandra
//clusterConfig.ConnectObserver = timer{}
session, err := clusterConfig.CreateSession()
if err != nil {
log.Fatal("Failed to connect to Azure Cosmos DB", err)
}
return session
}
I have been getting the following error :
unable to create session: control: unable to connect to initial hosts: Invalid Cosmos DB account or key
Not sure what the issue here is.
It doesn't look like you've configured the necessary options for the SSL/TLS configuration, particularly the certificates.
I haven't connected to a Cosmos DB before so I'm not sure of the certs/keys required but I previously helped someone configure the gocql driver with the right TLS settings in this post -- https://community.datastax.com/questions/3753/.
In their environment, they needed to provide the certs and keys to connect as follows:
certPath, _ := filepath.Abs("/home/erick/astra-bundle/cert")
keyPath, _ := filepath.Abs("/home/erick/astra-bundle/key")
caPath, _ := filepath.Abs("/home/erick/astra-bundle/ca.crt")
cert, _ := tls.LoadX509KeyPair(certPath, keyPath)
caCert, _ := ioutil.ReadFile(caPath)
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
cluster.SslOpts = &gocql.SslOptions{
Config: tlsConfig,
EnableHostVerification: false,
}
Details are in the post above. I hope this helps. Cheers!
It seems your account or key is wrong.
First,please make sure your API is CASSANDRA API.You can check at here.
Second,please make sure your account or key is right.
COSMOSDB_CASSANDRA_CONTACT_POINT=<value for "CONTACT POINT">
COSMOSDB_CASSANDRA_PORT=<value for "PORT">
COSMOSDB_CASSANDRA_USER=<value for "USERNAME">
COSMOSDB_CASSANDRA_PASSWORD=<value for "PRIMARY PASSWORD">
You can find them here:
More details,you can refer to this documentation.
Hope this can help you.

Authentication successful but unable to retrieve and list Azure AD Users using Azure Golang SDK

I am trying to use Azure Golang SDK to pull the list of Azure AD users.
Few things to Note:
1. Authentication is successful. "Authorization successful." is displayed when I use below code to fetch bearer token for Azure SPN.
This is pretty much vanilla code picked from Azure-Go-SDK repo.
//GetGraphAuthorizer gets an OAuthTokenAuthorizer for graphrbac API.
func GetGraphAuthorizer(fs auth.FileSettings) (autorest.Authorizer, error) {
if graphAuthorizer != nil {
return graphAuthorizer, nil
}
var a autorest.Authorizer
var err error
a, err = getAuthorizerForResource(grantType(), Environment().GraphEndpoint, fs)
if err == nil {
// cache
graphAuthorizer = a
fmt.Println("Authorization successful.")
} else {
graphAuthorizer = nil
fmt.Println ("Authorization failed.")
}
return graphAuthorizer, err
}
Defined a wrapper on around GetGraphAuthorizer function to instantiate userClient object:
func getADUserClient(fs auth.FileSettings) graphrbac.UsersClient {
userClient := graphrbac.NewUsersClient(azure.GetTenantId(fs))
a, _ := azure.GetGraphAuthorizer(fs)
userClient.Authorizer = a
userClient.AddToUserAgent(azure.UserAgent())
return userClient
}
Then I use the token to list users in Azure AD in below function:
adUserClient := getADUserClient(fs)
// if auth failed, then it should've displayed the failure message here but prints "Authorization successful instead"
for list, err := adUserClient.ListComplete(context.Background(), ""); list.NotDone(); err = list.Next() {
if err != nil {
fmt.Print("got error while traversing User list: ", err)
}
i := list.Value()
fmt.Println(*i.DisplayName)
fmt.Println(*i.GivenName)
}
No output what so ever!!
FYI:- I have users in Azure tenant.
I have granted SPN access to Graph API.
Any help is appreciated.
Not 100% sure but for some reason I had to grant Azure SPN "Delegated" permission to:
Directory.ReadWrite.All
Groups.ReadWrite.All
Surprisingly, Once the program listed users, I removed above "Delegated" permissions off SPN and just left the Application permissions and it continues to work!

How to get authenticate with the squareup using backend golang?

In sqaureup application Aplication_name in oauth option there is a redirect url Which will redirect a given url with the QueryString code. While I'm hitting https://connect.squareup.com/oauth2/authorize?client_id=YOUR_CLIENT_ID this url in the browser then it will redirect me to a given url in oauth with attached code. And then to take a access_token you have to give a POST request to given url https://connect.squareup.com/oauth2/token with the body
{
"client_id": "YOUR_APPLICATION_ID",
"client_secret": "YOUR_APPLICATION_SECRET",
"code": "M-Q7k-N0Emx_3cBqwbVLTQ",
"redirect_uri": "YOUR_REDIRECT_URI"
}
I do it same and send By method POST to this url with json data but it will gives me the error:-
{
"message": "Not Authorized",
"type": "service.not_authorized"
}
The Golang Code I'm using for this is :-
func Token(c *gin.Context) {
code := c.Query("code") // code be something like:-sq0cgp-wLVQt5HOLfug6xiVdmCDCf
splitCode := strings.Split(code, "-")
token := models.PostToken{
ClientID: "YOUR_APPLICATION_ID",
ClientSecret: "YOUR_APPLICATION_SECRET",
Code: splitCode[1],
RedirectUri: c.Request.Host + c.Request.URL.RequestURI(),
}
bindData, err := json.Marshal(token)
if err != nil {
panic(err)
}
var jsonStr = []byte(string(bindData))
url := "https://connect.squareup.com/oauth2/token"
req, err := http.Post(url, "application/json", bytes.NewBuffer(jsonStr))
fmt.Println(req, err)
}
Models struct:-
type PostToken struct {
ClientID string `json:"client_id" bson:"client_id"`
ClientSecret string `json:"client_secret" bson:"client_secret"`
Code string `json:"code" bson:"code"`
RedirectUri string `json:"redirect_uri" bson:"redirect_uri"`
}
You have to do some points I mentioned:-
First check your application Id.
In second parameter ClientSecret you have to use Oauth Application Secret key Which you will got from the application dashboard -> Oauth option.
In Code you don't have send the split code send simple string code value which your getting in the variable name code.
Fourth parameter is optional as the documentation says here.
Then you will got what you want :D.

ResourceExhausted in Google Speech API

this is my first post on StackOverflow. I get ResourceExhausted with Google Speech API - LongRunningRecognizeResponse. It says "e.g. check quota", but I'm not sure what it means exactly. How do I check quota and make necessary setups?
func sendRequestWithUri(uri string)
(*speechpb.LongRunningRecognizeResponse, error) {
log.Printf("Uri: %s", uri)
ctx := context.Background()
client, err := speech.NewClient(ctx)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
// Create Request with config
req := &speechpb.LongRunningRecognizeRequest{
Config: &speechpb.RecognitionConfig{
Encoding: speechpb.RecognitionConfig_FLAC,
SampleRateHertz: 44100,
LanguageCode: "en-US",
},
Audio: &speechpb.RecognitionAudio{
AudioSource: &speechpb.RecognitionAudio_Uri{
Uri: uri,
},
},
}
log.Printf("Created request: %s", req)
op, err := client.LongRunningRecognize(ctx, req)
if err != nil {
return nil, err
}
return op.Wait(ctx)
}
The code takes the URL for a FLAC file uploaded on Google Cloud Storage. After attempts to try with files in different lengths, I always receive:
rpc error: code = ResourceExhausted desc = Resource has been exhausted (e.g. check quota).
exit status 1
Then I opened GCP console, and simply enabled Speech API on one of the projects, where I want to work with Speech API. On a local machine (macOS, bash), I have selected the target project via gcloud gcloud config configurations create myproject and gcloud auth login. It looks like project config is successfully created:
$ gcloud config list
[core]
account = mygmail
disable_usage_reporting = False
project = myproject
Your active configuration is: [myproject]
After enable and setup, I still get the same ResourceExhausted.
Do I miss anything? Thanks.

Resources