User Authentication on a mobile AngularJS App - angularjs

I'd like to ask a question, which will likely have more than one solution but at this stage I don't know how to solve this problem.
I'm currently building a mobile application built in Angular/Ionic which is accessing the Woocommerce API, for which the app needs to pass a consumer key as well as secret in order to obtain product information as well as create products.
I assume that I do not have direct access to a database on my phone where I can store theses details to authenticate my app and point it at the right woocommerce store.
Even if I store these in a server based app, then my mobile app still needs to authenticate to the server based app in order to access the correct woocommerce store.
Could somebody point me into the right directions as to how developers go about this problem?

Usually, mobile authentication in Phonegap/Ionic looks like that:
You send Authentication request with Login/Pass or ApiKey.
Server response some Token.
You store Token in localStorage.
Send token with every ApiRequest.
Here is example how pass token to every API request if you already have some token.
angular.module('app').config(AppConfig);
AppConfig.$inject = ['$httpProvider'];
function AppConfig($httpProvider, $sceProvider) {
var token = simpleStorage.get('access_token'); // simpleStorage here is a js-plugin for using LocalStorage
if(token){
$httpProvider.defaults.headers.common['access-token'] = token;
}
}

here is a good article for angular-js authentication
https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
If you need of high level security then you can use token based login
like: http://devcenter.kinvey.com/angular/tutorials/how-to-implement-safe-signin-via-oauth
or
you can use http://jwt.io

Related

How to get user info with a valid Bearer Token?

At work we are making an SPFx Web Part React client app that deploys to SharePoint as a Web Part. Our back-end is a ASP.NET Core 2.2 Web API that is secured using Azure Portal's built in Authentication feature. The front-end is using AadHttpClient that magically handles the authentication by taking the context of the current page (SharePoint) that has the user already logged in. Doing so, silent authentication occurs and the API call is successfully made with authentication successfully passed. The AadHttpClient is supposed to magically bundle up the token in the request header that gets sent to the back-end Web API. I still need to debug the live development app and see how to retrieve the Bearer Token in the back-end Web API. These are my next probable steps?
Would I just probably use 'string bearerToken = Request.Headers.....;' or 'string bearerToken = Request.Headers["KeyValue"]' to get the token itself?
Assuming I can get this Bearer Token, how can I check the caller's user information? Is it just var userName = User.Identity.Name;? Or would I or could I use the token and some how make a call to Microsoft Graph API to view the user's info?
If you are using ASP.NET Core and using default authentication then things are bit easier. From documentation you can see that several tokens are injected in the request header based on Identity provider so in your case you have to look for following headers which Azure AD injects. These headers would contain ID Token which you would need to verify the claims and get user information.
X-MS-TOKEN-AAD-ID-TOKEN
X-MS-TOKEN-AAD-ACCESS-TOKEN
X-MS-TOKEN-AAD-EXPIRES-ON
X-MS-TOKEN-AAD-REFRESH-TOKEN
Ideally all the claims are injected automatically in ClaimsPrincipal
you can find more here
Official Docs
How To extract Token

How does AAD API Access delegate permission work?

I'm having a little trouble following how API Access delegate permissions work with azure active directory. I feel like i'm probably misunderstanding a key aspect of how AAD works.
Here is my set up
I have a Web Application let’s call it WebApp. I have created
an AAD for the Web Application and registered with a AAD App ID. Let’s
call it App ID A
I have a Web Api let’s call it ApiService. I have also created an AAD for it and registered with a AAD App ID. Let’s all it App ID B.
In AAD App ID A, I have updated the clicked on the API Access ->
Required Permissions -> Add (App ID B ; Web API) permissions
I’ve updated the manaifest in the AAD App ID B, to give consent to
knownClientApplications to include the client ID of the Web App
I’ve also enable oauth2AllowImplicitFlow to be true for both App’s
manifest.
What I’m trying to do is, A user signs into the web application sign. When it signs in, the user is able to acquire a token for the specific Web App App ID A. The user should be able to use that token and have access the Api Service with App ID B. I thought by configuring the whole API Access -> Required Permissions within the Web Application it would give me delegate permission with the logged in user to communicate with the Api Service WebApi.
When I examine the JWT token, I notice that there is a claim for Microsoft Graph, but not for the ApiService. Shouldn’t I be seeing a claim?
When I try to use the token, it reacts with a 404 authentication error.
Any advice appreciated,
Thanks,
Derek
UPDATE
In response to #joonasw
I actually looked at the example you wrote when i started.
https://joonasw.net/view/aspnet-core-2-azure-ad-authentication
In the example, the web application is initialized with:
.AddOpenIdConnect(opts =>
{
Configuration.GetSection("OpenIdConnect").Bind(opts);
opts.Events = new OpenIdConnectEvents
{
OnAuthorizationCodeReceived = ctx =>
{
return Task.CompletedTask;
}
};
});
In the HomeController, there is code to retrieve the token for the graph api
private async Task<string> GetAccessTokenAsync()
{
string authority = _authOptions.Authority;
string userId = User.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
var cache = new AdalDistributedTokenCache(_cache, _dataProtectionProvider, userId);
var authContext = new AuthenticationContext(authority, cache);
//App's credentials may be needed if access tokens need to be refreshed with a refresh token
string clientId = _authOptions.ClientId;
string clientSecret = _authOptions.ClientSecret;
var credential = new ClientCredential(clientId, clientSecret);
var result = await authContext.AcquireTokenSilentAsync(
"https://graph.microsoft.com",
credential,
new UserIdentifier(userId, UserIdentifierType.UniqueId));
return result.AccessToken;
}
From my understanding, when the user initially login to the web application it will trigger the OnAuthorizationCodeReceived() method where it will be using the clientId/clientSecret/resource of the web applicaiton. The token is stored in the distributed token cache under the key resource/client id.
In the example, GetAccessTokenAsync() is used to grab the token to access the graph API.
In my case, I was hoping to update that method to retrieve the token for the WebApi which has a different clientId/clientSecret/resoruce. In my case, it will AcquireTokenSilentAsync will throw an AdalTokenAcquisitionExceptionFilter because the token needed is not stored in the cache and in the AdalTokenAcquisitionExceptionFilter it will call try to reauthenticate
context.Result = new ChallengeResult();
which will redirect to the authentication page and then hits the AddOpenIdConnect() method. However, the openIdConnect is configured with the web app clientID/ClientSecret/Resource and will not store the new token properly. It will try to call GetAccessTokenAsync() again and the whole process will go in an infinite loop.
In the example, if you were to comment out the "Anthentication:resource" in app.settings, you will experience the same issue with the infinite loop. What happens is that you initially authenticate correctly with no resource specified. Then when you click on you try to get the token for microsoft graph which is a new resource, it can't find it in the cache and then tries to reauthenticate over and over again.
I also notice that the acquireAsyncAuthentication only returns a AuthenticationResult with a bearer tokentype. How would you get the refresh token in this case?
Any advice?
Thanks,
Derek
UPDATE (Solution)
Thanks to #jaanus. All you have to do is update the resource to the clientid of the web api and pass that into AcquireTokenSilentAsync. The web api id uri that you can get from the azure portal did not work.
Okay, so it seems there are multiple questions here. I'll try to make some sense of this stuff to you.
Adding the "Web App"'s client id to the "ApiService" knownClientApplications is a good idea.
It allows for consent to be done for both apps at the same time. This really only matters for multi-tenant scenarios though.
Now, your Web App will be acquiring access tokens at some point.
When it does, it must specify a resource parameter.
This parameter says to AAD which API you wish to call.
In the case of the "ApiService", you should use either its client id or Application ID URI (this is more common).
Depending on the type of your Web App, the access token is acquired a bit differently.
For "traditional" back-end apps, the Authorization Code Grant flow is usually used.
In this flow your back-end gets an authorization code after the user logs in, and your Web App can then exchange that code for the access token.
In the case of a front-end JavaScript app, you would use the Implicit Grant flow, which you have allowed (no need to enable it in the API by the way).
This one allows you to get access tokens directly from the authorization endpoint (/oauth2/authorize) without talking to the token endpoint as you usually have to.
You can actually get the access token right away after login in the fragment of the URL if you wish.
ADAL.JS makes this quite a lot easier for you if you are going in this route.
The reason you get the authentication error is because the access token is probably meant for Microsoft Graph API. You need to request an access token for your API.
An access token is always only valid for one API.

Can someone explain HttpContext.Authentication.GetTokenAsync("access_token")

I have implemented an ASP.NET Core MVC Client using Hybrid flow, and I am wondering what the HttpContext.Authentication.GetTokenAsync("access_token") does.
If you need more background on my question:
The instructions for accessing an API from with an ASP.Net Core Client App Controller Action are generally as follows:
var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");
var client = new HttpClient();
client.SetBearerToken(accessToken);
var response = await client.GetAsync("http://localhost:5001/api/stuff");
There is magic in httpContext.Authentication.GetTokenAsync("access_token") :-)
I am wondering what this function might be doing. Is it decrypting the access token from a cookie in the MVC App Domain? ... from the ID4 Domain?
I am sorry but I have been unable to find sufficient documentation on what this does or finding the cookie the access token may be in. I have looked here:
https://learn.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.authentication.authenticationtokenextensions
Does anyone know what it does? A link to more thorough documentation is a totally appreciated answer.
TU!
You can store arbitrary tokens in your authentication cookie in and that method simply returns one with a given name. Actually setting that would have happened during the sign in process. So in short, it comes from the authentication cookie for your client application and would typically be set at the point of sign in using IdSrv4.
It's a way for the client webapp to confirm separately whether the user really did authenticate with IdentityServer (the user comes to your webapp, the webapp forwards the user to IdentityServer for authentication). The id_token comes back with the user to your webapp in a browser cookie, basically when your webapp sees that id token, it does an independent check with IdentityServer, and if it represents a valid user authentication, you'll get an access token back. You can use that access token to get user claims from the userinfo endpoint.
After all of the above, you can take one of the claims and use it as a key for your application's roles/permissions.

Angular token and user login scenario

I m building app who uses oauth2.
I me using:
Laravel for backend
Oauth2 for Laravel (lucadegasperi)
Angular for frontend because it will be also and native mobile app:D.
My question is?
What is the workflow for user sign in?
Now i have.
User comes to site and enter username and password
Angular send post for access token and when access token is returned i go for user data. Then I store access_token in localstorage. I m using grant_type=password i forget to mention.
I have 2 hours when token gona expire. In that moment when token expire I go for new token by refresh_token functionality.
My Questions are:
Is this good way/approach?
What is supposed to happen when user close browser?
Now when user close browser and again enter to my app. I will check localstorage and then autheticate user by access_token. If Access Token is expired i will get new one.
What about remeber me option or so called keep me signed in?
Does it mean thant i must set token that will be expired in 365 days (lifetime)?
or create cookie/ localstorage with access token so when user comes newt time i read cookie/loaclastorage and then authorize user?
And finnaly about destroying token. Now my token will be detroyed when i log of from the app.
Thanks
We are building the same kind of service/app using the same components. We use a password flow and I store the token in local storage if the user ticks the "remember me" checkbox on the login form, otherwise I just store the token in an un-persisted variable that gets destroyed when the user refreshes or closes the browser.
See some notes on testing protected endpoints here:Testing OAuth 2.0 protected API endpoints in Laravel
Marijan!
I'm working on simple app containing two separate layers. 1) Rails 5 Json API provider. 2) Separate NodeJS server running Angular 2 application.
Angular 2 app on Login requests access token from google
Angular 2 app retrieves UserInfo from google/people API
Angular 2 app now able to POST json with User's display name and some id from Google Response json.
Angular 2 POSTs json to my Rails 5 API server (partially implemented, but already works with login/pass auth).
So far I have implemented implicit OAuth2 using the code similar to this Gist. Using this code I am able to get User Identification Info which is enough for me to identify the user in API provider or create account for it.
This approach works for me. Hope it will work for you as well.
Note: this approach might be insecure.

PassportJS, Angular and jsonwebtokens

I have an Express/Angular app with passportjs-facebook auth and I'm trying to implement a token based system to make calls to my api using jsonwebtokens and avoiding sessions/cookies.
The process that I had in mind goes as follows:
Anonymous user tries to log in with Facebook.
Facebook ID is checked
against the DB retrieving the user if there's a match or creating a
new one if the user doesn't exist.
A token is generated for that
user.
Send token to user
Angular app gets token and stores it on localStorage.
An interceptor on the angular app checks for the user's token as sends it on a header for any subsequent calls.
I'm struggling with steps 4 and 5, I'm not sure how to pass the token and get it on my angular app. Could anyone point me on the right direction to get this working?
You express app can generate the JWT for the app after FB auth.
Take look at this article: https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

Resources