Authenticate aginst server and restful api using angular and java ee - angularjs

I've got an web app developed using angularjs for the front-end, java ee for the server side and a java restful api to connect both ends. I am using glassfish for the development process but the solution should be compatible with websphere, wildfly (not as important as the other three) and weblogic (doesn't need to be the same approach to all of them but that would be ideal).
So both the front-end and the resful api authenticate against the server which was solved by using BASIC authentication and only ONE username/password combination was asked for. When I changed BASIC to be FORM (using j_security_check) so I could design a proper login page. After having changed this, first I have to login using the form and then I have to login against the rest api as well, which is not what I want. So I've been trying different approaches ever since without any success.
Things I've tried so far:
Create a filter so I can capture username/password and add this into the header of the restful calls so no log in info is asked after the form login page -> doesn't work in glassfish
Change the login for specified in the web.xml for one developed by myself using angular so I can capture username/password and use an injector to add it to all the calls to the resful api -> Cannot login against the server since it doesn't accept any of my attempts by either rejecting then or saying that the page doesn't exist (probably doing it wrong but couldn't find much info about this...)
Using web.xml form authentication try adding an angular controller to capture the username/password and use an injector (angular doesn't work with the login page using j_security_check)
Capturing the response from the server on login so I can use the session to authenticate when using the restful api (don't know how to capture the response in the form page...)
Any thoughts are more than welcome after almost two weeks trying to make this work.
If you need more information or a example of any part of the code please just say and I will add it to the question.
Thanks!

Related

Azure AD implementation for SPA / WebAPI application having both on the port/HostEnv.?

I am trying to implement Azure AD authentication in a SPA application.
I am using an OWIN Startup.cs file in the WEB API and ADAL.js file in the angularjs front end application. (as per most of the tutorials suggestion)
My application does not have WebAPI and UI hosted in different domains/port. Basically, the WebAPI is referenced in the UI application project. (So no need for enabling CORS).
Now I have registered the applications on the Azure AD separately.
i.e. ClientApp -> Reply URL: http://localhost:90/ and
WebAPI -> APPID SignOn URL: http://localhost:90/Api/V1/
I have configured the ADAL.js and also getting the login page when trying to access the application from the UI. Also, I am able to retrieve the id.token generated after logging through the URL redirection. Also have decorated the web api controllers with the [Authorize] attribute.
My main concern here is that, if I try to call the WebAPI directly using tools like postman, I am getting access denied/Unauthroized Access (401). Can someone pls explain how can I test on my local env. with this scenario?
My sample request is: http://localhost:93/Api/V1/User/Preference (GET)
I am adding the token in the Authroization property of the Headers in the web api call.
Also a side note, I don't think I require OWIN/Startup.cs file for securing the WebAPI. The way I tried is that I got the token value send through the headers and got the AudienceID using JwtSecurityToken and parsing the contents of the Authroization property. Is this approach right as per security or I should stick to the OWIN implementation.
All of the ADAL JS tutorials have the backend API and the UX hosted on the same domain and port, with no need for CORS. See for example https://azure.microsoft.com/en-us/resources/samples/active-directory-javascript-singlepageapp-dotnet-webapi/. Those samples demonstrate that you need only ONE Azure AD registration, as the JS layer is in effect the exact same app as the web API.
We do have some samples demonstrating how to call an external API as well, and those do require CORS- but only for the extra API. The logic for calling the app backend remains the same (just one Azure AD app registration, no need for CORS).Postman doesn't offer any opportunity to pop out UX, hence one strategy you can follow is to obtain the tokens you need beforehand.
The use of OWIN allows you to centralize the auth setup; if you add auth in the controller, you'll need to repeat that logic for every new controller you add. Also, maintaining the code will be harder as you might use API surface that requires code changes when you update the assemblies, while that's less likely to happen if you use the standard middleware setup

Use API key between angularJS and Laravel

I'm building an API based application, which uses Laravel as the backend and AngularJS for the front-end.
User Authentication between the front-end and the API is relatively straightforward, using JSON web-tokens (JWT). This tutorial was especially helpful
But much of my front end app is not user-authenticated, it simply needs to be protected by an API key.
I would like to continue using the JWT approach if possible, but i can't find a single package or guide for securing a front-end application with a simple API key (with no initial user login). I don't want to re-invent the wheel, there must be existing solutions for this common problem..
Does anyone have any experience securing and API based AngularJS frount end for use with a custom API? Are there any packages which exist to do this?
NOTE: I have investigated Auth0, which is great, but it is has several problems (the cost, no free support for a custom user DB, no built-in support for a simple API-key)
Thanks
The best way I can think of to handle this is to create a new Laravel user for your angular site.
You will also need a proxy script which contains the site's user credentials. It would reach out to Laravel with
those credentials and return the JWT. Then you just call this proxy script from Angular to get your token. The purpose
of the proxy script being a good way to hide those credentials from users.
This way, you don't need to change anything in your API as it's really just a new user accessing the site. If or when
the user needs to elevate his credentials by signing in as himself, you can also continue to use the proxy script and
have it replace those default site credentials with the user credentials before grabbing the JWT from Laravel.

AngularJS with web API authentication

I have recently started learning AngularJS and I'm trying to create a simple login system. Some of the methods for creating and storing a cookie for authorisation looked a lot more complicated than the .net approach I was use to so my first thought was to keep using that method of authentication by doing a call to the API and keeping the angular UI side free of all that.
This option was suggested in this post here -
How to handle authentication in Angular JS application
However when I try to implement this it authenticates fine, but it does not save this cookie. If I access the API again and try anything referencing the cookie like,
FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);
It will just say that there is nothing there.
Is there a simple way of retaining this cookie in the API that I am not using?
Here is how you can do it, this will also let you include custom information with the auth cookie.
https://stackoverflow.com/a/10524305/1121845

Oauth social login using MEAN.js Restful sessionless API backend

I'm developing a Restful API using MEAN.js, which will be consumed by an AngularJS Web site and Phonegap Mobile Apps.
I'd like the user to be able to create an account and/or login using Faceboo, Google and Twitter.
I'm trying to use the same sample code that comes with MEAN.js seed application, but with the Node side of it, on port 3000 serving only the API, and the web site running on another server (currently on port 9000).
I','ve already implemented Token authentication using a Passport custom Local strategy, which generates a token, and the Bearer Strategy to autheticate API calls.
But I'm having problems with social login, to link social accounts to existing users.
From the Angular Client I call an api endpoint that redirects the user to the oauth provider (e.g. Twitter). When the user comes back, my serve has no knowledge of the logged user, since I'm not using sessions anymore.
I've tried to return the provider token to the client, but have problems parsing the anguler url. Then I coded another page outside angular that receives the provider token and calls an api endpoint sending the oauth token and the token issued by my api. It worked for Google, but not for Twitter. It seems twitter needs a session.
Anyway, what is the best approach to achieve what I want? How can I make this work?
Since your using Angularjs, take a look at this Angularjs library https://github.com/sahat/satellizer. The library pretty much opens up an oauth popup and checks the popup url for tokens. You can easily replicate the approach or just use this library. It works with a few social media providers like Twitter and its easy to add more.
I was in need of the same thing and so I set out to create my own. It's still in development but should give you a good start. Feel free to create a pull request and help to make it better. Maybe we can eventually merge it into their codebase.
https://github.com/elliottross23/MeanJsSocialLoginTokenAuth

Example of an SPA with a login screen that uses AngularJS and connects to ASP.NET Web API 2?

I would like to create a new AngularJS, Web API Single page application. Does anyone have any examples that show how I can set up a user login screen that connects to a WEB API controller for a simple login (no need for google/facebook login etc) that uses ASP.NET Identity and without the need for user registration.
Also how can I handle showing a new view once the login has been completed. What I would like is to have a solution that does not show routing in the browser URL. So for example I would like to be able to switch from the login view and a couple of other different views without the url changing from www.abc.com.
In other words I would like to avoid showing www.abc.com/login, www.abc.com/screen1, www.abc.com/screen2
Any advice would be much appreciated.
So, instead of trying to find an example, I created one instead (link at the bottom). To explain how the functionality works, I want to go over a few things:
The new ASP.NET Identity system provides an OAuth 2.0 Bearer token implementation which can be used with clients that consume a Web API resource over HTTP. Since the authentication is not stored in a session cookie, the server is not responsible for maintaining the authentication state. The side-effect is that the consumer has to manage authenticating the server and managing the returned token. This is the system that Microsoft uses in the SPA template that it provides with VS 2013.
AngularJS makes no assumptions about authentication, so it's up to you how to authenticate.
AngularJS provides the $http service for querying remote HTTP-based services as well as $resource which is built on top of $http. Using Authorization headers with the Bearer token implementation above, you can combine both to provide authenticated access to server resources over HTTP. AngularJS allows you to set a 'default' Authorization header which it will use in every subsequent HTTP transaction.
With that in mind, the way I accomplished this is by creating a User service that handles all of the authentication details, including setting the HTTP Authorization header, between the Web API server and the SPA. Based on the authentication status of the user, you can hide certain UI elements in order to prevent navigation. However, if you also define the state as requiring authentication as a property of the resolve object for the state, a watcher set on the $stateChangeError event will capture the error and redirect the user to the login form. Upon proper authentication, it will then redirect the user to the state they were trying to navigate to.
In order to prevent authentication from being lost between browser sessions (since the client is responsible for maintaining the authentication token, and that token is maintained in memory), I also added the ability for the user to persist the authentication to a cookie. All of this is transparent to the user. For them, it is practically identical to traditional form-and-session based authentication.
I'm not sure why you want to prevent the user from seeing the routes, but I have coded it as such. I am in debt to Sedushi's Plunker example of how to use AngularUI Router to navigate in a stateful manner without using URLs. Still, I'm not sure I can personally recommend this for any application I would write on my own.
The full solution (both the WebAPI and the WebUI) is available with step-by-step instructions here.
Let me know about any specific part that is unclear, and I will try to make it more clear in the answer.
Refer the following blog for the demo of single page application (SPA) for ASP.NET Web API 2 and AngularJS, developed by the team at Marlabs.
http://weblogs.asp.net/shijuvarghese/archive/2014/01/25/demo-spa-app-for-asp-net-web-api-2-and-angularjs.aspx
The app is built with following technologies:
ASP.NET Web API 2
EF 6 Code First
AutoMapper
Autofac
Semantic UI
AngularJS 1.1.5
The application is published on github at https://github.com/MarlabsInc/webapi-angularjs-spa.
#DavidAntaramian gave a great example. But if you want a simple one, you can look to this HOL from Microsoft.
Their latest example on github uses .NET Core, but you can download release from October 2015.

Resources