Why is ServiceStack JwtAuthProvider being invoked when service is specified to authenticate with GithubAuthProvider? - authentication

Exploring the ServiceStack authentication providers for the first time. Have gradually built up a test project by adding BasicAuthProvider and when that worked, added GithubAuthProvider. The last one added was JwtAuthProvider and that works as well. When I retested authentication with any of the previous authentication providers such as Github, for example, I find that the JwtAuthProvider lambda function for CreatePayloadFilter is still being invoked. This was not expected.
The AuthFeature plugin is as follows:
Plugins.Add(new AuthFeature(
() => new PartnerWebSession(),
new IAuthProvider[] {
new JwtAuthProvider(appSettings) { ... },
new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
new GithubAuthProvider(appSettings)
}));
I have created BasicHello, GithubHello and JwtHello service models with different end points for use with each of the authentication providers with routes:
/basic/{Name}
/github/{Name}
/jwt/{Name}
The AuthenticateAttribute has been attached to the Service classes designed to work with these models and they each specify the Provider to use, e.g.:
[Authenticate(Provider = "basic")]
public class BasicAuthentication : Service
{
public object Any(BasicHello request)
{
return new BasicHelloResponse { Result = $"{nameof(BasicAuthentication)} says Hello, {request.Name}!" };
}
}
Testing using Visual Studio debug and Chrome browser. Have ensured that no previous cookies JWT are hanging around from previous tests by clearing cookies for all time. I enter the URL:
http://localhost:52070/api/github?name=stephen
This takes me to the ServiceStack rendered authentication screen with login dialogue and "Sign In with Github" button. Click the "Sign In with Github" button which takes me to the "Sign in to GitHub" page provided by GitHub. Successfully authenticate, and then code execution hits a breakpoint I've set in CreatePayloadFilter lambda of the JwtAuthProvider.
I did not expect this. Is this an error or am I doing something wrong?

If you have the JWT AuthProvider registered it populates the successful Auth Response with a populated JWT Token that encapsulates the partial authenticated session.
The stateless client JWT Token (i.e. instead of server session cookies) can then be used to make authenticated requests after a successful OAuth Sign In.

Related

How to configure Azure AD authentication in Hybrid ASP.NET Core MVC (backend) and Vuejs SPA (frontend)?

My application is a hybrid approach where use ASP.NET Core MVC as my backend. I have various controllers which my front end uses to pull data from our database and also to do API calls on MS Graph. I am using the following program.cs file to get the authentication initiated when a user first logs on to the site:
//authentication pipline
builder.Services.AddHttpContextAccessor();
var initialScopes = builder.Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
builder.Configuration.Bind("AzureAd", options);
options.Events = new OpenIdConnectEvents
{
//Tap into this event to add a UserID Claim to a new HttpContext identity
OnTokenValidated = context =>
{
//This query returns the UserID from the DB by sending the email address in the claim from Azure AD
string query = "select dbo.A2F_0013_ReturnUserIDForEmail(#Email) as UserID";
string connectionString = builder.Configuration.GetValue<string>("ConnectionStrings:DBContext");
string signInEmailAddress = context.Principal.FindFirstValue("preferred_username");
using (var connection = new SqlConnection(connectionString))
{
var queryResult = connection.QueryFirst(query, new { Email = signInEmailAddress });
var claims = new List<Claim>
{
new Claim("UserID", queryResult.UserID.ToString())
};
var appIdentity = new ClaimsIdentity(claims);
context.Principal.AddIdentity(appIdentity);
}
return Task.CompletedTask;
},
};
}).EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
//Add Transient Services
builder.Services.AddTransient<IOneDrive, OneDrive>();
builder.Services.AddControllers(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();
builder.Services.AddRazorPages().AddRazorPagesOptions(options =>
{
options.Conventions.AllowAnonymousToFolder("/Login");
options.Conventions.AuthorizeFolder("/");
options.Conventions.AuthorizeFolder("/files");
}).AddMicrosoftIdentityUI();
// Add the UI support to handle claims challenges
builder.Services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();
builder.Services.AddRequiredScopeAuthorization();
In the Azure AD portal my application is registered as a web app. So when a user initially goes to the site they are redirected to https://login.microsoftonline.com/blahblah to get the login process started. This is automated by the Azure AD identity platform. Then once the login occurs they are redirected to localhost where the VueJS spa is loaded (localhost:43862). My spa uses various axios requests to the controllers and they pull data and vue router loads components. However, my issue is say the user needs to relog in because the cookie is expired or they logged out in another tab. The next axios request made by the expired session does not redirect the user to Azure login screen but instead results in an CORS error. So I need to get my axios requests to force the page redirect to Azure AD login screen (which probably is the worst idea since CORS policy is resulting in error) or have it return a redirect to localhost/login which is my own custom login screen with a button to Azure AD login and shouldnt impact CORS. So how do I intercept this Azure AD redirect to Azure AD login and replace with my own?
I have also tried to return a 401 error code so I could check for that in my axios request but to no avail it does nothing. If I put a breakpoint there it does hit this code but it does not change the status code of the response and I still get 302. My code for that was to try and add to the event :
OnRedirectToIdentityProvider = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
}
My other ideas was maybe I should set my CORS policy to allow redirects from login.microsoft.com? Or would this be bad practice?
I can answer part of your question... First, for our API application which is protected by Azure AD, what the API should do is validating the request whether it contained a correct access token in the request header, if yes, give the response, if no, then give error like 401 or 403. A normal API application shouldn't have a UI to let users sign in. Anyway, if you want to expose an API in an MVC project, it's OK, but for API itself, it shouldn't have a UI.
Let's see sample below, I had a .net 6 web api project, and here's my program.cs:
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddMicrosoftIdentityWebApiAuthentication(builder.Configuration);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
And it requires configurations in appsetting.json.
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "azure_ad_client_id",
"ClientSecret": "client_secret",
"Domain": "tenant_id",
"TenantId": "tenant_id",
//"Audience": "api://azure_ad_client_id_which exposed_api" // here I used the same azure ad app to expose API, so I can comment this property
},
And this is the Controller:
[ApiController]
[Route("[controller]")]
[Authorize]
public class WeatherForecastController : ControllerBase
{
[RequiredScope("Tiny.Read")]
[HttpGet]
public string Get()
{
return "world";
}
}
I had an Azure AD app, and I exposed an API like this:
I also add this API for the same Azure AD app.
Then let's do a test. When I call this API directly, I will get 401 error:
If I used an expired token within the request, I will also get 401 error:
But if I used a correct token(go to https://jwt.io to decode the token, we should see it containing correct scope, for me its "scp": "Tiny.Read",), I will get response:
And till now, the API part had finished. Let's see the client SPA. For SPA, you should integrate MSAL so that you can make your users to sign in via Azure AD, and generate the access token for calling MS graph API or your own API. The code for generating access token should be the same but you should set different scope for different API. In my scenario, my API required a scope Tiny.Read, then I should set in my client App.
Here's an screenshot for generating access token in react. You need to set the scope in your code.
Now you have the method to generate access token, you already know the API url. Then you can send request to call api, using AJAX, using fetch, or something else, sending an http request is ok. And in the calling api part, you also need to handle the response. If the response code is 401, then you need to do some logic, maybe redirect to the sign in page. And you said you had trouble here, you met CORS issue. I can't answer this part. I think it depends on how you redirect to Azure AD sign in page. I'm afraid you can take a look at this sample to learn how to sign in users and call graph api.

How to handle redirects to auth provider from the backend in Fable Elmish SPA

I have an AspNetCore backend api (in F# with Giraffe) that uses AzureAD authentication with Microsoft.AspNetCore.Authentication.AzureAD.UI, with stateful session store, and https only cookies.
The frontend is an Elmish SPA compiled to js with Fable.
If I just type into the url bar a protected endpoint of my backend, everything works correctly, if not already signed in, I get redirected to the login.microsoft endpoint, with the clientID and so on, where upon successful signin, the original request completes and I get the response of my protected endpoint.
But if I try to access the same endpoint from the SPA code, eg.: with fetch, or with Fable.Remoting, if not logged in, the backend still redirects but the redirected request to login.microsoft no longer works.
With Fable.Remoting there is a CORS header, that the login endpoint refuses. If I send fetch with nocors, there is a 200 OK response from the login endpoint BUT no response body (eg no html code for the login page) and seemingly nothing happens.
I just have no idea how this should be handled on the SPA side, and could not really find anything about it. Why does the backend include a CORS header in the redirect if initiated from Fable.Remoting vs if initiated from the browser url bar? What is wrong with the fetch-ed response that there is no response body?
I can write just js code into my client, but could not even figure out how would this be handled in a pure js SPA.
Also tried the whole thing in production, to remove the webpack devServer proxy from the equation, but everything stays the same.
First, create "signin" and "signout" routes in Giraffe:
/// Signs a user in via Azure
GET >=> routeCi "/signin"
>=> (fun (next: HttpFunc) (ctx: HttpContext) ->
if ctx.User.Identity.IsAuthenticated
then redirectTo false "/" next ctx
else challenge AzureADDefaults.AuthenticationScheme next ctx
)
/// Signs a user out of Azure
GET >=> routeCi "/signout"
>=> signOut AzureADDefaults.AuthenticationScheme
>=> text "You are signed out."
Next, you need to configure the webpack "devServerProxy". This is how my current Fable app is configured:
// When using webpack-dev-server, you may need to redirect some calls
// to a external API server. See https://webpack.js.org/configuration/dev-server/#devserver-proxy
devServerProxy: {
// delegate the requests prefixed with /api/
'/api/*': {
target: "http://localhost:59641",
changeOrigin: true
},
// delegate the requests prefixed with /signin/
'/signin/*': {
target: "http://localhost:59641",
changeOrigin: true
},
// delegate the requests prefixed with /signout/
'/signout/*': {
target: "http://localhost:59641",
changeOrigin: true
}
},
This will allow you to provide a sign-in link from your SPA:
a [Href "/signin"] [str "Sign in"]
Now when the user loads your app, you can immediately try to pull back some user info (this route should require authentication). If the request (or any other) fails with a 401, you can prompt the user to "Sign in" with your sign-in link.
Lastly, your Azure app registration for your dev environment should point back to the port of your Web Api (which it sounds like yours already does).

ServiceStack Authentication IsAuthenticated always false for users authenticated via facebook

Hi am trying to use OAuth authentication FacebookAuthProvider provided by servicestack
var AppSettings = appHost.AppSettings;
appHost.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new CredentialsAuthProvider(AppSettings),
new FacebookAuthProvider(AppSettings),
new GoogleAuthProvider(AppSettings)
}));
I have implement custom AuthEvents and I have access to authorized user data
but after RedirectUrl happens in endpoint session is empty and IsAuthenticated property is false
In the same time from Controller I can see that created session successfully saved in Cache
This scenario occurred only if user doesn't login in facebook in the browser yet, but for user that already logged in facebook, authentication works fine
What am I doing wrong ?
Thanks in advance!
Updates:
Scenario for repsoducing:
ensure that you didn't loged in facebook in browser (open facebook.com and log out if need)
run web app (project which created with template mvcauth)
try to login via facebook
3.1. for first attempt you will be redirected to https://www.facebook.com/login.php? page for specify your facebook account credentials
after first attempt you will be returned to web app page /Account/Login#s=1 but User.Identity.IsAuthenticated = false in AccountController.Login and you still unauthorized.
after second attempt you will finally successfully logged in
At the same time after first attempt Session with user data will be created and saved in Cache, it looks like after redirecting from page 'https://www.facebook.com/login.php' а new session being created without auth data, but for second attempt we successfully login, maybe the core of issue is redirection from 'https://www.facebook.com/login.php'
In order to be able to use ServiceStack.Auth in MVC and vice-versa you'll need to register the NetCoreIdentityAuthProvider which provides integration between ServiceStack Authenticated Sessions and ASP.NET Core's Claims Principal, e.g:
public void Configure(IAppHost appHost)
{
var AppSettings = appHost.AppSettings;
appHost.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new NetCoreIdentityAuthProvider(AppSettings), /* Use ServiceStack Auth in MVC */
new CredentialsAuthProvider(AppSettings), /* Sign In with Username / Password */
new FacebookAuthProvider(AppSettings),
new GoogleAuthProvider(AppSettings),
new MicrosoftGraphAuthProvider(AppSettings),
}));
appHost.Plugins.Add(new RegistrationFeature()); //Enable /register Service
//override the default registration validation with your own custom implementation
appHost.RegisterAs<CustomRegistrationValidator, IValidator<Register>>();
}

Why is my implementation of SSO using Ember-Simple-Auth with Auth0 getting stuck in a redirect loop?

I have an ember application that uses the Auth0 Ember Simple Auth addon to use the Ember-Simple-Auth functionality with Auth0's Lock.js. Recently I have been trying to implement single-sign-onfunctionality, such that if a user logs into a login portal application, their session will be preserved for other applications on the same domain, and they will not need to log in repeatedly. However my implementation of SSO is resulting in an infinite redirect loop between my login logic and Auth0's endpoint.
I have enabled SSO in the Auth0 application settings. My login is implemented in a few blocks.
My route.js contains a beforeModel() method which contains:
if (!get(session, 'isAuthenticated')){
// Forward to the login action
}
My login action:
login() {
var session = get(this, 'session');
session.authenticate('authenticator:myauthenticator', { authParams: { scope: 'openid' } });
}
This grabs the session object, and calls my custom authenticator. So far, this is basically just ember-simple-auth boilerplate, and complies with the examples supplied in the Auth0 Ember-Simple-Auth documentation.
Where I run into trouble is my custom authenticator. The base authenticator is here. You can see that it handles basic login logic easily, including showing the Auth0 lock when a user isn't authenticated. However it has no logic for handling the kind of SSO-session checking that I want to implement. So I implemented a custom authenticator as below, using examples provided by Auth0 for (basically) this exact scenario (you can see their examples [here], I'm using a slightly altered version)3:
authenticate(options) {
return new Ember.RSVP.Promise((res) => {
// the callback that will be executed upon authentication
var authCb = (err, profile, jwt, accessToken, state, refreshToken) => {
if (err) {
this.onAuthError(err);
} else {
var sessionData = { profile, jwt, accessToken, refreshToken };
this.afterAuth(sessionData).then(response => res(this._setupFutureEvents(response)));
}
};
var lock = this.get('lock');
// see if there's a SSO session available
lock.$auth0.getSSOData(function(err, data) {
if (!err && data.sso) {
// there is! redirect to Auth0 for SSO
options.authParams.callbackOnLocationHash = true;
lock.$auth0.signin(options.authParams, authCb);
} else {
// regular login
lock.show(options, authCb);
}
});
});
}
This behaves mostly as I would expect it to. When I log in with an existing session from another SSO-enabled app on the same domain, if (!err && data.sso) resolves to true, and lock.$auth0.signin(options.authParams, authCb) is called. However, this signin logic is not working as intended. Auth0.signin calls the Auth0.authorize method, which generates a target URL that looks something like:
https://mydomain.auth0.com/authorize?scope=openid&response_type=token&callbackOnLocationHash=true&sso=true&client_id=(MyClientIdHash)&redirect_uri=localhost%23access_token%3(MyAccessToken)%26id_token%3(MyIdToken1).(MyIdToken2).(MyIdToken3)token_type%3DBearer&auth0Client=(MyAuth0Client)
My application is then redirected to this URL for authorization. I get a 302 and am redirected back to the callback URL (my root page). Because there is a new page transition, if (!get(session, 'isAuthenticated')) is hit again. It returns false, and so the same logic repeats itself, looping indefinitely.
Does anyone have any insight on what I might be doing incorrectly here? The authorize endpoint seems to behave as if I were being authenticated, but then the authentication is never actually triggered. I've debugged through this code fairly extensively but seen no obvious red flags, and I've followed provided examples closely enough that I'm not sure what I would change. I'm not entirely sure where the failure to authenticate is happening such that get(session, 'isAuthenticated') is false.

Is this a bug in ServiceStack / Authentication?

Trying to use ServiceStack for authentication, and have it re-direct to a login page as follows:
Plugins.Add(new AuthFeature(
() => new CustomUserSession(), //Use your own typed Custom UserSession type
new IAuthProvider[] {
new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
new TwitterAuthProvider(appSettings), //Sign-in with Twitter
new FacebookAuthProvider(appSettings), //Sign-in with Facebook
new DigestAuthProvider(appSettings), //Sign-in with Digest Auth
new BasicAuthProvider(), //Sign-in with Basic Auth
new GoogleOpenIdOAuthProvider(appSettings), //Sign-in with Google OpenId
new YahooOpenIdOAuthProvider(appSettings), //Sign-in with Yahoo OpenId
new OpenIdOAuthProvider(appSettings), //Sign-in with Custom OpenId
}, "http://www.anyURIhereisignored.com"));
However the URI argument in this case "http://www.anyURIhereisignored.com" is simply ignored.
Looking at the class definition for AuthFeature, I see that the htmlRedirect param is declared as optional with a default value of "~/login", however it appears that it is always using that value and ignoring whatever was passed in. It seems that although the htmlRedirect value gets set initially to the passed URI, somehow internally it is never using that, instead always defaulting to "~/login". Is anyone else experiencing the same issue?
If you're using MVC4 and your controllers are inheriting from the ServiceStackController<> as per the ServiceStack doco, then you may want to try overriding the LoginRedirectUrl property:
public override string LoginRedirectUrl
{
get { return "/Account/Login?redirect={0}"; }
}
This will redirect any unauthenticated requests for secured actions to the login url composed from the specified value.
You should also make sure you remove the ASP.NET membership modules from the web.config if you want to use ServiceStack auth in MVC.
I have a custom URI set as "~/account" and it is working fine. I tried changing it to google and the results was as you are looking for:
https://www.google.co.uk/?redirect=http://localhost/secure
Have you overridden the redirect in the attribute that indicates authentication is required ie.
[Authenticate(ApplyTo.All,"~/login")]
?