How to allow an angularjs app authenticate in rails api? - angularjs

I have two separated apps (AngularJS + Express + NodeJS) and a Ruby on Rails API (rails-api).
To keep it simple my client application will not authenticate users but it will need to consume the data from api.
I've used authenticate_with_http_token method in the rails-api and it works (if you pass in header or query params) but I can't retrieve the token as a security form (from environment variable I think) inside the angularjs app. Yes I can access the env vars from express server, but I can't share this values to be used at angular.
App.run(function($http ...) {
// $http.defaults.headers.common.Authorization = proccess.env.AUTH_TOKEN_API <- I can't do this. But is something like this I need.
$http.defaults.headers.common.Authorization = 'Token token=78db1w26vve20aa36...';
How to keep security in api in this case?

Related

Spring Boot, React and OpenId Connect

We have a use case where we are implementing OpenId Connect in a Spring Boot (backend) + React (frontend) application. We are implementing Authorization code flow.
The backend and frontend are on separate domain.
Here is the flow that happens:
The backend returns the generated URL which can be open by the React App for login (redirecting to Cognito in our case - but it can be anything) - or even this URL can be generated on the Frontend itself - since the clientId will be exposed in the URL anyway
The user logs in, a request is sent to the redirect uri, where the Authorization Code is used to get an access token, id token and refresh token
When this ends, we have the tokens but how do we transfer them to the React App in the other domain? I assume redirection and passing the tokens as query parameters makes sense - something like return "redirect://http://www.yourfrontenddomain.com?access_token" + tokenValue;
Am i missing something here or my approach is fine?
Using Implicit flow here would be easier - but this is less secure and only recommended for Javascript apps - here we have a mix of Backend + Frontend.
Thanks a lot in advance
Ok it seems i was not understanding the concepts correctly.
Authorization code flow with PCKE is exactly made for this use case - to be used in SPA's or Mobile clients.
By using that flow, we can just use Spring Security and just validate the tokens on the backend (without generating them or anything)

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

angularJS login connect to API backend

I've found alot of text explaining this but i haven't quite found what i'm looking for. I'm hoping someone can point me in the right direction. I am building an Angular App that communicates with a RoR back-end. On the back-end there is a basic authentication with username and password. For the moment i've hardcoded the username and password into my app.js. I'm using Restangular so i set it up like so:
var authenticationToken = btoa('username,password');
.config(function (RestangularProvider) {
RestangularProvider.setDefaultHeaders({Authorization: 'Basic ' + authenticationToken});
}
But what I would like is for users to have to login when they open the app with username and password. So that my app can use those to send requests to the backend. I have no real idea how to set this up properly.
update
I figured out my problem. I'm using default headers, while I should be using individual headers. Which i can just set in my service call.
All you need to do is create a text input in Angular. Follow the example in the Angular documentation. Then in your controller/directive (whatever scope you store the username and password) just make the authentication call like you did in your question.

How do I implement secure OAuth2 consumption in AngularJs?

I'm setting up oauth2 with Salesforce connect using AngularJS. When I attempt the initial GET using $http I get CORS errors - Access-Control-Allow-Origin not allowed for my client. However, using the hack below in my controller function works.
Is there a better way to do this in AngularJs given that I don't have control over the server? My backend is Firebase so it would be great if I could do this through FIrebase like I can for Facebook :
$scope.auth = function () {
var authUrl = $scope.AUTHORIZATION_ENDPOINT +
"?response_type=token" +
"&client_id=" + $scope.CLIENT_ID +
"&redirect_uri=" + "https://www.xyz/";
window.location = authUrl ;
The cors issue happens when make asynchronous call to different server via browser.
So it doesn't appear if the call is made from another server. so you have to use a proxy server which in turn makes a call to your actual server.
You can try the below proxy server which is straightforward.
https://www.npmjs.com/package/cors-anywhere
or you can write your own proxy server which runs on the same domain as your client app and proxies your request to the secured server.

How to pass basic auth header to REST endpoint after Forms Authentication sign in?

I have a Backbone/RequireJS application built on top of .NET MVC4. I am using Forms Authentication to authenticate the user against our back end data store, and this is working great.
Our services layer is a .NET Web Api Project (RESTful API), and is using a tokenized approach to auth (initial request includes basic auth header. If auth is successful, response payload includes authentication token. Subsequent requests pass the token).
What I'm not sure about is how to now authenticate against our services layer. I'm sure I'll have to pass the auth header, but not sure how to generate the token, as I won't have username/password in my JS.
Should I bypass Forms auth altogether here, and simply make an ajax request over SSL? I can POST to the /Account/Login action just as well, and use the Membership Provider to validate credentials. If successful, I can add the Auth header for initial request & use auth token for subsequent requests.
Example of adding auth header / custom token here:
$.ajaxSetup({
'beforeSend': function (xhr) {
if($.cookie("AuthToken")) {
xhr.setRequestHeader("CustomTokenHeader", $.cookie("AuthToken"));
} else {
var token = methodToBase64EncodeUsernamePassword(username, password);
xhr.setRequestHeader("Authentication", "Basic " + token);
}
}
});
Take a look at this solution, which is based off a screencast I cannot seem to find again. If I can find it, I will update the answer. You should be able to follow the solutions easily though. The one you are looking for is PerRouteMHOwnershipSample. I believe the best practice is to 'bypass Forms auth altogether here, and simply make an ajax request over SSL'. Any api route you want to secure, will be filtered and a token will then need to be passed from your app and decoded on the server. I would personally not look at using Forms Authentication to secure your api.

Resources