Dotnetnuke OAUTH/OWIN external Login with facebook - asp.net-web-api2

I developed a module for Dotnetnuke(8) with WebAPI 2 Endpoints via the DNN API
This API is consumed by an Android-App.
To access the functions that are populated via the API, the user needs to authenticate.
I have already implemented the JWT (Json Web Token) Authentication with the WebAPI and login with username/password from the App works fine with this method.
Now I also want to allow users to login via their facebook-login and to get their name and email and photo from their facebook profile to authenticate and authorize them via the DNN-Users-Database and allow/disallow them to use the API functions.
I googled around a lot and read a lot of blogposts and articles about external authentication in the last few days. The following are very interesting and already gave me ann good insight how the process may work:
http://bitoftech.net/2014/08/11/asp-net-web-api-2-external-logins-social-logins-facebook-google-angularjs-app/
Registering Web API 2 external logins from multiple API clients with OWIN Identity
https://www.asp.net/web-api/overview/security/external-authentication-services
but I cannot really find out (and it seems i do not really understand) if and how this can be made working with my dnn-API and the JSON-WebToken Auth Method in my project.
If anybody can help to get me in the right direction, your help is highly appreciated.
Thanks in advance and kind regards
Don
EDIT: The DNN-API gives all the JWT-Functionality I just need to define the api paths and functions. e.g:
'
<Route("{controller}/{action}/{p1}")>
<AcceptVerbs("GET")>
<AllowAnonymous>
Public Function userInf(ByVal p1 As String) As HttpResponseMessage
Dim response As New HttpResponseMessage
Dim pID As Integer = DotNetNuke.Entities.Portals.PortalController.Instance.GetCurrentPortalSettings.PortalId
Dim objUserInfo As New DotNetNuke.Entities.Users.UserInfo
objUserInfo = DotNetNuke.Entities.Users.UserController.Instance.GetUserById(pID, CInt(p1))
If Not objUserInfo Is Nothing Then
If objUserInfo.UserID > 0 Then
response = Request.CreateResponse(System.Net.HttpStatusCode.OK, JsonConvert.SerializeObject("Username: " & objUserInfo.Username.ToString))
Else
' Not logged in
response = Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "Not found")
End If
Else
' Not logged in
response = Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "Not logged in")
End If
response.Headers.Add("Access-Control-Allow-Origin", CORS) ' <- Allow CORs !!!!
' response.Headers.Add("Access-Control-Request-Method", "*")
Return response
End Function
The Api Path for the DNN Web-API is for authentication:
example.com/DesktopModules/JwtAuth/API/mobile/Login
where I pass the username and password in the request-body as a json-object
(Documentation on dnnsoftware[dot]com / docs / administrators / jwt /)
This all works as expected. The thing now is how to make work the facebook login as an external login work together with my JWT-AUTH

Web api doing authentication by itself, yout need to create OAuthAuthorizationServerOptions and configure web api to use methods, there is an example of how web api token based auth works with standart Bearer token.
There ApplicationOAuthProvider its a class which generates token for inhereting from OAuthAuthorizationServerProvider.
To call method from your token generator you need to get to the path /api/token and request will automaticly give you token and user Claims, which you will define in your token generator.
public void ConfigureOAuth(IAppBuilder app)
{
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
var oauthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
Provider = new ApplicationOAuthProvider(),
};
// Token Generation
app.UseOAuthAuthorizationServer(oauthServerOptions);
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
Hope this help.

Related

How can I change the 'typ' of a token provided by Azure AD?

I have a project setup like this:
React frontend
-> authenticates against...
Identity Server
-> which redirects to...
A Microsoft login
I'm using a Clients Credential Provider and it works great - the IS4 redirects to MS login, and then gets redirected with the access token back, which is then passed on to the React app.
Now, I've been tasked with creating a feature to change the user's password. I'm trying to do this by sending the old+new password to IS4, and then calling the MSGraphClient, but I couldn't make it work.
I've tried the Username/Password provider, because I have all the info needed, but I need to change stuff on the ActiveDirectory settings to make my app public. But even then, I don't like that solution.
I've also tried with the On-behalf-of provider, this is the code:
var scopes = new[] { "User.Read",
"Directory.AccessAsUser.All" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "~~";
// Value from app registration
var clientId = "~~";
var clientSecret = "~~";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// This is the incoming token to exchange using on-behalf-of flow
var oboToken = HttpContext.Request.Headers.First(h => h.Key == "Authorization").Value.ToString().Replace("Bearer ", "");
var cca = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
// DelegateAuthenticationProvider is a simple auth provider implementation
// that allows you to define an async function to retrieve a token
// Alternatively, you can create a class that implements IAuthenticationProvider
// for more complex scenarios
var authProvider = new DelegateAuthenticationProvider(async (request) => {
// Use Microsoft.Identity.Client to retrieve token
var assertion = new UserAssertion(oboToken);
var result = await cca.AcquireTokenOnBehalfOf(scopes, assertion).ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
var graphClient = new GraphServiceClient(authProvider);
And it kinds of work, because the request is made, but the server throws an error:
AADSTS5002727: Invalid JWT header type specified. Allowed types: 'JWT','http://openid.net/specs/jwt/1.0'.
I checked my token on JWT.io, and the typ is at+jwt... Why? Why is MS sending me a type of token that it doesn't support? How can I change it from my side so it's a plain JWT?
Thanks for any advice, and any other possible solution for this.
To resolve the error "AADSTS5002727: Invalid JWT header type specified. Allowed types: JWT,http ://openid.net/specs/jwt/1.0" , please try the below if helpful:
Please check the version of .Net core you are currently using to generate the token. Try using .Net core 2.2 with IS4.
Try setting IdentityServerOptions.AccessTokenJwtType to empty string or JWT on IdentityServerOptions.
In the mentioned code, replace var oboToken variable directly with the value of token.
var oboToken = "JWT_TOKEN_TO_EXCHANGE";
Please note the below point from MsDoc :
Don't attempt to validate or read tokens for any API you don't own,
including the tokens in this example, in your code. Tokens for Microsoft services can use a special format that will not validate as
a JWT, and may also be encrypted for consumer (Microsoft account)
users
If still the error persists, try upgrading clients to a new token validation library that works with the new style tokens.
Please check whether the below links give you any pointer to resolve the issue:
JWT Token always Invalid · Issue #905 · openiddict/openiddict-core · GitHub
IdentityServer .Net Core 3.0 & Owin/Katana Token validation · Issue #3705 · IdentityServer/IdentityServer4 · GitHub

ServiceStack API aspnet core with Azure AD B2C returns 401 for request even with bearer token

I have a working ServiceStack API that authenticates against a AzureAD tenant. We are trying to move this to start using Azure B2C. The application is build with c# and runs on net 5.0. I've managed to change the configuration to use the 'correct' config. I'm then using Postman to get my access token from my tenant suing the authorization code flow.
However, when i make a request to the api, the response is always a 401 status code.
Where in the servicestack code can I put a break point to see why this failure is happening? I have tried multiple places in our AppHostConfigurator.cs/AppHost.cs files, but the break points doesn't appear to display why a 401 is being sent back as a response. I'm sure it's something related to wrong claims/roles expected etc, maybe the Azure ADB2C application being setup incorrectly, but obviously i need to know exactly so that i can resolve.
I'm setting up the authentication like this:
private static void ConfigureAuthentication(IAppHost host)
{
var authProviders = new List<IAuthProvider> {new NetCoreIdentityAuthProvider(host.AppSettings)};
if (host.AppSettings.GetAllKeys().Contains("AzureAdB2C"))
{
var debugMode = host.AppSettings.Get(nameof(HostConfig.DebugMode), false);
var azureSettings = host.AppSettings.Get<AzureAdB2COptions>("AzureAdB2C");
var jwt = azureSettings.GetB2CJWTProviderReader(debugMode);
jwt.PopulateSessionFilter = (session, payload, request) =>
{
if (session.Email == null && payload.ContainsKey("upn") && payload["upn"].Contains("#"))
session.Email = payload["upn"];
if (session.UserName == null && payload.ContainsKey("unique_name"))
session.UserName = payload["unique_name"];
};
authProviders.Add(jwt);
}
var auth = new AuthFeature(() => new AuthUserSession(), authProviders.ToArray())
{
HtmlRedirect = "/account/signin",
HtmlLogoutRedirect = "/account/signout",
IncludeAssignRoleServices = false,
IncludeRegistrationService = false
};
// remove default service authentication services
auth.ServiceRoutes.Remove(typeof(AuthenticateService));
host.Plugins.Add(auth);
}
We are using swagger as well to call the API (which works as expected). This question is more about that requests that are submitted with a bearer token.
thanks
Please refer to this existing answer for examples of how to validate why a 3rd Party JWT Token is invalid with ServiceStack's JWT Auth Provider.

identityserver 4 get current user's access_token

I am having trouble getting my current user's access_token.
Here is my setup:
QuickstartIdentityServer (QIS) in aspnet core, identity and EF storage
API (API) in NodeJs. Validates jwt tokens in header against QIS.
SPA angular app that works great with QIS and API and is out of the scope of this question
In a section of the QuickstartIdentityServer (QIS) site (user details page), I would like to call an API endpoint using an access_token to authenticate the request. I am struggling to retrieve the current user's access_token from my QIS site. Whenever I call HttpContext.GetTokenAsync("access_token") I get a null value. I have seen this section of IdSrv4 documentation: https://identityserver4.readthedocs.io/en/release/quickstarts/5_hybrid_and_api_access.html?highlight=gettokenasync but it seems to apply to an MVC client and not my own identity server.
Anyone could shed some light on how to get my user's access_token ?
Thanks
EDIT
Here is a starting point to try to explain better my issue:
https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/6_AspNetIdentity/src/IdentityServerWithAspNetIdentity
Starting from this QIS project, I would like to get the logged in user's access token. So for instance, if I edit HomeController to add this call:
public async Task<IActionResult> Index()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
return View(accessToken);
}
I would then be able to call my NodeJS API with this token in the Auth Header.
Hope this explains better my issue.
So I managed to authenticate myself w/ my API using a dedicated Client using client credentials grant and the following call to get an access_token:
var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
var tokenClient = new TokenClient(disco.TokenEndpoint, clientId, clientSecret);
var tokenResponse = await tokenClient.RequestClientCredentialsAsync(scope);
Then I can add to my request header to API the access_token returned in tokenResponse:
using(var client = new HttpClient()) {
client.SetBearerToken(tokenResponse.AccessToken);
...
// execute request
}
The downside is that I can't "impersonate" the current currently logged on IS on API side.

Acquiring an Access token by using JWT used for AzureBearerAuthentication

I have a WebApi app that is using Windows Azure Active Directory Bearer Authentication to authenticate users. After the user is authenticated, I want to query Azure's Graph Api to get more information about the user.
I have a solution that works, but seems very hacky. I read the Authorization header and strip out the bearer part, and then I use AquireToken to get the new token:
var authHeader = HttpContext.Current.Request.Headers["Authorization"];
var tokenMatch = Regex.Match(authHeader, #"(?<=^\s*bearer\s+).+$", RegexOptions.IgnoreCase);
var result = authInfo.AuthContext.AcquireToken(resourceId, authInfo.Credential,
new UserAssertion(tokenMatch.Value));
return result.AccessToken;
There has to be a better way, but I've tried AcquireToken many different overloads and this was the only way I could get it to work. I tried AcquireTokenSilent, which works in my client app because there is a token in the TokenCache, but when I try in the WebApi, there doesn't seem anywhere to implement a TokenCache.
That is indeed somewhat hacky :-) see https://github.com/AzureADSamples/WebAPI-OnBehalfOf-DotNet for a way in which you can retrieve the incoming token through the ClaimsPrincipal. It boils down to passing TokenValidationParameters = new TokenValidationParameters{ SaveSigninToken = true } in the options and retrieving in from your controller or filter code via
var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;

Accessing Shoeboxed API with Google Apps Script (OAuth v2)

I'm trying to initiate a session with the Shoeboxed API via Google Apps Script. I hoped I could use Apps Script internal library to access it but I'm having issues. Here is my attempt:
function testAPI() {
var consumerKey = '';
var consumerSecret = '';
var oauthConfig = UrlFetchApp.addOAuthService('shoeboxed');
oauthConfig.setAccessTokenUrl(
'https://id.shoeboxed.com/oauth/token');
oauthConfig.setRequestTokenUrl(
'https://id.shoeboxed.com/oauth/token');
oauthConfig.setAuthorizationUrl(
'https://id.shoeboxed.com/oauth/authorize');
oauthConfig.setConsumerKey(consumerKey);
oauthConfig.setConsumerSecret(consumerSecret);
var options = {
'oAuthServiceName' : 'shoeboxed',
'oAuthUseToken' : 'always'
};
var url = 'https://api.shoeboxed.com/v2/user';
var response = UrlFetchApp.fetch(url, options);
Logger.log("Response: " + response.getContentText());
}
It's failing at the point where it attempts to fetch user data via the API url with an authorization failed message. I'm not sure what I'm doing wrong. Information about the API and OAuth can be found here: https://github.com/Shoeboxed/api/blob/master/sections/authentication.md
New method:
It looks like that API requires OAuth2, but the UrlFetchApp.addOAuthService method only works with the older version of OAuth.
There's a new method ScriptApp.newStateToken() which can be used in combination with OAuth2, but it requires more manual/explicit control over the OAuth2 steps. It generates a state token.
A minor detail on that method:
Note that when you construct URLs, the state token should passed as a URL parameter on the .../authorize URL, not embedded as a URL parameter within the .../usercallback URL.
For example:
You would want to redirect the user to:
https://id.shoeboxed.com/oauth/authorize?client_id=<your client id>&response_type=code&scope=all&redirect_uri=<your site>&state=<CSRF token>
where redirect_uri is:
https://script.google.com/macros/d/1234567890abcdefghijklmonpqrstuvwxyz/usercallback
When the user clicked authorize, Shoeboxed should redirect them to:
https://script.google.com/macros/d/1234567890abcdefghijklmonpqrstuvwxyz/usercallback?state=<CSRF token>
oauth2 support for the shoeboxd API has just been added to the cEzyOauth2 Google Apps Script library.
You can copy the pattern to your app and include the library as described here
It uses the statetoken as described by Steve Lieberman, and takes care of the oauth2 conversation, token handling and refreshing automatically.