Redirect unauthorized requests to Azure AD for login - asp.net-web-api2

I've got a WebAPI instance running in Azure that is secured with Azure AD. A mobile app connects to this API using bearer tokens, works great. When I try calling the API from the browser, though, it returns a 401 because I'm not logged in. That's true because I'm not presented with a login screen.
My API doesn't have any UI so what I'd want it to do is to forward the user to Azure AD login and return to the API endpoint they were calling after authentication.
If I go to the Azure portal, there's a setting that says "Action to take when the request is not authorized". If I set that one to "Log in with Azure Active Directory", it behaves the way I want it to. But... I have some endpoints which need to be accessed anonymously, and this setting catches all requests, not caring about any [AllowAnonymous] attributes.
So any request to an endpoint labeled Authorize that is not authorized yet should be forwarded to Azure AD login, all others should be allowed.

Add a DelegatingHandler to your web api project and register it in WebApiConfig.cs:
config.MessageHandlers.Add(new UnAuthorizedDelegatehandler());
public class UnAuthorizedDelegatehandler: DelegatingHandler
There you can check for 401 status codes and do the redirect to whatever and also apply a redirect url as querystring parameter.
HttpResponseMessage rm = await base.SendAsync(request, cancellationToken);
if (rm.StatusCode == HttpStatusCode.Unauthorized)
{
// configure the redirect here
return rm;
}

Related

Social Login authentication in an API

I am using Microsoft Owin/Katana and implemented the social login authentication in a Web Forms and MVC application which is working perfectly.
I have a requirement to convert the implementation into an API (controllers). In my MVC application, I am calling this line of code inside the login controller,
HttpContext.GetOwinContext().Authentication.Challenge(properties, AuthenticationProvider);
The user is redirected to the login screen of the provider (i.e. Google, Facebook, Twitter).
I was hoping to achieve the following,
User call /api/login controller of my API and it checks the provider and then using the access key and secret key, it returns the login URL as string or JSON and the consumer of the API will redirect to that URl. This way the secret and access keys are not exposed and just the URL is returned.
The problem is that there is no way I am able to find to get the login request URL of the provider. The Challenge method is void and it just redirects the user which in case of an API is not acceptable.
I have used the following code in a Web API,
var properties = new AuthenticationProperties() { RedirectUri = this.RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
MessageRequest.GetOwinContext().Authentication.Challenge(properties, AuthenticationProvider);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.RequestMessage = MessageRequest;
return Task.FromResult(response);
When I call the API using Postman then it returns the whole HTML of the login page. When I call the API URL directly in the browser then it redirects to the login page correctly but I just want to return the Url of the provider and the consumer should redirect itself.
Is there any way to achieve this?

How signin-google in asp.net core authentication is linked to the google handler?

I went into the source code but I can't see where it's wired to the handler.
In the GoogleExtensions.cs file, I see the
=> builder.AddOAuth<GoogleOptions, GoogleHandler>(authenticationScheme,
displayName, configureOptions);
But I don't understand how the route "/signin-google" calls the handler.
How signin-google in asp.net core authentication is linked to the google handler?
The question can be divided into two small questions .
How user is redirected to the url of /signin-google
How GoogleHandler process the request on /signin-google
How user is redirected to signin-google
Initially, when user clicks the Google button to login with Google Authentication, the browser will post a request to the following url:
https://your-server/Identity/Account/ExternalLogin?returnUrl=%2F
Your server simply redirects the user to Google.com and asks Google to authenticate the current user :
https://accounts.google.com/o/oauth2/v2/auth?
response_type=code
&client_id=xxx
&scope=openid%20profile%20email
&redirect_uri=https%3A%2F%2Fyour-server%2Fsignin-google
&state=xxx
When Google has authenticated the user successfully, it will redirect the user to your website with a parameter of code according to redirect_uri above.
https://your-server/signin-google?
state=xxx
&code=yyy
&scope=zzz
&authuser=0
&session_state=abc
&prompt=none
Note the path here equals /signin-google. That's the first key point.
How GoogleHandler process the signin-google
Before we talk about how GoogleHandler goes , we should take a look at how AuthenticationMiddleware and AuthenticationHandler work:
When there's an incoming request, the AuthenticationMiddleware (which is registered by UseAuthentication() in your Configure() method of Startup.cs), will inspect every request and try to authenticate user.
Since you've configured authentication services to use google authentication , the AuthenticationMiddleware will invoke the GoogleHandler.HandleRequestAsync() method
If needed, the GoogleHandler.HandleRequestAsync() then handle remote authentication with OAuth2.0 protocol , and get the user's identity.
Here the GoogleHandler inherits from RemoteAuthenticationHandler<TOptions> , and its HandleRequestAsync() method will be used by AuthenticationMiddleware to determine if need to handle the request. . When it returns true, that means the current request has been already processed by the authentication handler and there's no further process will be executed.
So how does the HandleRequestAsync() determine whether the request should be processed by itself ?
The HandleRequestAsync() method just checks the current path against the Options.CallbackPath . See source code below :
public abstract class RemoteAuthenticationHandler<TOptions> : AuthenticationHandler<TOptions>, IAuthenticationRequestHandler
where TOptions : RemoteAuthenticationOptions, new()
{
// ...
public virtual Task<bool> ShouldHandleRequestAsync()
=> Task.FromResult(Options.CallbackPath == Request.Path);
public virtual async Task<bool> HandleRequestAsync()
{
if (!await ShouldHandleRequestAsync())
{
return false;
}
// ... handle remote authentication , such as exchange code from google
}
}
Closing
The whole workflow will be :
The user clicks on button to login with Google
Google authenticates the user and redirects him to /signin-google
Since the path== signin-google, the middleware will use HandleRequestAsync() to proecess current request, and exchange code with google.
... do some other things

Token based authentication for both Web App and Web API using Azure AD B2C

Scenario:
Both Web application and Web API need to be authenticated and protected from the server side.
Requirement:
Web application is serving the contents for the browser and browser should be calling Web API directly (i.e. Browser to API).
Question:
Is it possible to authenticate both Web APP and the API using tokens?
Any sample code or clear direction would be highly appreciated.
Normally web applications are authenticated using cookies and APIs are authenticated using tokens.There are some sample projects available here but they are either browser to API (SPA token based) or Server side Web App calling API from server to server.
UPDATE 1
App is saving the TokenValidationParameters and used bootstrapContext.Token within the app controller to grab for server to server communication.
As per #dstrockis, I'm trying to grab the id_token from the Web App soon after the end of validation (not within the app contrller).
I'm using SecurityTokenValidated invoker in OpenIdConnectAuthenticationOptions.Notifications within the Startup class. SecurityTokenValidated receives a parameter of type SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> but I'm not sure where to find the id_token within it. Method is below.
private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
{
return new OpenIdConnectAuthenticationOptions
{
// For each policy, give OWIN the policy-specific metadata address, and
// set the authentication type to the id of the policy
MetadataAddress = String.Format(aadInstance, tenant, policy),
AuthenticationType = policy,
// These are standard OpenID Connect parameters, with values pulled from web.config
ClientId = clientId,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed,
//NEW METHOD INVOKE ************************************
//******************************************************
SecurityTokenValidated = OnSecurityTokenValidated
//******************************************************
},
Scope = "openid",
ResponseType = "id_token",
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
SaveSigninToken = true
},
};
}
//NEW METHOD ************************************
private Task OnSecurityTokenValidated(
SecurityTokenValidatedNotification<OpenIdConnectMessage,
OpenIdConnectAuthenticationOptions> arg)
{
//QUESTION ********************************************************
//How to find the just saved id_token using incoming parameter, arg
//*****************************************************************
return Task.FromResult(0);
}
UPDATE 2
Instead of SecurityTokenValidated, I tried AuthorizationCodeReceived and it's not getting called at all. As discussed here, my redirect url does have an ending slash as well.
Any Ideas?
Our ASP.NET OpenID Connect middleware which supports AAD B2C is built to rely on cookie authentication from a browser. It doesn't accept tokens in a header or anything like that for securing web pages. So I'd say if you want to serve HTML from your web app in the classic way, you need to use cookies to authenticate requests to the web app.
You can definitely get & store tokens within the browser and use those to access your web API, even if you use cookies to authenticate to the web app. There's two patterns I'd recommend:
Perform the initial login using the OpenID Connect Middleware, initiating the flow from the server side as described in the samples. Once the flow completes, the middleware will validate the resulting id_token and drop cookies in the browser for future requests. You can instruct the middleware to save the id_token for later use by using the line of code written here. You can then somehow pass that id_token down to your browser, cache it, and use it to make requests to the API.
The other pattern is the inverse. Start by initiating the login from javascript, using the single page app pattern from the B2C documentation. Cache the resulting id_tokens in the browser, and use them to make API calls. But when the login completes, you can send a request to your web app with the id_token in the body, triggering the OpenID Connect middleware to process the request and issue a session cookie. If you want to know the format of that request, I'd recommend inspecting a regular server side OpenID Connect flow.
Found the answer to my own question and adding here for the future reference.
After a successful validation, id_token can be accessed by invoking the SecurityTokenValidated notification. Code sample is below.
private Task OnSecurityTokenValidated(
SecurityTokenValidatedNotification<OpenIdConnectMessage,
OpenIdConnectAuthenticationOptions> arg)
{
//Id Token can be retrieved as below.
//**************************************
var token = arg.ProtocolMessage.IdToken;
return Task.FromResult(0);
}
However, saving this directly into a browser cookie may not be secure.

How to create identity in MVC app with JWT

I'll try to be explicit.
I have a Front End app (MVC), it can communicate with a Facade Web Api (Resource) and get token from an authentication server.
My problem is I can't create an identity in MVC app. This is mu Startup class.
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
When I try to go to a method controller decorated with [Authorize], I get 401 error instead to be redirected to Login page.
Please, I would appreciate any help, advice or example.
Regards,
Typically, unless your app is doing postback's you do not need to enable the cookie authentication with login path. That is for the oauth password login flow (grant_type) where you are internally authorizing your users against your identity database. If you're redirecting to an external authorization api (like facebook) then you don't need to set a login path in your application since the first authorization endpoint that gets hit is your external callback (after you send them to facebook, they will send them back to your external endpoint). The redirect you are getting is because cookie authentication is registered as active authentication mode so it redirects 401's to the login path you set (overriding other OWIN middleware).
If you want to house your authorization server in house, have a look at the link below, it will at the least get you setup with JWT support -
http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/

Using cookies or tokens with cross domain forms authentication

I am trying to implement authentication using jQuery and Forms Authentication on an ASP.NET MVC 3 web service. The idea is that I'll do a jQuery AJAX post to the web service, which will do Forms Authentication and return a cookie or token, and with each data access call, my web application (jQuery) will use that cookie or token.
What I have -
I have the AJAX call to the ASP.NET Web service set up, and I have the web service set up as follows:
public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(userName, password))
{
return Json(FormsAuthentication.GetAuthCookie(userName, rememberMe), JsonRequestBehavior.AllowGet);
}
else
{
return Json("Authentication Failed", JsonRequestBehavior.AllowGet);
}
}
}
This is working so that if I make the AJAX call with correct credentials, I am returned a cookie in JSON, and if not, I'm returned the auth failed string.
What I don't know - What to do with the JSON cookie once I receive it back. I can store this in HTML5 local storage, but I don't know what part of it (or the whole thing) to send back with my data access calls, and how to interpret it and check the cookie on the web service side. If I shouldn't be using cookies, is there a way to generate and use a token of some kind?
For anyone else who happens to come across, here's how I solved it:
I realized that sending the cookie back via JSON was not necessary. By using FormsAuthentication.SetAuthCookie, an HTTP Only cookie is set, which gets automatically sent with AJAX calls. This way, the server is the only one responsible for the Auth cookie, and can verify the authentication with Request.IsValidated.