How do OWIN Authentication providers work? How would I write a custom one? - asp.net

I'm looking at the source code for Microsoft.OWIN.Security.Google and am a bit confused and overwhelmed at how many classes there are to do such a simple thing (redirect, get a cookie, check it).
Can anyone explain how the various components fit together
Middleware
Extensions
etc
... so that I can write a custom provider

After some google-ing and trying different ideas in debugger I ended up with "copy-paste-edit" :)
here is a brief resume of classes
Extensions - nothing special, a helper:
// instead of using
app.Use(typeof(CustomAuthenticationMiddleware), app, options);
// you can use
app.UseCustomAuthentication(options);
Middlware - methods are used to attach authentication to owin pipeline
AuthenticationProvider - As I understand, this could be overriden outside, to be able to change some logic without rewriting whole thing. Has 2 methods:
Authenticated - is called when handler finishes all authentication in AuthenticationHandler.AuthenticateCoreAsync()
ReturnEndpoint which is called in AuthenticationHandler.InvokeAsync, just before external authetication.
But it appeared absolutely useless, when I tried to customize existing providers (google, facebook,...)
Handler - here is all the OAUTH2 functionality.
ApplyResponseChallengeAsync() - generates AuthorizationEndpoint URL and redirects useragent to authorization server
InvokeAsync() - handles the get to RedirectEndpoint (/signin-google or whatever was set up on authorization server) and returns the user to the starting controller(or callback). It is doing a redirect with all needed cookies set up
AuthenticateCoreAsync() - does all server side calls to authorization server. Creates all Identity.Claims necessary to create appropriate cookies before

Related

OAuth2 using Qt - how to cath redirect_uri using Qt

I am writing an OAuth2 client using Qt. For the first stage of authorization, I use qml WebView: a link opens in it, where the user enters data and confirms his actions, after which the google service calls redirect_uri (there is a user scheme like "com.mycompany.myappname://", which I give google when registering an OAuth2 client). Google specifies the result in the parameters in this redirect and sends the authorization code (it looks something like this: "com.mycompany.myappname://?code=4/ABCDEFG&scope=email openid&authuser=1&prompt=consent", where the "code" parameter is used for the following authorization stage - obtaining an access_token). Now, to catch this redirect, I use the Java Activity to which my scheme is attached. Activity reads parameters and sends them to C++ using public static native method. Next, in C++, the second stage of OAuth2 authorization passes.
Question: Is it possible to catch redirect_uri using Qt methods? In order to completely abandon Java and thereby make this client cross-platform for Android and IOS (in IOS, if I'm not mistaken, redirect_uri is also used with the result of the first stage of OAuth2 authorization).
Thanks in advance!
You can use QOAuthHttpServerReplyHandler something like in this official example.
Then the redirect_url might be 127.0.0.1 and then you can handle the payload/url parameters from an appropriate signal from QOAuthHttpServerReplyHandler.

Resource based (Imperative) authorization won't enter the handler

Scenario:
I have an API with .net core 2.2
On top my controller I authorize access using IdentityServer4 with an Attribute
Inside one of my endpoints I want to authorize access to a method only in some cases
I implemented resource based authorization inside my endpoint just like it's shown in microsoft documentation.
It didn't work.
I put a breakpoint inside my authorization handler and tried debugging, but when this handler should be called, it is not.
I mean that when the following line runs
var authorizationResult = await _authorizationService
.AuthorizeAsync(User, Document, "EditPolicy");
the Handler should be called, but that never happens.
Did anyone have the same problem?
So in the end the problem was due to the registration of the service in the startup.cs.
I was using TryAddScope, by changing to AddScope it worked fine.

Spring-Security-OAuth2 - how to add fields to access token request?

I have a Spring Boot application, that is using Spring Security with OAuth 2.0. Currently, it is operating against an Authentication Server based on Spring Example code. However, running our own Auth Server has always been a short-term target to facilitate development, not a long-term goal. We have been using the authorization_code grant type and would like to continue using that, irrespective of the Auth Server implementation.
I am attempting to make changes to use OAuth 2.0 Endpoints in Azure Active Directory, to behave as our Authentication Server. So far, I have a successful call to the /authorize endpoint. But the call to get the /token fails with an invalid request error. I can see the requests going out.
It appears that parameters that Azure states as mandatory are not being populated in the POST request. Looking at the Azure doco, it expects the client_id to be defined in the body of the message posted to the endpoint, and that is not added, by default, by Spring.
Can anyone point me in the right direction for how I can add fields to the Form Map that is used when constructing the Access Token request? I can see where the AccessTokenRequest object is being setup in OAuth2ClientConfiguration....
#Bean
#Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
protected AccessTokenRequest accessTokenRequest(#Value("#{request.parameterMap}")
Map<String, String[]> parameters, #Value("#{request.getAttribute('currentUri')}")
String currentUri) {
DefaultAccessTokenRequest request = new DefaultAccessTokenRequest(parameters);
request.setCurrentUri(currentUri);
return request;
}
Should I be trying to define the map in a request.parameterMap spring property? If so, I'm not too sure how that works.
Or should I be using one of the interfaces defined in the AuthorizationServerConfigurerAdapter class?
I have the information to include when sending the AccessTokenRequest, I just don't know the best way to configure Spring to include it? Thanks for any help.
Actually, I found this out. I needed to change the client authentication scheme. Simply adding the following to my application properties added the client_id to the form....
security.oauth2.client.clientAuthenticationScheme=form
If you're using yaml, then yaml-ize it. Thank you Spring!

Spring Security OAuth2 Behind a Proxy Server

There seem to be many examples of Spring Security OAuth2, but most of them run on localhost at some specific set of ports. I was able to get my application working with ports specified for my AuthorizationServer and my ResourceServer. The next step I needed to take was move this application behind a proxy server, but the application stopped functioning. The main issues seem to be path related, but I'm struggling with lack of examples on how to accomplish the task of moving OAuth2 Spring behind a proxy server. I've focused on overriding the WhitelabelApprovalEndpoint, but I'm not sure if this is what is required.
I was able to create a controller that is nearly identical to the WhiteLabelApprovalEndpoint, but do not know how to adapt it to accommodate being behind a proxy.
#Controller
#SessionAttributes("authorizationRequest")
public class ApprovalEndpoint {
#RequestMapping("/oauth/confirm_access")
...
private static String TEMPLATE = "<html><body><h1>OAuth Approval</h1>"
+ "<p>Do you authorize '${authorizationRequest.clientId}' to access your protected resources?</p>"
+ "<form id='confirmationForm' name='confirmationForm' action='authorize' method='post'><input name='user_oauth_approval' value='true' type='hidden'/>%csrf%%scopes%<label><input name='authorize' value='Authorize' type='submit'/></label></form>"
+ "%denial%</body></html>";
...
The only change I made to the class was to update the form action string, making the path relative by replacing
action='${path}/oauth/authorize'
with
action='authorize'
This allows the POST to go to the correct URL
http://localhost/proxy/stuff/javaPath/oauth/authorize
instead of
http://javaPath/oauth/authorize
The latter doesn't map when submitted through Apache (the frontend proxy). But it would seem that this creates other problems in the Java application, because this results in the error
error="invalid_request", error_description="Cannot approve uninitialized authorization request."
I see that this exception is thrown in the AuthorizationEndpoint when the authorizationRequest is null. This looks like it should be handled by my custom class having SessionAttributes set properly, but updating the just the path that I'm POSTing to seems to break this.
May be you already solved it but posting the answer as it may help someone.
It is because authorize end point URL (domain + path(including proxy)) should be consistent. I mean either it should be 'localhost' or your proxy path but it should be consistent.
As OAuth uses session internally and later fetches it from the same path (when the POST happens) . So if the URL changes (POST) it wont get the session then it throws Cannot approve uninitialized authorization request.
For my case ,I was using the authorize end point as:
https://mydomain/myapp/oauth/authorize?grant_type=authorization_code&client_id=clientid&redirect_uri=http://localhost:8181&response_type=code
but in the properties I was having :
server:
session:
cookie:
path: /appProxy
context-path: /myapp
port: 8081
After successful authorization when POST is done on it tries to fetch the session from /appProxy/myapp instead of /myapp and resulting in Cannot approve uninitialized authorization request.
So to solve this, I can either remove Session.cookie.path property or run Oauth server on https://mydomain/appProxy/myapp/oauth/authorize to make it consistent.

ASP.Net custom authentication with existing server

We have an existing user licensing server that is running via PHP. It allows for creation of users, checking if the provided username and password is valid, and updating a user.
We are creating a new ASP.Net website and want it to use this existing user PHP scripts/database to restrict access to portions of the ASP.Net website. Also there are web services that use the same login and password via basic authentication that we need to access as well from the ASP.Net server.
I am looking for a way for .Net to use the remote PHP scripts to validate login. And I need a way for the users login id and password to be available so I can use them to communicate with those existing web services from the ASP.Net server on their behalf.
Does anyone know how to go about getting this sort of thing done. Or any good tutorials or blogs?
Thanks!
It's possible to run PHP and ASP.NET on the same server, and even in the same web application. You can also create .NET code that runs before and/or after each PHP request (with an HttpModule).
PHP under IIS just has a separate HttpHandler that invokes the cgi-bin process.
If you want to call a PHP page from an ASP.NET page, one approach is to use Server.Execute() -- although web services would certainly be cleaner from an architectural perspective.
Beyond that, for the actual authentication/authorization part of your question, the approach depends on the specifics of your implementation. You can certainly do things like share cookies between PHP and .aspx.
unfortunatly they are different languages and php scripts cannot be used in an asp.net site. You would have to recreate your classes(scripts) but what you can do is use your existing database if its in mysql or any other. That's the best you would be able to do as far as I know.
If those PHP web services respect some industry standard such as SOAP for example, you can simply consume them by generating strongly typed client proxies. If not, well, then you still have the good old WebClient which allows you to send HTTP requests and read responses. It's as simple as:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "username", "john" },
{ "pwd", "secret" },
};
var result = client.UploadValues("http://foo.com/login.php", values);
// TODO: do something with the result returned by the PHP script
}
Have you tried using stored procedures instead of PHP scripts? That way you don't have to write multiple instances of the same code and it can be used in .NET and PHP.

Resources