How to add external login in .net web api 2? - social-networking

I'm trying to add external login with template from MVC5, Web API2 with method
Task<IHttpActionResult> AddExternalLogin(AddExternalLoginDTO model)
The method need only one parameter ExternalAccessToken - token from FB, Google, ...
But ticket for some user data is still null
AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);
Where is the problem?

Related

Hooking up IdentityServer4.AccessTokenValidation and Reference Tokens with ASP.NET Core Identity

I am try to build out an Angular 6 application backed by a ASP.NET Web API back end. The application authenticates users against a separate Identity Server 4 that federates Azure AD ultimately returning a Bearer reference token.
From a login and then authenticate (the token) perspective, everything is working. The user access the site, gets redirected to Azure AD, logs in, and gets redirected back to the Angular 6 app. For the API calls, the token is injected into the header and the ASP.NET Core authentication middleware validates the token and returns the data.
services
.AddAuthentication(options => {
options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(options => {
options.Authority = AuthClient.SsoBaseUrl;
options.RequireHttpsMetadata = false;
options.ApiName = AuthClient.SsoClientName;
options.ApiSecret = AuthClient.SsoClientSecret;
});
My problem is that I am trying to incorporate ASP.NET Core Identity and I am unsure of where/how to tie the claims principal returned via AddIdentityServerAuthentication.
In a previous version (ASP.NET Framework 4.7) of this application, we used Ws-Federation which redirected back to ExternalCallbackLogin() in AccountController which executed the usual AuthenticationManager.GetExternalLoginInfoAsync() and then SignInManager.ExternalSignInAsync() and then (if required) AppUserManager.CreateAsync() and AppUserManager.AddLoginAsync().
This code basically checked the [AspNetUserLogins] table for the provider specific key (from the claims) to map to a user in the [AspNetUsers] table.
With the change to IdentityServer4.AccessTokenValidation I cannot figure out where to put this logic. Since I am using reference tokens it does not look like the JwtBearerEvents (specifically the OnTokenValidated event) is not being raised. In fact, it does not look like there are any Introspection events...??
I am tried testing the logic in a test endpoint that called the above "Manager" methods (technically it was the updated for ASP.NET Core Identity equivalent methods) but that is not working either.
For example, the very first call to SignInManager.GetExternalLoginInfoAsync() returns null.
What am I doing wrong?

IdentityServer (OpenId Connect) authentication on asp.net webform

i'm trying to use IdentityServer3 to authenticate users on an asp.net webform application with owin pipeline (no mvc)
All the examples suggest to configure the application like a mvc application, but in this way the application doesn't perform a redirection to the IdentityServer Login page when i try to access to a protected resource of the webform application
this is my client (webform) configuration
[Startup.cs]
app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationMode = AuthenticationMode.Active,
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
//LoginPath = new PathString ("/Account/Login") //<--enabling this path property redirect me to a local login page but not to the external IdentityServer login page
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
Authority = "https://localhost:44300/identity", //<<--url of the identityServer
ClientId = "webform",
ClientSecret = "ciccio",
Scope = "openid profile roles",
RedirectUri = "https://localhost:44302/", //<-- url of the client (to come back ofter the login)
ResponseType = "id_token",
SignInAsAuthenticationType = "Cookies"
});
i'm sure i forgot something
It looks, you missed app.UseStageMarker(PipelineStage.Authenticate); at the bottom of your Startup.cs.
The reason is that (according to the documentation):
Owin middleware components (OMCs) run at the latest stage, which by default is PreHandlerExecute. The stage markers are used to make them to run earlier.
The complete sample including cookie mapping and support for logout is in IdSrv repo
posting this just in case someone else's still looking a solution for the same problem like we did recently, finding this question without an answer
as workaround i tried these solution suggested in this article but they DON'T WORK
Login page on different domain
both solutions in the example page force a "brutal" redirection to the IdentityServer, but doing so, the IdentityServer doesn't show you the login page because the performed request is not in the correct form
the "signin=xxxxxx" parameter attached to the querystring, needed to legitimate the login request is not present.
i've tried to use an mvc client as well, in this case every requests made to a protected resource (with Authorize attribute) is redirected to the IdentityServer in the correct way (the url where the user should be redirected to log-in page is in this format https://localhost:44300/identity/login?signin=4f7ee6677aec2d2aca6ebc40e4d13720) with the "signin" parameter attached to the querystring
this behaviour doesn't happen in a webform application (at least with the same configuration used in a mvc application)
I'm sure that something is missing, something like a "httpModule" that intercepts the "http 401 not authorized response" and composes a correctr url to redirect towards the login page of the IdentityServer
forgive me for my english

Azure AD permissions and the PUT verb

We have an ASP.Net MVC web site that talks to a WebAPI service. This is authenticated at the application level by using application authentication in Azure AD.
This all works fine for GET and POST operations, but the same tokens don't work for PUT operations, is there any good reason for this?
EDIT - example of how we are calling the service.
We're using an HttpClient to make a call to the WebAPI
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return await _httpClient.PutAsync(url, content);
Then we get back a HttpResponseMessage which has status code of Unauthorized.
We're not calling the Graph API directly but using the AAD instance to authenticate the calling of one service by another.

Authorize using Oauth2 Token in Asp.Net WebAPI

Hello I am building an ASP.Net WebApi. First I authorized the WebApi using basic authentication .net membership provider and the Thinktecture Identitymodel.
var authConfig = new AuthenticationConfiguration();
authConfig.AddBasicAuthentication((username, password) => Membership.ValidateUser(username, password));
config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
I guess it couldn't be made any easier.
To take it a step further i've set up the Thinktecture IdentityServer which provides me with oauth2 tokens. My question is how do i validate the access tokens the client sends me (the WebApi) with the identity server?
I've been looking into the AddJsonWebToken methods the IdentityModel provides, but I can't really figure out wich uri (endpoint) in the identityserver i should call to validate the token. Probaply I'm just completly lost here and missing the point, any help would be greatly appriciated!
To summarize:
How do I validate the access_tokens i receive in my WebApi and how do I wire that to the [Authorize] attribute?
Simply call AddJsonWebToken in you web api config - and add the issuer name, signing key and realm uri.
There is no need to call idsrv for validation.
Here's a sample:
http://leastprivilege.com/2012/05/26/thinktecture-identitymodel-and-asp-net-web-api/

how to get user specified data with Asp.net Web API

I created MVC4 application with internet application template, added an API controller with authorize attribute.
How can I make api controller action return user specified data?
Currently I am using WebSecurity.GetUserID to get Userid, I have Userid in the data table.
After compiling the application, if I call api controller action first, I will have following error message:
You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call
should be placed in an _AppStart.cshtml file in the root of your
site.
if I go to MVC controller action frist, and come to api action again, it works fine.
I am wondering how to solve this issue, and what is the best practice to handle user specified data with web api and MVC4, Thanks.

Resources