How to extract username and password in swagger-ui Authentication form - basic-authentication

By searching, I got answer to add "req.headers.Authorization" as the following, but it is hard-coded username and password. I want to reuse the username and password in Authentication form to take input of username and password.
<!-- index.html -->
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
requestInterceptor: (req) => {
if (req.loadSpec) {
// How to extract username and password in Authentication form?
req.headers.Authorization = 'Basic ' + btoa('user:password');
}
return req;
},
...
})

Related

Is it possible to use client_credentials grant type for auth0 login in CyPress?

In our project we use Auth0 with Google login and don't use username/password login. We started to write tests for our app, but we can't login in Cypress framework. We need login using Google auth (but it's not possible to do it using request). Also, we don't store token in localStorage, because frontend part uses auth0 react sdk for it.
I tried to find how to login in Cypress using auth0, but found only solutions for username/password login.
Possible solution from this post:
Cypress.Commands.add("login", () => {
cy.clearLocalStorage();
const email = "";
const password = "";
const client_id = "";
const client_secret = "";
const audience = "";
const scope = "";
cy.request({
method: "POST",
url: "",
body: {
grant_type: "password",
username: email,
password,
audience,
scope,
client_id,
client_secret,
},
}).then(({ body: { access_token, expires_in, id_token, token_type } }) => {
cy.window().then((win) => {
win.localStorage.setItem(
`##auth0spajs##::${client_id}::${audience}::${scope}`,
JSON.stringify({
body: {
client_id,
access_token,
id_token,
scope,
expires_in,
token_type,
decodedToken: {
user: JSON.parse(
Buffer.from(id_token.split(".")[1], "base64").toString("ascii")
),
},
audience,
},
expiresAt: Math.floor(Date.now() / 1000) + expires_in,
})
);
cy.reload();
});
});
});
I can get token using client_credentials grant type, but I can't use it in this solution, because it uses id_token instead of the access_token.
Is it possible to use client_credentials grant type for this login? Or should we turn ON username/password login for it?
Request for client_credentials grant type:
curl --request POST \
--url 'https://YOUR_DOMAIN/oauth/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=client_credentials \
--data client_id=YOUR_CLIENT_ID \
--data client_secret=YOUR_CLIENT_SECRET \
--data audience=YOUR_API_IDENTIFIER
It returns:
{
"access_token":"eyJz93a...k4laUWw",
"token_type":"Bearer",
"expires_in":86400
}
Here's a Cypress test that shows how we handle Keycloak, Okta, and Auth0 in Ionic for JHipster:
https://github.com/jhipster/generator-jhipster-ionic/blob/main/generators/ionic/resources/oauth2/cypress/support/commands.ts
We turned ON username/password way for login, and used UI for login. After the first login, Cypress don't show login page again, because we are already logged.
My solution (we use only username/password without additional info from Auth0):
Cypress.Commands.add('loginAuth0', (username = Cypress.env('auth0_username'), password = Cypress.env('auth0_password')) => {
cy.visit(`/`);
cy.wait(4000); // wait when auth0 modal is loaded (if user is not logged in)
cy.document().then(doc => {
if (doc.querySelector("#username") != null && doc.querySelector("#password") != null) {
cy.get('#username').type(username);
cy.get('#password').type(password);
cy.get('button[name="action"]').click();
} else {
cy.log("User is already logged.");
}
});
});

How can I check username and password of an existing user in WordPress with react-native/

I'm writing a mobile application for a WordPress site.
I want to check username and password with WPAPI and JSON Basic Authentication plugin.
I have tried this code so far:
const wp = new WPAPI({
endpoint: 'https://example.com/wp-json',
username: this.state.username,
password: this.state.password
});
console.log(wp.users().me());
it returns
_options:{auth:true, ...}
no matter what is the username and password value.
Maybe show your react native implementation of the WPAPI.
Documentation:
As an example, wp.users().me() will automatically enable authentication to permit access to the /users/me endpoint.
Sounds like it's more an API-Call which set a flag instead of returning your userprofile (I guess you expected to get your user-profile?!)
Maybe give it a try to request a page (like described in the examples (see: Documentation)):
wp.pages().slug( 'about' )
I have finally solved this problem:
validate() {
let username = this.state.username;
let password = this.state.password;
let userPassCombination = username + ':' + password;
let encodedPass = base64.encode(userPassCombination);
let headers = {
'Content-Type': 'text/json',
Authorization: 'Basic ' + encodedPass,
};
fetch(myConstants.URL + '/wp-json/', {
method: 'GET',
headers: headers,
}).then(responseData => {
//console.log(JSON.stringify(responseData));
if (responseData.ok) {
this.props.navigation.navigate('Profile', {
username: this.state.username,
});
}
else {
alert('wrong information.');
}
});
}
}

How to send verification email from server to client's register email

I am using meteor for developing my application. I need to verify user as soon as he register himself. I used SendverificationEmail() method of meteor and i m getting link on the server side . Now i want to send that unique link to the client's register email. How it will done?
You will have to use meteor Email package to send email:
Meteor Email Package
After you have added package just write below code in your method to send an email
Email.send({ to, from, subject, text });
Sorry to See this post little late, but there are many folks out there who are willing to implement this even today. So below are the steps to achieve email verification flow.
NOTE: I am using Meteor 1.6.1.1, with Flow-routers + Blaze Templates. Also, make sure you have enabled 3rd party API access call to Gmail. You can do this from Gmail settings.
Import Packages: accounts-ui, accounts-password
In root_folder/server/ folder, inside main.js copy paste below code and make the necessary credential change to your file.
var username = 'asdasdasdas';
var password = 'sdasdasdasd';
var server = 'smtp.gmail.com';
var port = '465';
process.env.MAIL_URL = 'smtps://' +
encodeURIComponent(username) + ':' +
encodeURIComponent(password) + '#' +
encodeURIComponent(server) + ':' + port;
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
Accounts.emailTemplates.from = 'support_team#domain.com';
//-- Application name
Accounts.emailTemplates.siteName = 'Your Site Name';
//-- Subject line of the email.
Accounts.emailTemplates.verifyEmail.subject = function(user) {
return 'Email Confirmation.';
};
//-- Email text
Accounts.emailTemplates.verifyEmail.text = function(user, url) {
var newUrl = url.replace('/#','');
return 'Thank you for registering. Please click on the following link to verify your email address: \r\n' + newUrl;
};
// Configure to send the Email Verification mail as true
Accounts.config({
sendVerificationEmail: true,
restrictCreationByEmailDomain: function(email) {
var domain = email.slice(email.lastIndexOf("#")+1); // or regex
var allowed = ["gmail.com", "yahoo.co.in", "outlook.com", "yahoo.com", "yandex.com", "protonmail.com", "protonmail.ch", ];
return _.contains(allowed, domain);
},
loginExpirationInDays: 1
});
When you successfully create an account in Meteor app, you will get an email as below;
Inside the mail, You will see a link with route of pattern /verify-email/:token, hence go inside project/client/routes.js you need to add the route,
import { FlowRouter } from 'meteor/kadira:flow-router';
//force user to stay on home page instead of desired page
Accounts.onLogin(function(user){
var user = Meteor.user();
if(user.emails && user.emails[0].verified){
FlowRouter.go('dashboard');
}
});
FlowRouter.route('/verify-email/:tokenId', {
name: 'verify-email',
action: function(params, queryParams) {
var token = FlowRouter.getParam("tokenId");
console.log(token);
Accounts.verifyEmail(token, function(err){
if(!err){
FlowRouter.go("dashboard");
} else {
FlowRouter.go("error-page");
}
});
},
});
In case if you are using iron-router, you can refer this LINK

In meteor how to verify user password before running a method? [duplicate]

There are some irreversible actions that user can do in my app. To add a level of security, I'd like to verify that the person performing such an action is actually the logged in user. How can I achieve it?
For users with passwords, I'd like a prompt that would ask for entering user password again. How can I later verify this password, without sending it over the wire?
Is a similar action possible for users logged via external service? If yes, how to achieve it?
I can help with the first question. As of this writing, meteor doesn't have a checkPassword method, but here's how you can do it:
On the client, I'm going to assume you have a form with an input called password and a button called check-password. The event code could look something like this:
Template.userAccount.events({
'click #check-password': function() {
var digest = Package.sha.SHA256($('#password').val());
Meteor.call('checkPassword', digest, function(err, result) {
if (result) {
console.log('the passwords match!');
}
});
}
});
Then on the server, we can implement the checkPassword method like so:
Meteor.methods({
checkPassword: function(digest) {
check(digest, String);
if (this.userId) {
var user = Meteor.user();
var password = {digest: digest, algorithm: 'sha-256'};
var result = Accounts._checkPassword(user, password);
return result.error == null;
} else {
return false;
}
}
});
For more details, please see my blog post. I will do my best to keep it up to date.
I haven't done this before, but I think you will need something like this on your server
Accounts.registerLoginHandler(function(loginRequest) {
console.log(loginRequest)
var userId = null;
var username = loginRequest.username;
// I'M NOT SURE HOW METEOR PASSWORD IS HASHED...
// SO YOU NEED TO DO A BIT MORE RESEARCH ON THAT SIDE
// BUT LET'S SAY YOU HAVE IT NOW
var password = loginRequest.password;
var user = Meteor.users.findOne({
$and: [
{username: username},
{password: password}
]
});
if(!user) {
// ERROR
} else {
// VERIFIED
}
});
then you can call this function from the client side like this:
// FETCH THE USERNAME AND PASSWORD SOMEHOW
var loginRequest = {username: username, password: password};
Accounts.callLoginMethod({
methodArguments: [loginRequest]
});
I have a project on github for different purpose, but you can get a sense of how it is structured: https://github.com/534N/apitest
Hope this helps,
I have found the best way to validate the users password is to use the Accounts.changePassword command and
pass in the same password for old and new password. https://docs.meteor.com/api/passwords.html#Accounts-changePassword
Accounts.changePassword(this.password, this.password, (error) => {
if(error) {
//The password provided was incorrect
}
})
If the password provided is wrong, you will get an error back and the users password will not be changed.
If the password is correct, the users password will be updated with the same password as is currently set.

New user can't change password in Meteor

When I add a new user, and open the link in the received verification email, the new user is logged in but can't change password. When I go to "Change password", I leave "current password" blank, type a password and click "Change password" and get the error "Match failed".
The user is created with a Meteor.call from the client to the following method:
Meteor.methods({
createUser: function(user) {
var userID = Accounts.createUser({
username: user.username,
email: user.email,
profile: {
firstName: user.firstName,
lastName: user.lastName,
}
});
Accounts.sendVerificationEmail(userID);
}
});
I have the following settings for Accounts.config and Accounts.ui.config:
Accounts.ui.config({
passwordSignupFields: 'USERNAME_AND_EMAIL'
})
Accounts.config({
forbidClientAccountCreation: false,
sendVerificationEmail: true
})
Thanks :-)
Why do you leave current password blank?
When creating an account you must specify a password otherwise it is considered null.
Try passing in password: "" when creating it if you intend to change it this way.
I would recommend you write a method to change it if you want them to enter a password after they have verified their account. Something like this:
Meteor.methods('changeMyPassword':function(newPassword) {
Accounts.setPassword(this.userId, newPassword);
});
The intention of the account verification email is that you create the account with a specified password and verify it after you've created the account.
Example of how to use Accounts.createUser

Resources