After implementing to office 365 able to login but getting Bad Request? - asp.net

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

Related

"System.Net.HttpListener" not available in IAppBuilder properties

I am developing a web app with mix authentication (Owin Token Based and Windows authentication). I have implemented Owin token based authentication and want to implement windows authentication for the users which are marked as active directory users.
In Owin middleware, I want to get requesting user's windows username. I am getting object in OwinContext.Request.User.Identity. However, OwinContext.Request.User.Identity.Name is always blank string.
I found that I should add below lines in startup.cs:
var listener = (HttpListener)app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
However, I am getting key not found exception. "System.Net.HttpListener" is not present in Properties array. I have installed Microsoft.Owin.SelfHost, Microsoft.Owin.Host.HttpListener. However, I am still getting the error.
Any help is greatly appreciated.
Thanks,
GB
For me issue was that project was started as shared lib, not a web app.
Solution was to add a line into .cspro file after <ProjectGuid> line.
<ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
Then you dont need to add HttpListener explicitly, just reload project and follow this instructions starting from Properties edition part.
Enabling Windows Authentication in Katana
You can access principal the same ways:
Get the user in an OWIN middleware:
public async Task Invoke(IDictionary<string, object> env)
{
OwinContext context = new OwinContext(env);
WindowsPrincipal user = context.Request.User as WindowsPrincipal;
//...
}
Get the user in a Web API Controller:
// In a web api controller function
WindowsPrincipal user = RequestContext.Principal as WindowsPrincipal;
UPD: List of Visual Studio Projects GUIDs

Get URL information in Startup

In an asp.net MVC 5 project I'm using a katana owin based middlewere to handle the authentication. Inside the Start.cs file I have the Startup class with the Configuration method.
Is there a way to get the full URL of the request inside the Configuration method? I need to get the last part of it to be stored in a cookie
public void Configuration(IAppBuilder app) {
app.UseCookieAuthentication(new CookieAuthenticationOptions { ... }
// something here to get the full URL
// other authentication code here
}
Startup runs outside of the request-cycle. In fact, it only runs once, and then multiple successive URLs can be serviced before it ever runs again (when AppPool recycles, server restarts, etc.)
Long and short, even if you could access the URL, it wouldn't do you any good because it would simply be the first random URL that was accessed, which may or may not be applicable to whatever you're trying to do here.

ASP.NET Web API v2 and logging all errors/exceptions with ELMAH

Despite spending hours searching the net I couldn't find a solution to this problem. Being a noob to Web API v2 this is probably a really easy question for someone with more experience.
I have a clean MVC project updated to use Web API v2. I've installed a number of ELMAH packages via Nuget.
When working with the normal Home controller in MVC if I put an invalid page e.g. /Home/test it would generate a 404. Elmah in turn captures this and I know just from the logs what pages might be broken etc.
I want to transfer this level of logging over to the API controller. The logging does work, but I have to throw an exception to the controller to get something logged in Elmah.
I'm guessing that things like 404/415 errors are classed as 'handled' exceptions, but I'm only getting un-handled exceptions logged.
At any rate what I want is for ANY errors on the API controller to be logged. This way I can monitor how the API is being used and any errors caused by calling clients. Errors might be 404s, 415 for unsupported data types and so on. That way if there are any problems with posted data from a client I can easily see the response that would have been passed back.
Thanks in advance!
WebApi.config:
Public static void Register(HttpConfiguration config)
{
...
config.filters.add(new Elmah.Contrib.WebApi.ElmahHandleErrorApiAttribute());
}
Filter.config:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new Elmah.Contrib.Mvc.ElmahHandleErrorAttribute());
filters.Add(new HandleErrorAttribute();
}
It turns out that 404 errors are treated a bit differently in Web API, they bypass the usual request pipeline and are sent directly to the browser before ELMAH knows anything about them.
So in order to log 404 errors with ELMAH you need to add a 'catch all' route as the last route in your WebApiConfig to log the errors manually.
I've just updated the post and included a working example solution - http://jasonwatmore.com/post/2014/05/03/Getting-ELMAH-to-catch-ALL-unhandled-exceptions-in-Web-API-21.aspx
You need to register an exception logger with Web API as well. Check out this awesome post: http://www.jasonwatmore.com/post/2014/05/03/Getting-ELMAH-to-catch-ALL-unhandled-exceptions-in-Web-API-21.aspx

OpenIdConnect Owin login with google

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

authentication in singalR selfhost server- and web client in SSL

I have a singalR self host server that is hosting my singalR in a console application on https
I am using this packages to self host:
Install-Package Microsoft.Owin.Hosting -pre
Install-Package Microsoft.Owin.Host.HttpListener -pre
Install-Package Microsoft.AspNet.SignalR.Owin
i have a web client which is backed by WebApi, I can connect to my selfhosted singalR from my webclient and send messages however I would now like to add authentication to this, which means only logged in users can send messages to my selfhosted singalR server.
I used [Authorize] attribute before my method
[Authorize]
public void Test(string test)
{
Console.WriteLine(test);
}
I have my web client authentication done via forms authentication however after logging in sucessfully in my webclient, when i do call singalR method, i recieve javascript error
Uncaught Value cannot be null. Parameter name: user
It tells that my method is protected but somehow my user is not passed to my self hosted singalR server, What is missing here?
Support for this was introduced with SignalR 1.0, you can read a little about that on David Fowlers blog. The problem is, with it being so new it's a little sparsely documented.
I'm not exactly sure what's going on in your application at the moment but you can find a similar question already on Stack Overflow which might help you get on the right track: Integrating SignalR with existing Authorization
Basically, you can create a SignalR Attribute that implements IAuthorizeHubConnection and IAuthorizeHubMethodInvocation, then decorate your Hubs/Methods that you want authorized.
public class HubAuthorizeAttribute : Attribute, IAuthorizeHubConnection, IAuthorizeHubMethodInvocation {
public virtual bool AuthorizeHubConnection(HubDescriptor hubDescriptor, Microsoft.AspNet.SignalR.IRequest request) {
IAuthorizationProvider authorizationProvider = DependencyResolver.Current.GetService<IAuthorizationProvider>();
return authorizationProvider.IsAuthorizedController(hubDescriptor.Name);
}
public virtual bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext) {
IAuthorizationProvider authorizationProvider = DependencyResolver.Current.GetService<IAuthorizationProvider>();
return authorizationProvider.IsAuthorizedAction(hubIncomingInvokerContext.MethodDescriptor.Hub.Name, hubIncomingInvokerContext.MethodDescriptor.Name);
}
}
Alternatively, you could add the HubAuthorizeAttribute as a HubPipeline Module to Globally require Authorization.
var globalAuthorizer = new HubAuthorizeAttribute ();
GlobalHost.HubPipeline.AddModule(new AuthorizeModule(globalAuthorizer, globalAuthorizer));
I've asked a similar question a few times over the last days in the SignalR JabbR chat and haven't got any answer.
When I was about to post my question here I found your question and this other one. Unfortunately, from the answer given there a couple of weeks ago, it seems like SignalR itself provides no Authentication support, so that's a huge problem for many selfhosted applications (we were intending to use Integrated Windows Authentication with SignalR...)

Resources