python social auth load strategy and authenticate user manually with release 0.1.26 - python-social-auth

I used python social auth for social authentication in the last 2 months and it was great.
I needed QQ support, hence installed newest git commit (23e4e289ec426732324af106c7c2e24efea34aeb - not part of a release).
until now i used to authenticate the user using the following code:
# setup redirect uri in order to load strategy
uri = redirect_uri = "social:complete"
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
# load the strategy
try:
strategy = load_strategy(
request=request, backend=backend,
redirect_uri=uri, **kwargs
)
strategy = load_strategy(request=bundle.request)
except MissingBackend:
raise ImmediateHttpResponse(HttpNotFound('Backend not found'))
# get the backend for the strategy
backend = strategy.backend
# check backend type and set token accordingly
if isinstance(backend, BaseOAuth1):
token = {
'oauth_token': bundle.data.get('access_token'),
'oauth_token_secret': bundle.data.get('access_token_secret'),
}
elif isinstance(backend, BaseOAuth2):
token = bundle.data.get('access_token')
else:
raise ImmediateHttpResponse(HttpBadRequest('Wrong backend type'))
# authenticate the user
user = strategy.backend.do_auth(token)
which worked fine.
In the latest release this behaviour has changed, and an exception is raised since the "load_strategy" method has changed.
I can't seem to find any documentation on how to do it with the new release.
Any help would be appreciated!
Omri.

The last changes in the repository changed the importance of the strategy, instead of being the main entity to perform the authentication, it's just a helper class to glue the framework with the backends. Try with this snippet to load the strategy and the backend:
from social.apps.django_app.utils import load_strategy, load_backend
strategy = load_strategy(request)
backend = load_backend(strategy, backend, uri)
...
user = backend.do_auth(token)

Related

Writing log to gcloud Vertex AI Endpoint using gcloud client fails with google.api_core.exceptions.MethodNotImplemented: 501

Trying to use google logging client library for writing logs into gcloud, specifically, i'm interested in writing logs that will be attached to a managed resource, in this case, a Vertex AI endpoint:
Code sample:
import logging
from google.api_core.client_options import ClientOptions
import google.cloud.logging_v2 as logging_v2
from google.oauth2 import service_account
def init_module_logger(module_name: str) -> logging.Logger:
module_logger = logging.getLogger(module_name)
module_logger.setLevel(settings.LOG_LEVEL)
credentials= service_account.Credentials.from_service_account_info(json.loads(SA_KEY_JSON))
client = logging_v2.client.Client(
credentials=credentials,
client_options=ClientOptions(api_endpoint="us-east1-aiplatform.googleapis.com"),
)
handler = client.get_default_handler(
resource=Resource(
type="aiplatform.googleapis.com/Endpoint",
labels={"endpoint_id": "ENDPOINT_NUMBER_ID",
"location": "us-east1"},
)
)
#Assume we have the formatter
handler.setFormatter(ENRICHED_FORMATTER)
module_logger.addHandler(handler)
return module_logger
logger = init_module_logger(__name__)
logger.info("This Fails with 501")
And i am getting:
google.api_core.exceptions.MethodNotImplemented: 501 The GRPC target
is not implemented on the server, host:
us-east1-aiplatform.googleapis.com, method:
/google.logging.v2.LoggingServiceV2/WriteLogEntries. Sent all pending
logs.
I thought we need to enable api and was told it's enabled, and that we have: https://www.googleapis.com/auth/logging.write
what could be causing the error?
As mentioned by #DazWilkin in the comment, the error is because the API endpoint us-east1-aiplatform.googleapis.com does not have a method called WriteLogEntries.
The above endpoint is used to send requests to Vertex AI services and not to Cloud Logging. The API endpoint to be used is the logging.googleapis.com as shown in the entries.write method. Refer to this documentation for more info.
The ClientOptions() function should have logging.googleapis.com as the api_endpoint parameter. If the client_options parameter is not specified, logging.googleapis.com is used by default.
After changing the api_endpoint parameter, I was able to successfully write the log entries. The ClientOptions() is as follows:
client = logging_v2.client.Client(
credentials=credentials,
client_options=ClientOptions(api_endpoint="logging.googleapis.com"),
)

ning.http.client Kerberos Example

How can I support Kerberos based authentication with the ning http client?
I am extending existing code which has support for NTLMAuth and I want to be able to include support for Kerberos, which is used on some of the websites that I need to test.
I want to be able to put in the user and password programmatically, I do not want to use a keyTab, or setup krb5 configuration on the system where this is running.
I have the following code block;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Realm.RealmBuilder;
....
RealmBuilder myRealmBuilder = new RealmBuilder()
.setScheme(AuthScheme.KERBEROS)
.setUsePreemptiveAuth(true)
.setNtlmDomain(getDomain())
.setNtlmHost(getHost())
.setPrincipal(getUsername())
.setPassword(getUserPassword()));
RequestBuilder rb = new RequestBuilder()
.setMethod(site.getMethod())
.setUrl(site.getUrl())
.setFollowRedirects(site.isFollowRedirects())
.setRealm(myRealmBuilder),
site)
ยดยดยด
Currently I get the error response:
FAILED: Invalid name provided (Mechanism level: KrbException: Cannot locate default realm)
Does anyone have an good example of how to do this correctly?

OIDC AspNetCore OpenIdConnectHandler Correlation Failed state property not found

I have an OIDC authentication server based on Identity Server 4 which allows federation on to an external identity provider.
services.AddAuthentication()
.AddOpenIdConnect(extIDP.AuthScheme, extIDP.AuthDisplay, options =>
{
options.SignInScheme = extIDP.Options.SignInScheme;
options.SignOutScheme = extIDP.Options.SignOutScheme;
options.Authority = extIDP.Options.Authority;
options.ClientId = extIDP.Options.ClientId;
options.ClientSecret = extIDP.Options.ClientSecret;
options.ResponseType = extIDP.Options.ResponseType;
options.CallbackPath = extIDP.Options.CallbackPath;
options.SignedOutCallbackPath = extIDP.Options.SignedOutCallbackPath;
options.RemoteSignOutPath = extIDP.Options.RemoteSignOutPath;
options.RequireHttpsMetadata = extIDP.Options.RequireHttpsMetadata;
options.SaveTokens = true;
options.Scope.Clear();
options.Scope.Add(IdentityServerConstants.StandardScopes.OpenId);
options.Scope.Add(IdentityServerConstants.StandardScopes.Profile);
options.Scope.Add(IdentityServerConstants.StandardScopes.Email);
options.Scope.Add(JwtClaimTypes.Role);
});
Where extIDP comes from some configuration.
So this works just fine, but we have a client with an IDP that doesnt support a response mode of form_post (which is the default used in the setup above), so if I add in an extra line to the config to set the ResponseMode to "fragment" then we should be fine but it does not work.
I end up with a Correlation Error being reported
With verbose logging enabled in our Auth Server we get
Warning: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler
".AspNetCore.Correlation." state property not found
Note this is occurring when running against two test auth servers locally so has nothing to do with load balancing problems.
I also added a cookie policy to ensure it wasnt being cause by a strict cookie policy. So I am currently a bit stuck.

Terraform - AWS - API Gateway dependency conundrum

I am trying to provision some AWS resources, specifically an API Gateway which is connected to a Lambda. I am using Terraform v0.8.8.
I have a module which provisions the Lambda and returns the lambda function ARN as an output, which I then provide as a parameter to the following API Gateway provisioning code (which is based on the example in the TF docs):
provider "aws" {
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
region = "${var.region}"
}
# Variables
variable "myregion" { default = "eu-west-2" }
variable "accountId" { default = "" }
variable "lambdaArn" { default = "" }
variable "stageName" { default = "lab" }
# API Gateway
resource "aws_api_gateway_rest_api" "api" {
name = "myapi"
}
resource "aws_api_gateway_method" "method" {
rest_api_id = "${aws_api_gateway_rest_api.api.id}"
resource_id = "${aws_api_gateway_rest_api.api.root_resource_id}"
http_method = "GET"
authorization = "NONE"
}
resource "aws_api_gateway_integration" "integration" {
rest_api_id = "${aws_api_gateway_rest_api.api.id}"
resource_id = "${aws_api_gateway_rest_api.api.root_resource_id}"
http_method = "${aws_api_gateway_method.method.http_method}"
integration_http_method = "POST"
type = "AWS"
uri = "arn:aws:apigateway:${var.myregion}:lambda:path/2015-03-31/functions/${var.lambdaArn}/invocations"
}
# Lambda
resource "aws_lambda_permission" "apigw_lambda" {
statement_id = "AllowExecutionFromAPIGateway"
action = "lambda:InvokeFunction"
function_name = "${var.lambdaArn}"
principal = "apigateway.amazonaws.com"
source_arn = "arn:aws:execute-api:${var.myregion}:${var.accountId}:${aws_api_gateway_rest_api.api.id}/*/${aws_api_gateway_method.method.http_method}/resourcepath/subresourcepath"
}
resource "aws_api_gateway_deployment" "deployment" {
rest_api_id = "${aws_api_gateway_rest_api.api.id}"
stage_name = "${var.stageName}"
}
When I run the above from scratch (i.e. when none of the resources exist) I get the following error:
Error applying plan:
1 error(s) occurred:
* aws_api_gateway_deployment.deployment: Error creating API Gateway Deployment: BadRequestException: No integration defined for method
status code: 400, request id: 15604135-03f5-11e7-8321-f5a75dc2b0a3
Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.
If I perform a 2nd TF application it consistently applies successfully, but every time I destroy I then receive the above error upon the first application.
This caused me to wonder if there's a dependency that I need to explicitly declare somewhere, I discovered #7486, which describes a similar pattern (although relating to an aws_api_gateway_integration_response rather than an aws_api_gateway_deployment). I tried manually adding an explicit dependency from the aws_api_gateway_deployment to the aws_api_gateway_integration but this had no effect.
Grateful for any thoughts, including whether this may indeed be a TF bug in which case I will raise it in the issue tracker. I thought I'd check with the community before doing so in case I'm missing something obvious.
Many thanks,
Edd
P.S. I've asked this question on the Terraform user group but this seems to get very little in the way of responses, I'm yet to figure out the cause of the issue hence now asking here.
You are right about the explicit dependency declaration.
Normally Terraform would be able to figure out the relationships and schedule create/update/delete operations accordingly to that - this is mostly possible because of the interpolation mechanisms under the hood (${resource_type.ref_name.attribute}). You can display the relationships affecting this in a graph via terraform graph.
Unfortunately in this specific case there's no direct relationship between API Gateway Deployments and Integrations - meaning the API interface for managing API Gateway resources doesn't require you to reference integration ID or anything like that to create deployment and the api_gateway_deployment resource in turn doesn't require that either.
The documentation for aws_api_gateway_deployment does mention this caveat at the top of the page. Admittedly the Deployment not only requires the method to exist, but integration too.
Here's how you can modify your code to get around it:
resource "aws_api_gateway_deployment" "deployment" {
rest_api_id = "${aws_api_gateway_rest_api.api.id}"
stage_name = "${var.stageName}"
depends_on = ["aws_api_gateway_method.method", "aws_api_gateway_integration.integration"]
}
Theoretically the "aws_api_gateway_method.method" is redundant since the integration already references the method in the config:
http_method = "${aws_api_gateway_method.method.http_method}"
so it will be scheduled for creation/update prior to the integration either way, but if you were to change that to something like
http_method = "GET"
then it would become necessary.
I have submitted PR to update the docs accordingly.

Grails rest spring security plugin does not store generated token using GORM in database

I am using the GORM option to store the generated token in database for my Grails 3.x application using grails spring security rest plugin.
The application generates the token but does not get stored in database. Do we need to override the tokenStorage method and have our own implementation to store the token in database
The plugin properties configured in application.groovy are listed below
grails.plugin.springsecurity.rest.token.validation.useBearerToken = false
grails.plugin.springsecurity.rest.login.endpointUrl = '/api/login'
grails.plugin.springsecurity.rest.token.validation.headerName = 'X-Auth-Token'
grails.plugin.springsecurity.rest.token.storage.useJwt = false
grails.plugin.springsecurity.rest.token.storage.useGorm=true
grails.plugin.springsecurity.rest.token.storage.gorm.tokenDomainClassName='com.auth.AuthenticationToken'
grails.plugin.springsecurity.rest.token.storage.gorm.tokenValuePropertyName='token'
grails.plugin.springsecurity.rest.token.storage.gorm.usernamePropertyName='username'
grails.plugin.springsecurity.rest.login.passwordPropertyName = 'password'
grails.plugin.springsecurity.rest.login.useJsonCredentials = true
grails.plugin.springsecurity.rest.login.useRequestParamsCredentials = false
grails.plugin.springsecurity.rest.token.rendering.authoritiesPropertyName = 'permissions'
Make sure you have added the following to your build.gradle:
compile 'org.grails.plugins:spring-security-rest:2.0.0.M2'
compile 'org.grails.plugins:spring-security-rest-gorm:2.0.0.M2'
And you have defined the following in application.groovy or application.yml
grails.plugin.springsecurity.rest.token.storage.useGorm=true
grails.plugin.springsecurity.rest.token.storage.gorm.tokenDomainClassName = 'com.yourdomain.AuthenticationToken'
grails.plugin.springsecurity.rest.token.storage.gorm.tokenValuePropertyName = 'tokenValue'
grails.plugin.springsecurity.rest.token.storage.gorm.usernamePropertyName = 'username'
There is almost no information to help you. No build configuration, no logs, no idea how the requests are made...
But from the description of your problem, my guess is that you are missing the GORM module in your classpath. It's clearly stated in the documentation.
Be also sure to read the what's new in 2.0 chapter.
I had the same problem, token not stored and no error messages seen.
After installing the GORM plugin:
compile "org.grails.plugins:spring-security-rest-gorm:2.0.0.M2"
I could login and a token was saved into the table.