CognitoUserSession is not valid because idToken is null - android-studio

I'm developing an app in Android Studio using amplify.
I need that unauthenticated users be able to read a type but need to signed in to create or modify it.
To achieve that I did the following:
I configured my auth to allow unauthenticated logins, following the steps in this documentation https://docs.amplify.aws/lib/auth/guest_access/q/platform/android
I configured my graphQL Api with Amazon cognito user pool as the default authorization type and IAM as additional authorization.
defined my type in schema.graphql this way
type Property #model\
#auth (
rules: [
{ allow: owner, operations: [create, update, delete, read]}
{ allow: private, operations: [create, read] }
{ allow: public, operations: [read], provider: iam }
]
)
#key(name: "propertiesByPrice" fields: ["modelType", "price"] queryField: "propertiesByPrice")
#key(name: "propertiesByLot" fields: ["modelType", "lot"] queryField: "propertiesByLot")
{
id: ID!,
imageUrl: String,
offerType: OfferType,
price: Int,
type: PropertyType,
rooms: Int,
bathrooms: Int,
parkingSpace: Int,
lot: Int,
state: String,
city: String,
neighborhood: String,
street: String,
number: String,
zipCode: String
modelType: String
}
So the guest users will be able to read the type Property but need to be signed in to create one and need to be the owner to modify it.
For tests I'm making the following query
Amplify.API.query(ModelQuery.list(Property::class.java),
{ result ->
Log.i(TAG, "listProperties: succeeded $result")
},
{ exception ->
Log.e(TAG, "listProperties: failed $exception")
})
I get the right response with signed in users but when I try to run it as guest i get the following error
W/CognitoUserSession: CognitoUserSession is not valid because idToken is null.
W/AWSMobileClient: signalTokensNotAvailable
Is there anything else I need to configure? Thanks in advance

Related

Openapi generator configuration for Azure B2C Authorization

My Angular client application is using MSAL in order to communicate with Azure B2C and retrieve the id token, refresh token and access token. These are in my localstorage after login.
I'm also using openapi generator to generate my services for my client application. The thing is, whenever I make a call to my backend, it is resulting as a 401.
The controller:
[Authorize]
[RequiredScope("example.read")]
[HttpGet(Name = "GetJobs")]
public async Task<ActionResult<IEnumerable<JobDTO>>> Index(int pageNumber, int pageSize, string? titleDesc, string? category)
{
var owner = CheckClaimMatch(ClaimTypes.NameIdentifier);
try
{
var result = await _jobModel.GetAllJobs(pageNumber, pageSize, titleDesc, category);
return Ok(result);
} catch (Exception ex)
{
return BadRequest(ex);
}
}
And here is my (simplified) openapi configuration:
openapi: 3.0.3
info:
title: EXAMPLE REST API
description: Api for the new example application
version: 1.0.0
servers:
- url: "https://{hostname}:{port}/{basePath}/"
variables:
hostname:
default: localhost
port:
default: "7051"
basePath:
default: api
tags:
- name: Job
paths:
/Jobs:
get:
operationId: getJobs
security:
- AzureOAuth:
- example.read
tags:
- Job
parameters:
- in: query
name: titleDesc
schema:
type: string
responses:
200:
description: Returns requested page
content:
application/json:
schema:
$ref: "#/components/schemas/JobPage"
components:
securitySchemes:
AzureOAuth:
type: oauth2
description: This API uses OAuth2 with authorizationCode grant flow.
flows:
authorizationCode:
authorizationUrl: https://example.b2clogin.com/example.onmicrosoft.com/B2C_1_SignUpAndSignIn/oauth2/v2.0/authorize
tokenUrl: https://example.b2clogin.com/example.onmicrosoft.com/B2C_1_SignUpAndSignIn/oauth2/v2.0/token
scopes:
example.read: read
example.write: write
schemas:
Job:
type: object
required:
- title
- category
- teleworkingDays
description: Job information
properties:
id:
type: integer
format: int64
title:
type: string
security:
- AzureOAuth:
- example.read
- example.write
I'm using oauth2 according to Azure's documentation.
Here is the post executed by the generated service.
Notice that the Bearer is empty.
I'm also wondering, if it's the correct way to do, because here I'm implementing it with the oauth2 way, but as I already have an access token in my localstorage, shouldn't just go with the bearer implementation ?
Also, testing with postman works completely fine, so I assume the controller part is fine.
Thank you

Stripe warning - Unrecognized token creation parameter

I'm just starting with stripe, and I noticed I get a warning in chrome saying:
Unrecognized token creation parameter parameter: company is not a
recognized parameter. This may cause issues with your integration in
the future.
This is the code.
stripe.createToken("account", {
company: {
name: "bbb",
address: {
line1: "77",
city: "abc",
state: "aa",
postal_code: "e2e"
}
},
tos_shown_and_accepted: true
}).then(function(result) {
debugger;
console.log(result);
});
I'm pretty much following the docs here (step 2)
https://stripe.com/docs/connect/account-tokens
It creates a token OK though.
The docs in the API reference suggest company is an object it should know:
https://stripe.com/docs/api/tokens/create_account
It basically tells you what is wrong.
It says that company is not a parameter that is recognized by that stripe endpoint. It creates the token, but ignores your passed parameter

How can I 'resolve' a MogoDB object to a specific JSON structure in Nodejs?

Suppose the following User Schema in MongoDB (using Mongoose/Nodejs):
var UserSchema = new Schema({
email: {
type: String,
unique: true,
required: 'User email is required.'
},
password: {
type: String,
required: 'User password is required.'
},
token: {
type: String,
unique: true,
default: hat
},
created_at: {
type: Date,
default: Date.now
},
});
// mongoose-encrypt package
UserSchema.plugin(encrypt, {
secret: 'my secret',
encryptedFields: ['email', 'password', 'token', 'created_at']
});
Now assume I want to return the user object from an API endpoint. In fact, suppose I want to return user objects from multiple API endpoints. Possibly as a standalone object, possibly as a related model.
Obviously, I don't want password to be present in the returned structure - and in many cases I wouldn't want token to be returned either. I could do this manually on every endpoint, but I'd prefer a no-thought solution - being able to simply retrieve the user, end of story, and not worry about unsetting certain values after the fact.
I mainly come from the world of Laravel, where things like API Resources (https://laravel.com/docs/5.6/eloquent-resources) exist. I already tried implementing the mongoose-hidden package (https://www.npmjs.com/package/mongoose-hidden) to hide the password and token, but unfortunately it seems as though that breaks the encryption package I'm using.
I'm new to Nodejs and MongoDB in general - is there a good way to implement this?
How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?
You can use this: Users.find().select("-password"),
but this is done whenever you send the queried item to the user (res.json()...) so you can do your manipultions with this field included and then remove it from the user before you send it back (this is using the promise approach, the best practice).
And if you want your changes to be used as default you can add "select: false" into the schema object's password field.
Hope this helps :)

I'm trying to make sense of session, but cannot get any data out of it

Currently using LUIS in a bot that connects to Slack. Right now I'm using interactive messages and trying to respond to user input correctly. When I click an item from the drop down LUIS receives it as a message. I can get the text with session.message.text, however I need to get the callback_id of the attachment as well as the channel it was sent from.
I've used console.log(session) to get an idea of what session looks like. From there I've seen that session.message.sourceEvent contains the data I need, however I can't use indexOf() or contains() to actual extrapolate the data. I've also tried session.message.sourceEvent.Payload but end up getting "[object [Object]]". I've tried searching for documentation on session formatting but to no avail.
Below is a snippet of what is returned when I run console.log(session.message.sourceEvent).
{ Payload:
action_ts: '1513199773.200354',
is_app_unfurl: false,
subtype: 'bot_message',
team: { id: 'T03QR2PHH', domain: 'americanairlines' },
user: { id: 'U6DT58F2T', name: 'john.cerreta' },
message_ts: '1513199760.000073',
attachment_id: '1',
ts: '1513199760.000073' },
actions: [ [Object] ],
callback_id: 'map_selection1',
original_message:
username: 'Rallybot',
response_url: 'https://hooks.slack.com/actions/T03QR2PHH/287444348935/Y6Yye3ijlC6xfmn8qjMK4ttB',
type: 'message',
{ type: 'interactive_message',
channel: { id: 'G6NN0DT88', name: 'privategroup' },
token: 'removed for security',
{ text: 'Please choose the Rally and Slack team you would like to map below.',
bot_id: 'B7WDX03UM',
attachments: [Array],
trigger_id: '285857445393.3841091595.085028141d2b8190b38f1bf0ca47dd88' },
ApiToken: 'removed for security' }
session.message.sourceEvent is a javascript Object, however indexOf or contains are functions of String or Array types.
Any info you required in the object, you should direct use the code <object>.<key> to invoke that value. You can try session.message.sourceEvent.Payload.action_ts for example.
Also, you can use Object.keys(session.message.sourceEvent) to get all the keys in this object.

Passport.js : Are UID unique?

I've a Nodejs app and I use Passeport to let my users connect throught Facebook or Google via Oauth. I'm storing basic data after connection such as : uid, firstname etc.
How can I be assured that the uid I'm receiving will be always unique for a given user ? I mean, data is coming either from Facebook or Google, so why couldn't I face a nasty duplicate uid for different users someday ?
The id you are getting via OAuth is unique when you are using either Facebook or Google. But if you want to use both then I would suggest make your dbSchema (if you are using mongoose) like this -
var userSchema = new mongoose.Schema({
local: {
username: String,
password: String
},
facebook: {
id: String,
token: String,
email: String,
name: String
},
google: {
id: String,
token: String,
email: String,
name: String
}
});
The UID is unique only within the scope of that single provider’s list of users.
This article suggests you combine the provider’s name plus the UID to get a unique value.
Combination of provider’s name and uID will uniquely identify user inside our app.
I would use the provider’s domain name such as “google.com” or “com.google”.

Resources