OpenIdConnect Owin login with google - asp.net

I'm trying to set up OWIN OpenIdConnect to authorize with google provider.
I have used:
http://blogs.msdn.com/b/webdev/archive/2014/03/28/owin-security-components-in-asp-net-openid-connect.aspx
as a tutorial for that, but it's designed for Azure AD provider, so i changed necessary information to google:
Startup.Auth:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(
new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "xxx.apps.googleusercontent.com",
Authority = "https://accounts.google.com",
RedirectUri = "https://localhost:44300/"
});
}
This causes redirect loop error in my browser.
To be sure, I have changed provider to Azure and it works perfectly.
Do you have idea how to fix that? In perfect I would like to integrate it with default membership provider, but for now I'm trying to get it work somehow.
EDIT:
I have found out that problem is in response_mode. Azure returns with POST, and google is returning GET.
Do you have any idea how to:
Make google returns with POST
Make OWIN OpenIdConnect read GET value property? Its separated from a url by '#', not '?'.

OWIN OpenIdConnectHandler only supports POST.
https://accounts.google.com/.well-known/openid-configuration
Doesn't specify response modes, so I am not sure if google+ signin does.

I followed an alternative approch without OWIN, as I tried to avoid using a lot of different libraries.
I basically bult a lightweight implementation especially for authentication against google (see description / documentation):
http://www.dominikamon.com/articles/3091/oidc-lightweight-library-for-aspnet.html
I've uploaded the code to Github:
https://github.com/DominikAmon/Amon.cc.OIDC

Related

How to implement Authorization Code flow with Owin

I'm using IdentityServer4 and trying to connect an MVC app up for authentication. I currently have things working by using the implicit flow, but I have run into the problem that my access tokens are expiring and there is no refresh token support for implicit. I also read today that implicit was designed for js apps before browsers got good, and that it is not as secure as authorization code flow.
SO. I would like to get my app working with the authorization code flow. I can't find any one simple solution for this using owin. I assume there is a nice and widely automated way to have owin take care of swapping the code for an access token and all that. After extensive research online I found this snippet of code that seems to be talking about what I'm doing:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
...
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "https://schemas.quickstarts.com/roles"
}
...
});
Does anyone have any examples or other info about getting owin to do all this?
Relevant info:
IdentityServer4
Client is .Net Framework 4.6

Headline steps required to extend an existing (Azure based) ASP.NET forms auth app to use ADFS

I have an existing ASP.NET app deployed on Azure. It has its own auth system, essentially a u/p database table and creation of a forms auth cookie:
public void LogIn(LoginDetails userLogin, bool createPersistentCookie)
{
var info = (CustomPrincipalInfo) userLogin;
var timeout = 30;
if (createPersistentCookie)
timeout = 60*24;
var cookie = info.CreateAuthenticationCookie(DateTime.Now, timeout, createPersistentCookie);
HttpContext.Current.Response.Cookies.Add(cookie);
}
public static HttpCookie CreateAuthenticationCookie(this CustomPrincipalInfo info, DateTime current, int timeout, bool remember)
{
var serializer = new JavaScriptSerializer();
var userData = serializer.Serialize(info);
var ticket = new FormsAuthenticationTicket(
1, info.Email, current, current.AddMinutes(timeout), remember, userData);
var secureTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, secureTicket) { Domain = FormsAuthentication.CookieDomain };
if (remember)
cookie.Expires = current.AddMinutes(timeout);
return cookie;
}
Most of the customers just register details, log in using their details with us etc, but we've been asked to integrate with a customer that uses ADFS for SSO. My reading around the topic suggests that we need to run an ADFS server, integrate our app with it, and then engage in a process of establishing trust between their ADFS server and ours
I'm curious to know if, given that it's hosted on Azure already, there is anything we can do with Azure/AAD to skip the "run an ADFS server" part, because we don't really have any infrastructure for doing so. The app startup routine is older school Global.asax style, using castle windsor for DI/IoC:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
DependencyRegistrar.Register();
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
InitializeInfrastructure();
MigrateDatabaseSchema();
DataAnnotationConfig.RegisterValidationAttributes();
BundleConfig.RegisterBundles();
}
The resources I'm turning up are generally older stuff:
ADFS with existing ASP.Net MVC App - this mentions a separate blog discussing server 2012r2 in depth - we do have such a sevrer, but are looking to retire it rather than add another reason to carry on using it/have to replace it with a newer one
Azure Websites SSO using ADFS brought up an azure sample that seems to imply Azure can help us avoid having to run a dedicated ADFS server, but again the sample is ~9 years old
The most recent one I found seemed to be a reasonable description of the problem I face, but I couldn't understand the answer (which basically seemed to be "read this link, scroll down a bit" - reading the link didn't smack me in the face with anything obviously "this is what you have to do")
Resources surrounding using ADFS on Azure seem massively involved; I don't feel like I need/want/to pay for load balancers, multiple storage accounts, DMZs and proxies etc.. This is literally so that one user at one customer can sign in a handful of times a month
What set of steps do I take to create a really basic ADFS SSO auth mechanism in this existing app, hook in to how it IDs users so that when joe.bloggs#customer.com comes and signs in via ADFS I can become aware of the email address that is signed in and give him his forms auth cookie like anyone else, and leverages some Azure based facility so that I don't have to run an ADFS server?
There are two ways to do this.
The basic problem is that your credentials are in a DB and neither AAD nor ADFS supports this.
You could run identityserver4 in Azure and configure idsrv4 to authenticate against the DB. Then you could federate idsrv4 with the partner ADFS.
Or you could move the users into Azure AD via the Graph API and then federate AAD with ADFS.

Is it possible to restrict access to REST API built using Web API 2?

I built a REST API using ASP.NET Web API 2, so I could deliver data from a backend database to my applications running on any platform (mobile, web, desktop etc) However up until now, I simply call the website with the controller I need data from and that's it, it sends back the JSON string in the response.
But, the data is kind of special, and there is nothing to prevent another developer from simply calling the controllers and getting back the exact same data and building their own application around it.
My question is - is there anyway to restrict access to the API so that only my applications can get valid response from the server. (i.e. prevent other developers from using my REST API)
I already read these documentation Security, Authentication, and Authorization in ASP.NET Web API I'm just not sure which of these scenarios apply to me, or if any will do what I am asking.
EDIT - Another piece of info, my web service is running on Azure in case it is relevant.
Did you happen to check token based authentication?Please go through https://stackoverflow.com/a/38670221/4868839 and https://www.youtube.com/watch?v=rMA69bVv0U8 must be a good to start with.
there are different way to validate your web api.
Authentication Filters in ASP.NET Web API 2
using you can customise your authentication filter
you can refer sample Reference link
Token Based Authentication using ASP.NET Web API 2, Owin, and Identity
//App_Start/Startup class
public void ConfigureAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/v1/accesstoken"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(AppConfiguration.AccessTokenExpireDuration),
Provider = new SampleOAuthProvider() // class that override your method
};
// Token Generation
app.UseOAuthBearerTokens(OAuthServerOptions);
}
You can find reference from inherits Default implementation of IOAuthAuthorizationServerProvider used by Authorization
i hope it sholud helps you thanks.

After implementing to office 365 able to login but getting Bad Request?

We have implemented Office 365 Azure AD authentication for our application. However, after office 365 authentication, it is going in continuous loop till it throws an errors "Bad Request"
Apparently this solved issue:
https://github.com/KentorIT/owin-cookie-saver
Taken verbatim from the site:
There is a bug in Microsoft's Owin implementation for System.Web. The
one that is being used when running Owin applications on IIS. Which is
what probably 99% of us do, if we're using the new Owin-based
authentication handling with ASP.NET MVC5.
The bug makes cookies set by Owin mysteriously disappear on some
occasions.
This middleware is a fix for that bug. Simple add it before any cookie
handling middleware and it will preserve the authentication cookies.
The process I followed, which appears to work so far is:
Using Project / Manage NuGet properties, add Kentor.OwinCookieSaver
In Startup.Auth.cs, inside public partial class Startup, before app.UseCookieAuthentication(new CookieAuthenticationOptions());, add app.UseKentorOwinCookieSaver();
abridged code sample
public partial class Startup
{
// LOTS OF STUFF
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseKentorOwinCookieSaver();
app.UseCookieAuthentication(new CookieAuthenticationOptions());
UPDATE:
After this change the issue still exists

Authenticate with ADFS inside Console App silently

I have a c# console application that references the ADAL.net library (Microsoft.IdentityModel.Clients.ActiveDirectory version 2.19.208020213)
The purpose of the console app is to consume a HTTP endpoint which is protected with ADFS.
The implementation of the ADFS auth is as follows....
var uc = new UserCredential("user", "password");
var ctx = new AuthenticationContext("https://sts.example.com/adfs", false);
var token = ctx.AcquireToken(ClientResourceUri, ClientId, uc);
The call to AcquireToken throws an exception...
This method overload is not supported by
'https://sts.example.com/adfs/'
Calling AcquireToken without the UserCredential object, and instead providing a redirectUri works, but throws up a dialog prompting for username and password, which is unsuitable as the console app will be executed in a non user environment...
var redirect = new Uri("https://example.com/arbitaryRedirect");
var token = ctx.AcquireToken(ClientResourceUri, ClientId, redirect);
//dialog is shown
If i switch to the latest alpha release of the adal.net library (3.6.212041202-alpha)
the error is more revealing...
MSIS9611: The authorization server does not support the requested
'grant_type'. The authorization server only supports
'authorization_code' or 'refresh_token' as the grant type.
However, mining google yields very little.
Is it actually possible to authenticate silently against ADFS?
Would i be correct in assuming (based upon answers in other posts) that the correct approach is to use WsTrustChannelFactory instead?
If not, what is the best approach?
It is possible using ADAL 3.x and ADFS in Windows Server 2016, with pretty much the same code you posted. Combinations of older versions of either ADAL or ADFS won't work.
Alternatively, you can use WS-Trust - which is significantly harder to handle, but can get the job done.

Resources