Laravel 5.4 - Socialite Providers multiple configurations with Twitter - twitter

I have two services to connect with Socialite Provider:
use Laravel\Socialite\Facades\Socialite;
use \SocialiteProviders\Manager\Config;
public function connect_1() {
$config1 = new Config(
env('TWITTER_CONSUMER_KEY_1'),
env('TWITTER_CONSUMER_SECRET_1'),
env('TWITTER_REDIRECT_URI_1'),
[
//
]
);
return Socialite::with('twitter')->setConfig($config1)->redirect();
}
public function connect_2() {
$config2 = new Config(
env('TWITTER_CONSUMER_KEY_2'),
env('TWITTER_CONSUMER_SECRET_2'),
env('TWITTER_REDIRECT_URI_2'),
[
//
]
);
return Socialite::with('twitter')->setConfig($config2)->redirect();
}
But, I have this error when I try this code:
Configuration for TWITTER_KEY is missing. There is no services entry
for twitter

I think this will work after
https://packagist.org/packages/socialiteproviders/manager
$clientId = "secret";
$clientSecret = "secret";
$redirectUrl = "yourdomain.com/api/redirect";
$additionalProviderConfig = ['site' => 'meta.stackoverflow.com'];
$config = new \SocialiteProviders\Manager\Config($clientId, $clientSecret, $redirectUrl, $additionalProviderConfig);
return Socialite::with('provider-name')->setConfig($config)->redirect();

Related

Create team in GraphAPI returns always null

I am using GraphAPI SDK to create a new Team in Microsoft Teams:
var newTeam = new Team()
{
DisplayName = teamName,
Description = teamName,
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
},
Members = new TeamMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", $"https://graph.microsoft.com/v1.0/users/{userId}"}
}
}
}
};
var team = await this.graphStableClient.Teams
.Request()
.AddAsync(newTeam);
The problem is that I get always null. According documentation this method returns a 202 response (teamsAsyncOperation), but the AddAsync method from SDK returns a Team object. Is there any way to get the tracking url to check if the team creation has been finished with the SDK?
Documentation and working SDK works different... As they wrote in microsoft-graph-docs/issues/10840, we can only get the teamsAsyncOperation header values if we use HttpRequestMessage as in contoso-airlines-teams-sample. They wrote to the people who asks this problem, look to the joined teams :)) :)
var newTeam = new Team()
{
DisplayName = model.DisplayName,
Description = model.Description,
AdditionalData = new Dictionary<string, object>
{
["template#odata.bind"] = $"{graph.BaseUrl}/teamsTemplates('standard')",
["members"] = owners.ToArray()
}
};
// we cannot use 'await client.Teams.Request().AddAsync(newTeam)'
// as we do NOT get the team ID back (object is always null) :(
BaseRequest request = (BaseRequest)graph.Teams.Request();
request.ContentType = "application/json";
request.Method = "POST";
string location;
using (HttpResponseMessage response = await request.SendRequestAsync(newTeam, CancellationToken.None))
location = response.Headers.Location.ToString();
// looks like: /teams('7070b1fd-1f14-4a06-8617-254724d63cde')/operations('c7c34e52-7ebf-4038-b306-f5af2d9891ac')
// but is documented as: /teams/7070b1fd-1f14-4a06-8617-254724d63cde/operations/c7c34e52-7ebf-4038-b306-f5af2d9891ac
// -> this split supports both of them
string[] locationParts = location.Split(new[] { '\'', '/', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
string teamId = locationParts[1];
string operationId = locationParts[3];
// before querying the first time we must wait some secs, else we get a 404
int delayInMilliseconds = 5_000;
while (true)
{
await Task.Delay(delayInMilliseconds);
// lets see how far the teams creation process is
TeamsAsyncOperation operation = await graph.Teams[teamId].Operations[operationId].Request().GetAsync();
if (operation.Status == TeamsAsyncOperationStatus.Succeeded)
break;
if (operation.Status == TeamsAsyncOperationStatus.Failed)
throw new Exception($"Failed to create team '{newTeam.DisplayName}': {operation.Error.Message} ({operation.Error.Code})");
// according to the docs, we should wait > 30 secs between calls
// https://learn.microsoft.com/en-us/graph/api/resources/teamsasyncoperation?view=graph-rest-1.0
delayInMilliseconds = 30_000;
}
// finally, do something with your team...
I found a solution from another question... Tried and saw that it's working...

Google Oauth2 API - No Refresh Token

I have attempted many solutions provided on Stack Exchange to obtain a refresh token, and they all fail. Below is my whole controller. As you can see, I have included $client->setAccessType('offline') and $client->setApprovalPrompt('force').
In addition, I have ran the revoke token many times, and I have gone into my Google Account here (https://myaccount.google.com/permissions), and removed access. None of these attempts provided me with a refresh token when I made a new authorization.
<?php
/**
* #file
* Contains \Drupal\hello\GAOauthController.
*/
namespace Drupal\ga_reports_per_user\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Google_Client;
use Google_Service_Analytics;
use Drupal\group\Context\GroupRouteContextTrait;
class GAOauthController extends ControllerBase {
use GroupRouteContextTrait;
public function authorize($group = NULL) {
$client = new Google_Client();
$credentials_file = \Drupal::service('file_system')->realpath("private://") . '/client_credentials.json';
$client->setAuthConfig($credentials_file);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$protocol = "https";
}
else {
$protocol = "http";
}
$redirect_uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . '/finish_google_oauth';
$client->setState($group);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$auth_url = $client->createAuthUrl();
return new TrustedRedirectResponse($auth_url);
}
public function finishOauth() {
if (isset($_GET['code'])) {
$client = new Google_Client();
$credentials_file = \Drupal::service('file_system')->realpath("private://") . '/client_credentials.json';
$client->setAuthConfig($credentials_file);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
$protocol = "https";
}
else {
$protocol = "http";
}
$redirect_uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . '/finish_google_oauth';
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->authenticate($_GET['code']);
$token = $client->getAccessToken();
$refreshToken = $client->getRefreshToken();
$client->setAccessToken($token);
$group_entity = \Drupal::entityTypeManager()->getStorage('group')->load($_GET['state']);
$group_entity->field_google_oauth_token->value = $token['access_token'];
$group_entity->field_google_oauth_token_type->value = $token['token_type'];
$group_entity->field_google_oauth_token_created->value = $token['created'];
$group_entity->field_google_oauth_token_expire->value = $token['expires_in'];
$save_status = $group_entity->save();
return new RedirectResponse('/group/' . $_GET['state']);
}
}
public function revoke($group = NULL){
$client = new Google_Client();
$group_entity = \Drupal::entityTypeManager()->getStorage('group')->load($group);
$result = $client->revokeToken($group_entity->field_google_oauth_token->value);
$group_entity->field_google_oauth_token->value = '';
$group_entity->field_google_oauth_token_type->value = '';
$group_entity->field_google_oauth_token_created->value = '';
$group_entity->field_google_oauth_token_expire->value = '';
$group_entity->save();
return new RedirectResponse('/group/' . $group);
}
}
If you have already requested an access token for that login / dev. token combo, it won't return it again for you. You'll have to revoke access by going to https://myaccount.google.com/permissions. Find your app, revoke access, and try again.
Source: I had this exact same problem and after nearly pulling my hair out, I figured this out.

How to use Basic auth in swagger ui v.3.0

in swagger ui 2.0 it was code
var basicAuth = new SwaggerClient.PasswordAuthorization("basicAuth", username, password);
window.swaggerUi.api.clientAuthorizations.add("basicAuth", basicAuth);
Can somebody provide code for version swagger ui 3.0?
Thanks.
Edit.
i`m trying to do something like this - Adding Basic Authorization for Swagger-UI
I`m using Swagger on server with Basic auth. SO i cant init library.
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
// yay ES6 modules ↘
Array.isArray(SwaggerUIStandalonePreset) ? SwaggerUIStandalonePreset : SwaggerUIStandalonePreset.default
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
without basic auth everything works fine.
basic auth enabled - http://prntscr.com/enxee4
In Swagger UI 3.x, fetching specs (.yaml/.json files) protected with Basic auth / API keys is supported in ver. 3.3.2 and later. In your Swagger UI initialization code, define a requestinterceptor that attaches auth headers to the spec fetch request:
<!-- index.html -->
const ui = SwaggerUIBundle({
url: "http://petstore.swagger.io/v2/swagger.json",
requestInterceptor: (req) => {
if (req.loadSpec) {
// Fetch the spec using Basic auth, replace "user" and "password" with yours
req.headers.Authorization = 'Basic ' + btoa('user:password');
// or API key
// req.headers.MyApiKey = 'abcde12345';
// or bearer token
// req.headers.Authorization = 'Bearer abcde12345';
}
return req;
},
...
})
I build an index.html with a simple form to fill user credentials to get a session id. Then redirect to swagger.html, for instance, and make some changes.
Before window.onload:
var orgFetch;
window.setExtraHeader = function(sessionId) {
var system = window.ui.getSystem();
if(!system) return;
if(!orgFetch) {
orgFetch = system.fn.fetch;
}
system.fn.fetch = function(obj) {
if(!obj) return;
if(!obj.headers) {
obj.headers = {};
}
obj.headers['sessionId'] = sessionId;
return orgFetch(obj)
.then(function(fetchRes) {
return fetchRes;
});
}
system.specActions.download();
}
and then:
window.ui = ui;
window.setExtraHeader(localStorage.getItem("sessionId"));
Source: https://github.com/swagger-api/swagger-ui/issues/2793
Hope this helps.
In swagger-ui 3.2x, to manually set Authorization header based on values entered in the authorize popup for basic authentication, we can use below code.
const ui = SwaggerUIBundle({
dom_id: '#swagger-ui',
requestInterceptor: (req) => {
if (!req.loadSpec) {
var authorized = this.ui.authSelectors.authorized();
//'Basic_Authentication' is security scheme key for basic authentication in the OpenApi file
var basicAuth = getEntry(authorized, 'Basic_Authentication');
if (basicAuth) {
var basicAuthValue = getEntry(basicAuth, 'value');
if (basicAuthValue) {
var username = getEntry(basicAuthValue, 'username');
var password = getEntry(basicAuthValue, 'password');
if (username && password) {
req.headers.Authorization = "Basic " + btoa(username + ":" + password);
}
}
}
}
return req;
}
//traverse through the object structure of swagger-ui authorized object to get value for an entryName
function getEntry(complexObj, entryName) {
if (complexObj && complexObj._root && complexObj._root.entries) {
var objEntries = complexObj._root.entries;
for (var t = 0; t < objEntries.length; t++) {
var entryArray = objEntries[t];
if (entryArray.length > 1) {
var name = entryArray[0];
if (name === entryName) {
return entryArray[1];
}
}
}
}
return null;
}

Zend 2 After login how to set user

I have the following code and which works, but now the next step.
How and where do i have to set a session so the script "sees" that the user is already logged in?
if ($form->isValid()) {
$securePass = $this->getUsersTable()->getUserByUsername( $this->params()->fromPost('username') );
if( $securePass ){
$bcrypt = new Bcrypt();
if ($bcrypt->verify( $this->params()->fromPost('password') , $securePass->password)) {
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$authAdapter = new AuthAdapter(
$dbAdapter,
'users',
'username',
'password'
);
$authAdapter
->setIdentity($securePass->username)
->setCredential($securePass->password);
$result = $authAdapter->authenticate($authAdapter);
echo $result->getIdentity() . "\n\n";
}
else {
}
The Zend way of doing it is to use Authentication component that handles this for you.
http://framework.zend.com/manual/current/en/modules/zend.authentication.intro.html
This will allow you to check if user is logged in (you will have to setup the authentication adapter first):
use Zend\Authentication\AuthenticationService;
// TODO set-up authentication adapter
$auth = new AuthenticationService()
$identity = $auth->getIdentity();
For accessing post data you should also leverage the framework instead of accessing $_POST directly. In your controller:
$this->params()->fromPost('username');
$this->params()->fromPost('password');
This will guide you through the whole process of adding authentication layer to your app:
https://zf2.readthedocs.org/en/latest/modules/zend.authentication.adapter.dbtable.html
Using the AuthenticationService provided by Zend, setting the user in the PHP session is automatically taken care of.
A good thing to understand the authentication mechanism would be to read, and code along with this introduction to authentication:
http://framework.zend.com/manual/current/en/modules/zend.authentication.intro.html#adapters
In a custom AuthenticationAdapter "setting the user in the session", or identity persistence, would be done by returning \Zend\Authentication\Result with the result of the authentication and the user identity in the authenticate() method.
$user = $this->userService->findByEmail($this->email);
if($user !== false) {
if($this->encryption->verify($this->password, $user->getPassword()) {
return new Result(Result::SUCCESS, $user);
}
return new Result(Result::FAILURE, null);
}
$this->userService being the UserService that leads to the UserMapper
(more about Services: http://framework.zend.com/manual/current/en/in-depth-guide/services-and-servicemanager.html)
$user being the User entity with the encrypted password stored
$this->encryption being your encryption method (Zend\Crypt\Password\Bcrypt for example)
$this->email being the email/username provided by the form
$this->password being the password provided by the form
Result being Zend\Authentication\Result
This is an easy approach. More detailed Result types are:
/**
* General Failure
*/
const FAILURE = 0;
/**
* Failure due to identity not being found.
*/
const FAILURE_IDENTITY_NOT_FOUND = -1;
/**
* Failure due to identity being ambiguous.
*/
const FAILURE_IDENTITY_AMBIGUOUS = -2;
/**
* Failure due to invalid credential being supplied.
*/
const FAILURE_CREDENTIAL_INVALID = -3;
/**
* Failure due to uncategorized reasons.
*/
const FAILURE_UNCATEGORIZED = -4;
/**
* Authentication success.
*/
const SUCCESS = 1;
LoginController.php
if ($form->isValid()) {
$securePass = $this->getUsersTable()->getUserByUsername( $this->params()->fromPost('username') );
if( $securePass ){
$bcrypt = new Bcrypt();
if ($bcrypt->verify( $this->params()->fromPost( 'password' ) , $securePass->password ) ) {
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$authAdapter = new AuthAdapter(
$dbAdapter,
'users',
'username',
'password'
);
$authAdapter->setIdentity($securePass->username)
->setCredential($securePass->password);
$result = $authAdapter->authenticate($authAdapter);
$sesssionData = $authAdapter->getResultRowObject();
$auth = new AuthenticationService();
$storage = $auth->getStorage();
$storage->write($sesssionData);
return $this->redirect()->toRoute('user_list');
}
}
}
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$app = $e->getParam('application');
$app->getEventManager()->attach('render', array($this, 'setLayoutTitle'));
$eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'checkLogin'));
}
public function checkLogin(MvcEvent $e)
{
$iden = new AuthenticationService();
if( $iden->getIdentity() === NULL ){
$matches = $e->getRouteMatch();
$controller = $matches->getParam('controller');
$getController = explode( '\\', $controller );
if( isset( $getController[2] ) && $getController[2] != 'Login' ){
$controller = $e->getTarget();
return $controller->plugin('redirect')->toRoute('login');
}
}
}

Using Neo4jUserManager

I'm new at Neo4j and I'm going to use neo4j.AspNet.Identity for my authentication and authorization. I'm using neo4jUserManager and also neo4jUserStore.But when I run the application, in Neo4jUserManager create method I'll face with NullExceptionReference and I don't know why? Can Anybody help me?
Below is my code
public class Neo4jUserManager : UserManager<ApplicationUser>
{
public Neo4jUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public async Task SetLastLogin()
{
// Store.FindByIdAsync()
}
public static Neo4jUserManager Create(IdentityFactoryOptions<Neo4jUserManager> options, IOwinContext context)
{
var graphClientWrapper = context.Get<GraphClientWrapper>();
var manager = new Neo4jUserManager(new Neo4jUserStore<ApplicationUser>(graphClientWrapper.GraphClient));
// Configure validation logic for usernames
// manager.UserValidator = new UserValidator<Neo4jUser>(manager)
// {
// AllowOnlyAlphanumericUserNames = false,
// RequireUniqueEmail = true
// };
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = false;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
// manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<Neo4jUser>
// {
// MessageFormat = "Your security code is {0}"
// });
// manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<Neo4jUser>
// {
// Subject = "Security Code",
// BodyFormat = "Your security code is {0}"
// });
// manager.EmailService = new EmailService();
// manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
To setup the graphClientWrapper, you can do this:
var gc = new GraphClient(new Uri("http://localhost.:7474/db/data"));
gc.Connect();
var graphClientWrapper = new GraphClientWrapper(gc);
var manager = new Neo4jUserManager(new Neo4jUserStore<ApplicationUser>(graphClientWrapper.GraphClient));
Also, as a side I would read up on how to use Owin. It should have been obvious to you that you're trying to pull from an IOwinContext object, and that if you're getting null you should investigate how to set that up. I imagine less than 5 minutes on Google would have helped you. OR just looking at what calls that method would have shown you how the EntityFramework was being setup in the template you're modifying.

Resources