How to secure my Restful api created in the play framework - authentication

I want to add user authentication to my restful api that I have created using the Java based Play! framework.
I currently have the Web based (browser accessed) app secured using the 'secure module' Details here: http://www.playframework.org/documentation/1.1/secure
Can I use the same module for authentication for when the restful apis are called directly via http requests?
If not, I would appreciate some pointers to tutorials/module for integrating another auth method (hopefully one that can apply to both web app access from browser and also http api access).
PS It would be nice to avoid doing HTTPS and digest if possible.

If you are already using a username/password mechanism adding http basic authentication for your API calls should not be difficult. You can create an interceptor that does something like:
public class ApiInterceptor extends Controller
{
#Before
static void checkAccess() {
if ( request.user == null || request.password == null) {
unauthorized();
}
boolean canAccess = .... ;// check user and password here
if ( !canAccess ) {
unauthorized();
}
}
}
But this means that you need to use SSL since the username and password go in clear text over http.

Related

Ktor Keycloak Acess Token Route Protection

I'm using a server that authenticates through keycloak. In keycloak I have created a realm and am able to get an Access token as a response. This access token gets fed now into my Ktor application.
However, I'm not quite sure how to protect routes in an easy manner. I want to have some protected routes that have a authenticate("keycloakOAuth"){} scope around it which handles validating the access token and refreshing using the refresh token if the access token is expired.
Currently I have keycloak inside Ktor configured as this:
authenticate("keycloakOAuth") {
get("login") {}
route("/callback") {
// This handler will be executed after making a request to a provider's token URL.
handle {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()
if (principal != null) {
val response = principal as OAuthAccessTokenResponse.OAuth2
call.respondText { "Access token: ${response.accessToken}" }
} else {
call.respondText { "NO principal" }
}
}
}
}
This works fine because when I go to login I'm getting sent to the Keycloak login page and I can login. When I logged in the callback executes and I get my Access Token back.
When I'm trying to protect routes however, some odd stuff happens. I know that I need to validate the incoming JWT token. But I have no clue how to given the Ktor capabilities. The examples are also of little help, since they are quite vague.
Currently I have something like this:
authenticate("keycloakOAuth") {
get("/testAuth") {
val principal = call.authentication.principal<OAuthAccessTokenResponse.OAuth2>()
if(principal != null) {
call.respondText("Authenticated!")
} else {
call.respondText("Unauthenticated...")
}
}
}
But my application will always send me to the login page and then callback page, even though I am sending the Bearer token when I'm testing this call.
My question is:
How do I protect routes in a manner that they need a valid token, with the same syntax that Ktor uses (like authenticate(){}). Do I need to configure JWT for this?
When you request one of the routes under authenticate, the full cycle of OAuth authentication is triggered. This is because the Authentication plugin is designed so a client sends credentials and gets authenticated for each request. For some reason, OAuth integration was implemented on top of the Authentication plugin hence such unexpected behavior.
To solve your problem you can have only /login and /callback routes restricted. In the callback's handler save user ID and tokens in a session or in any other storage for future use. For other routes, you can check manually the fact that a user is authenticated and then use tokens from storage to acquire protected data from the resource server. For convenience, you can create some extension functions to minimize the amount of boilerplate code. Unfortunately, there is no built-in functionality to make it work out of the box.
You don't need to configure JWT for this.

How to change default callback of the Microsoft authentication provider login?

In my ASP.Net Core app, I have implemented Microsoft External Login. I now wish to override the default login callback, which is listed by documentation to be https://localhost:5001/signin-microsoft, if of course running on localhost and on that port. The instructions on here then state that the callback override would be something like this: https://contoso.azurewebsites.net/.auth/login/microsoftaccount/callback.
I am a bit confused on where the callback is meant to be implemented. At the moment I have ExternalLoginCallback() callback method implemented in a base Controller class. But from looking at the above example, it doesn't look like it should be part of a controller.
Should the callback be inside Startup.cs, a Controller, or some other file I am not currently aware of?
The instructions on here then state that the callback override would be something like this: https://contoso.azurewebsites.net/.auth/login/microsoftaccount/callback.
That is related to built-in authentication and authorization support in Azure App service . Do you host your app in Azure App service ?
If yes :
If you enable the Authentication and authorizationfeature of the app service , that means you are using the built-in authentication and authorization support in Azure . That feature will take over the authentication and authorization of you application , that means authentication and authorization still works even you delete the external Azure AD authentication codes in your application . Then you could just :
Use Authentication and authorizationfeature of the app service , delete the Owin Microsoft Account authentication middleware related codes .
Disable Authentication and authorizationfeature of the app service, use Microsoft Account external login( Microsoft.AspNetCore.Authentication.MicrosoftAccount package) .
If no :
Then you should follow document : Microsoft Account external login . You can config the callback url by :
microsoftOptions.CallbackPath = "/home/about";
But if you are using the ASP.NET Identity template with Microsoft Account external login . After Microsoft authentication , asp.net will check whether user's identity exists in database . Since ASP.NET Core 2.1 and later provides ASP.NET Core Identity as a Razor Class Library. If you want to redirect user to another page after authentication , you can :
Scaffold Identity in ASP.NET Core projects: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2&tabs=visual-studio
After that ,modify the redirect url in Areas.Identity.Pages.Account.Login.cshtml.cs:
public IActionResult OnPost(string provider, string returnUrl = null)
{
returnUrl = "/home/contact";
// Request a redirect to the external login provider.
var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}

Simple custom authenticator in JAX-RS

In JAX-RS (or Jersey) REST service, I'm trying to make custom authentication for my users in database.
Currently I have #GET annotated method which should interact with user asking for credentials just like it is done in Spring framework with authentication provider - no custom login form, just plain HTTP login with browser popup form.
Currently I can handle HTTP Basic Access Authentication provided in header, but I need to ask for credentials before accessing content interactively and then make token-based authentication on this base.
I have to keep the application light-weight but I don't know how can this "easy" task be done..
Edit: I found something in Wildfly configuration (I'm using 9 Final version) but I don't know how to use it for login using datasource..
If you already can handle HTTP Basic authentication, then you only need to get a a "login form" from the browser? We solved this by implementing an javax.ws.rs.ext.ExceptionMapper and overriding toResponse(Throwable ex). Our app throws a NotAuthenticatedException which gets mapped to javax.ws.rs.core.Response.Status.UNAUTHORIZED. Then we add a response header appropriately:
#Provider
public class RESTExMapper implements ExceptionMapper<Throwable>
{
#Override
public Response toResponse(Throwable ex)
{
//our application maps a not logged in exception to javax.ws.rs.core.Response.Status.UNAUTHORIZED in this Pair
Pair<Integer, ObjectMap> ret = buildResponse( unwrap( ex));
ResponseBuilder rb = Response.status( ret.left()).entity( ret.right()).type( "application/json");
if( ret.left() == UNAUTHORIZED.getStatusCode())
return rb.header( HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"YOUR SERVICE NAME\"").build();
else
return rb.build();
}
The important part is setting the response header if the user is not logged in, that makes the browser display the HTTP Basic Login Dialog.

OWIN/OAuth2 3rd party login: Authentication from Client App, Authorization from Web API

I am trying to create a Web API that allows the API's clients (native mobile apps) to login using a 3rd party cloud storage provider. I'm using the following general flow from Microsoft:
Here is what I am trying to achieve:
I am using the default ASP.NET Web API Visual Studio template with external authentication, along with the OWin.Security.Providers Nuget package for Dropbox login functionality, and the existing built-in login functionality for Google (Drive) and Microsoft (OneDrive).
The issue I'm having is that the built-in functionality all seems to do the authentication and authorization as part of one flow. For example, if I set up the following in Startup.Auth.cs:
DropboxAuthenticationOptions dropboxAuthOptions = new DropboxAuthenticationOptions
{
AppKey = _dropboxAppKey,
AppSecret = _dropboxAppSecret
};
app.UseDropboxAuthentication(dropboxAuthOptions);
... and navigate to this url from my web browser:
http://<api_base_url>/api/Account/ExternalLogin?provider=Dropbox&response_type=token&client_id=self&redirect_uri=<api_base_url>
I am successfully redirected to Dropbox to login:
https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=<id>&redirect_uri=<redirect_uri>
... and then after I grant access, am redirected back to:
http://<api_base_url>/Help#access_token=<access_token>&token_type=bearer&expires_in=1209600
... as you can see the token is part of that, so could be extracted. The problem is that the client needs to be the one navigating to Dropbox and returning the authorization code back up to the Web API, and the Web API would send the authorization code back to the third party to get the token which would then be returned to the client... as shown in the diagram above. I need the ExternalLogin action in the AccountController to somehow retrieve the Dropbox url and return that to the client (it would just be a json response), but I don't see a way to retrieve that (it just returns a ChallengeResult, and the actual Dropbox url is buried somewhere). Also, I think I need a way to separately request the token from the third party based on the authorization code.
This post seems a little similar to what I am trying to do:
Registering Web API 2 external logins from multiple API clients with OWIN Identity
... but the solution there seems to require the client to be an MVC application, which is not necessarily the case for me. I want to keep this as simple as possible on the client side, follow the flow from my diagram above, but also not reinvent the wheel (reuse as much as possible of what already exists in the OWIN/OAuth2 implementation). Ideally I don't want the client to have to reference any of the OWIN/OAuth libraries since all I really need the client to do is access an external url provided by the API (Dropbox in my example), have the user input their credentials and give permission, and send the resulting authorization code back up to the api.
Conceptually this doesn't sound that hard but I have no idea how to implement it and still use as much of the existing OAuth code as possible. Please help!
To be clear, the sample I mentioned in the link you posted CAN be used with any OAuth2 client, using any supported flow (implicit, code or custom). When communicating with your own authorization server, you can of course use the implicit flow if you want to use JS or mobile apps: you just have to build an authorization request using response_type=token and extract the access token from the URI fragment on the JS side.
http://localhost:55985/connect/authorize?client_id=myClient&redirect_uri=http%3a%2f%2flocalhost%3a56854%2f&response_type=token
For reference, here's the sample: https://github.com/aspnet-security/AspNet.Security.OpenIdConnect.Server/tree/dev/samples/Mvc/Mvc.Server
In case you'd prefer a simpler approach (that would involve no custom OAuth2 authorization server), here's another option using the OAuth2 bearer authentication middleware and implementing a custom IAuthenticationTokenProvider to manually validate the opaque token issued by Dropbox. Unlike the mentioned sample (that acts like an authorization proxy server between Dropbox and the MVC client app), the JS app is directly registered with Dropbox.
You'll have to make a request against the Dropbox profile endpoint (https://api.dropbox.com/1/account/info) with the received token to validate it and build an adequate ClaimsIdentity instance for each request received by your API. Here's a sample (but please don't use it as-is, it hasn't been tested):
public sealed class DropboxAccessTokenProvider : AuthenticationTokenProvider {
public override async Task ReceiveAsync(AuthenticationTokenReceiveContext context) {
using (var client = new HttpClient()) {
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.dropbox.com/1/account/info");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.Token);
var response = await client.SendAsync(request);
if (response.StatusCode != HttpStatusCode.OK) {
return;
}
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var identity = new ClaimsIdentity("Dropbox");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, payload.Value<string>("uid")));
context.SetTicket(new AuthenticationTicket(identity, new AuthenticationProperties()));
}
}
}
You can easily plug it via the AccessTokenProvider property:
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
AccessTokenProvider = new DropboxAccessTokenProvider()
});
It has its own downsides: it requires caching to avoid flooding the Dropbox endpoint and is not the right way to go if you want to accept tokens issued by different providers (e.g Dropbox, Microsoft, Google, Facebook).
Not to mention that if offers a very low security level: since you can't verify the audience of the access token (i.e the party the token was issued to), you can't ensure that the access token was issued to a client application you fully trust, which allows any third party developer to use his own Dropbox tokens with your API without having to request user's consent.
This is - obviously - a major security concern and that's why you SHOULD prefer the approach used in the linked sample. You can read more about confused deputy attacks on this thread: https://stackoverflow.com/a/17439317/542757.
Good luck, and don't hesitate if you still need help.

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.