AddOAuth is not defining the Callbackpath specified (getting a 404 on it) - ASP .NET Core 3 - asp.net-core-3.1

I am trying to implement an OAuth2 client using ASP.NET Core 3 application. Here is how I add OAuth to my startup
services.AddAuthentication(config =>
{
config.DefaultAuthenticateScheme = "Client.Auth.Cookie";
config.DefaultSignInScheme = "Client.Auth.Cookie";
config.DefaultChallengeScheme = "SelfServer";
})
.AddCookie("Client.Auth.Cookie")
.AddOAuth("SelfServer", config =>
{
config.CallbackPath = "/oauth/callback";
config.AuthorizationEndpoint = "https://Server/oauth/authorize";
config.TokenEndpoint = "https://Server/oauth/token";
config.ClientId = "clientid";
config.ClientSecret = "secret_key";
});
As I read in the documentation, the /oauth/callback is something I do not have to define myself (no need to create OAuthController with Callback action). I kind of by mistake did it and defined it myself, then when I realized, I deleted the OAuthController and now I am getting a 404 on https://client/oauth/callback.
What am I missing?

Alright I realized a few seconds after posting this question that I forgot to call
app.UseAuthentication()
in my Configure() method in the Startup.

Related

Sailsjs - Cloud SDK - Blueprint API auto generated routes?

I wonder if it is possible to have the Blueprint API support in Cloud SDK.
But apparently, the generated cloud.setup.js file does not contain blueprint APIs. Just normal routes beginning with /api
It is written in the Cloud.js file :
* ### Basic Usage
*
* var user = await Cloud.findOneUser(3);
*
* var user = await Cloud.findOneUser.with({ id: 3 });
It lets think that it's possible to have auto generated routes to the blueprint APIs like actionModel -> findOneUser, createServer, addToGame, and so on...
Do you know if that is possible ? I don't find a documentation about this.
Thanks
I took original code in rebuild-cloud-sdk.js and created a rcsdk.js with the code below before the actual for (let address in sails.config.routes):
_.each(_.keys(sails.models), model => {
let action = sails.config.blueprints.prefix + sails.config.blueprints.restPrefix + '/' + model;
_.each([['GET', 'find'], ['POST', 'create']], pair => {
endpointsByMethodName[`${pair[1]}${model}`] = {
verb: pair[0],
url: action,
}
});
_.each([['GET', 'findOne'], ['PUT', 'update'], ['DELETE', 'delete']], pair => {
endpointsByMethodName[`${pair[1]}${model}`] = {
verb: pair[0],
url: action,
args: ['id'],
}
});
});
I also asked this question the other day. It is not possible. We need to be explicit here. Blueprint routes is only for quick integration testing with postman. I don't recommend this though. You should not be using postman or auto routes. You should write tests in files so they are permanent.

Identityserver4 with ComponentSpace SAML 2 get custom parameters during request

I am using IdentityServer4 with two external Idp's, one with WSFederation (ADFS) and one with SAML.
For the SAML implementation I use the commercial product ComponentSpace SAML 2 for ASP.Net Core. I use the middleware-based config.
Logging it with both Idp's works perfectly, but now I have the situation where, depending on the client, I need to pass extra parameters to the SAML AuthnRequest. I know how to pass this extra parameter in the request (I can use the OnAuthnRequestCreated from the middleware), but what I don't know is how to test at that point from where the request is coming, i.e. from which client.
I have control of the client so I could also pass extra acr_values (which I think can be used to pass custom data), but again I don't know how to get them in the OnAuthnRequestCreated event as shown in the code below.
Any help would be much appreciated.
services.AddSaml(Configuration.GetSection("SAML"));
services.AddAuthentication()
.AddWsFederation("adfs", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
//...rest of config (SSO is working)
})
.AddSaml("saml", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
//...rest of config (SSO is working)
options.OnAuthnRequestCreated = request =>
{
//Here I would need to know from which client the request is coming (either by client name or url or acr_values or whatever)
//to be able to perform conditional logic. I've checked on the request object itself but the info is not in there
return request;
};
});
The request parameter is the SAML AuthnRequest object. It doesn't include client information etc.
Instead of the OnAuthnRequestCreated event, in your Startup class you can add some middleware as shown below. You can call GetRequiredService to access any additional interfaces (eg IHttpContextAccessor) you need to retrieve the client information.
app.Use((context, next) =>
{
var samlServiceProvider =
context.RequestServices.GetRequiredService<ISamlServiceProvider>();
samlServiceProvider.OnAuthnRequestCreated += authnRequest =>
{
// Update authn request as required.
return authnRequest;
};
return next();
});
Thanks ComponentSpace for the reply. I didn't get it to work directly with your solution by using app.Use((context, next)) => ... but your comment on GetRequiredService pointed me into the direction to find the solution like below. Basically I'm getting the IHttpContextAccessor which I can then use to parse the query string. I then get the ReturnUrl from this query string and use the IIdentityServerInteractionService to get the AuthorizationContext object, which contains what I need to build my custom logic.
So thanks again for pointing me into the right direction.
//build and intermediate service provider so we can get already configured services further down this method
var sp = services.BuildServiceProvider();
services.AddAuthentication()
.AddSaml("SamlIdp", options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.OnAuthnRequestCreated = request =>
{
var httpContextAccessor = sp.GetService<IHttpContextAccessor>();
var queryStringValues = HttpUtility.ParseQueryString(httpContextAccessor.HttpContext.Request.QueryString.Value);
var interactionService = sp.GetService<IIdentityServerInteractionService>();
var authContext = interactionService.GetAuthorizationContextAsync(queryStringValues["ReturnUrl"]).Result;
//authContext now contains client info and other useful stuff to help build further logic to customize the request
return request;
};
});

Alamofire SSL failure

I know this type of question has been asked many times but it seems like there is an answer but I can not get it working.
In my environment, production is the only place I have a valid SSL certificate. Using Alamofire in my iOS app built against production works great. I don't want to develop/test against production and we can't get a valid SSL cert right now for any other environment.
I found this SO answer from an Alamofire developer suggesting a way to solve this but it is not working for me. When I run my app against non-production, the failure I'm seeing implies that it is using NSURLConnection and not NSURLSession as the proposed solution seems to rely on.
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
Would love it if someone could share their solution (maybe a gist?) on this.
I finally figured it out. The SO answer I had referenced had a small but important bug in it. I submitted an edit for it but will post the working code here:
let manager = Alamofire.Manager.sharedInstance
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = NSURLSessionAuthChallengeDisposition.UseCredential
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = manager.session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
if credential != nil {
disposition = .UseCredential
}
}
}
return (disposition, credential)
}
The issue was that it was not using the singleton instance of Alamofire.Manager. Instead it was creating a brand new instance which was never being used by the Alamofire framework.

How can I read SOAP-Headers and add FaultHeaders to a response sent by an AXIS 2 Web Service

I have a WSDL that defines a custom SOAP-header that the client needs to send and a SOAP-Fault header that the server could send as a response.
Now I have a problem. I cannot for the life of me fathom how to set SOAP-Fault-headers on a response generated with AXIS 2 (Version 1.6.1) or read SOAP-Headers that come with a request.
Can anyone point me in the right direction?
Thank you very much in advance.
If is security related you should look to Rampart.
If not, try looking into
ClientSide:
From your stub, retrieve the ServiceClient via _getServiceClient().
enter link description here
ServerSide:
If I recall correctly is done via MessageContext, so from axiscontext opbtain current message context.
Add custom fault to soap response. This can be done in one of two ways.
1) Simply throwing a Java exception with a message will generate a simple Axis2 fault
Example:
throw new java.lang.UnsupportedOperationException("Please implement " +
this.getClass().getName() + "#SomeOperationName");
Also please note: If you generated your service using the Axis2 WSDL2JAVA utility, the line above will be added to the MyServiceName_Skeleton source for each defined WSDL Operation.
Once the .aar is deployed, connectivity to each operation can be verified using a web browser, e.g. https://server:port/axis2/services/MyServiceName?SomeOperationName.
2) Ensure that the WSDL defines an optional (occurs:0) custom Fault structure. This can be sent to client with any other required (and empty) elements.
Example:
com.some.service.operation.SomeOperationNameResponse_Type OPRT = new com.some.service.operation.SomeOperationNameResponse_Type();
com.some.service.SomeOperationNameResponse OPR = new com.some.service.SomeOperationNameResponse();
.
.
.
if ((rcStatusString.equals("Succeeded")) || (rcStatusString.equals("Warning"))) {
<build happy path response>
} else if (rcStatusString.equals("Failed")) {
final MYFault fault = new MYFault();
final MYFault_Type faultType = new MYFault_Type();
final MYFaultList faultList = new MYFaultList();
final MYFaultList_Type faultListType = new MYFaultList_Type();
faultType.setFaultCode("10100");
faultType.setFaultSubcode("9999");
faultType.setFaultType(FaultType_Enum.SYSTEM);
faultType.setFaultReasonText("Some Operation Failed");
faultType.setSeverity(FaultSeverity_Enum.CRITICAL_ERROR);
//fault.setMYFault(faultType);
faultListType.addMYFault(faultType);
OTHRTYPE.setAValue("");
OPRT.setAValueType(OTHRTYPE);
OPRT.setMYFaultList(faultListType);
} else {
throw new java.lang.UnsupportedOperationException(
"MYSERVICE: [Some Operation] Session: "+sessVal+" Request ID: "+rcRequestId+" Unrecognized Completion Status ["+rcStatusString+"]");
}
OPR.setSomeOperationResponse(OPRT);
return OPR;
}

Zend Framework: Checking if route exists from code

in zend framework, is there anyway i can check if a route exists from code?
example
say the following routes/urls are valid (point to controller/action)
/users
/users/1 // /users?id=1
/users/page/1 /users?page=1
/users/tagged/tagname/page/1 /users?tagged=1&page=1
if the user tries to goto /users/nonexistantpage it should fail. soemthing to check if the user request the url, will it fail, but on the code level.
I believe you're looking for the match() method for the Zend router. See if that helps.
It's kinda old question, but I guess this is what you are looking for:
foreach(Zend_Controller_Front::getInstance()->getRouter()->getRoutes() as $route)
{
$route->match($uri);
}
For those using Zend Framework 2, this is very simple.
Let say we want to check if an URI matches against registered router and redirect the user if this is different from the current url.
$goto = 'http://www.mysite.tld/admin';
$request = $this->getRequest();
$request->setUri($goto);
if ($routeToBeMatched = $this->getServiceLocator()->get('Router')->match($request)) {
$currentRouteMatchName = $this->getEvent()->getRouteMatch()->getMatchedRouteName();
if ($routeToBeMatched->getMatchedRouteName() != $currentRouteMatchName) {
return $this->redirect()->toRoute($goto);
}
}
If you use rewrite router (Zend_Controller_Router_Rewrite), it has a method hasRoute($route_name)
Then if you want to check if route exists anywhere in your application you can check it like that:
Zend_Controller_Front::getInstance()->getRouter()->hasRoute("my_route");