Spring React and Sessions.. how to keep session - reactjs

I have set up my spring to maintain a HTTP session on an object like so:
#Component
#SessionScope
public class Basket { .. }
controller:
#PostMapping(path="/basket/addItem/{user}", consumes = "application/json", produces = "application/json")
public Basket createBasket(#PathVariable String user, #RequestBody Item item) {
System.out.println("POSTING..................................");
return basketService.addItem(user, item);
}
now when i use a REST client, in firefox i can see that the session bean is created and maintained for the duration - multiple calls. I can append to the object. If i try another client, it gets its own session with its own bean. great..
spring logs the following:
Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [269] milliseconds.
However im trying to create a basic front end in react, when react makes a request using axios it gets a new bean every time, which means that the session must be ending after each call. IS that correct? or im not tying it to the react application...
Maybe the approach im taking is not correct, maybe i should use a a different approach, Im trying to learn about spring boot, so its a basic project... and right now i want to maintain user session for a cart. so subsequent calls i can append to the object...

by adding the following to my controller it all began to work.
#CrossOrigin(origins = { "http://localhost:3000" }, allowedHeaders = "*", allowCredentials = "true")

Related

AddHttpClient in Blazor Server Side

I'm trying to create an httpclient in Blazor Server side which would create the least amount of configuration effort every time I call my webapi.
Essentially I would like achieve the following:
Named HTTPClient I can automatically call when I call a function in my webapi.
The webapi requires a bearer token, which I get by calling AcquireTokenSilent
Would be great if I don't have to specify the httpclient when I call the api
The webapi has been added as a service reference, so there is scaffold classes created under the namespace myapp.server.api
To start this off, I created the following in startup:
services.AddHttpClient<myapp.server.api.swaggerClient>(c =>
{
c.BaseAddress = new Uri("https://api.myapp.com/");
AzureADB2COptions opt = new AzureADB2COptions();
Configuration.Bind("AzureAdB2C", opt);
IConfidentialClientApplication cca =
ConfidentialClientApplicationBuilder.Create(opt.ClientId)
.WithRedirectUri(opt.RedirectUri)
.WithClientSecret(opt.ClientSecret)
.WithB2CAuthority(opt.Authority)
.WithClientName("myWebapp")
.WithClientVersion("0.0.0.1")
.Build();
IHttpContextAccessor pp;
string signedInUserID = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
new MSALStaticCache(signedInUserID, pp.HttpContext).EnablePersistence(cca.UserTokenCache);
var accounts = cca.GetAccountsAsync().Result;
AuthenticationResult result = null;
result = cca.AcquireTokenSilent(opt.ApiScopes.Split(' '), accounts.FirstOrDefault()).ExecuteAsync().Result;
c.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
My hope is to be able to call my api in my views in this way:
myapp.server.api.swaggerClient t = new myapp.server.api.swaggerClient();
currentCount = t.WeatherForecastAsync().Result.FirstOrDefault().Summary;
calling a new instance of swaggerclient requires me to specify an httpclient, so my hopes is to inject the httpclient I am configuring on a global level for that type can be injected automatically.
The pieces I need help with:
Given that I have specified my httpclient scoped to a specific type, would it call automatically if I call a function in my webapi? (Does not seem to fire when debugging)
To get the bearer token, I need to get the current userID, which is in the authstateprovider... seeing that this is in Startup, is getting it from DI even possible?
Any easy way to inject the httpclient on the constructor of my webapi classes? would I be able to get the httpclient in the constructor so that I essentially have a parameterless constructor not asking for httpclient?
Concerning your first question, inject the Web API HttpClient like this in your view:
#inject myapp.server.api.swaggerClient MyClient
and then in the code block:
currentCount = MyClient.WeatherForecastAsync().Result.FirstOrDefault().Summary;
You should be able to debug the code inside AddHttpClient.

How to use a CookieCollection in multiple functions

I'm setting up a web page using cookies to determine if the user already logged in, using a cookie containing his id. Problem is : The cookie is either not written or the cookie collection is not updated.
I've tried reading the documentation, but it does not define the usage of CookieCollection.
Here's the function where i write my cookie :
function displayData(){
$id = $this->getRequest()->getSession()->read('id');
$cookies = CookieCollection::createFromServerRequest($this->getRequest());
if(!$cookies->has('id')){
$cookie = (new Cookie('id'))
->withValue($id)
->withExpiry(new DateTime('+999 year'))
->withPath('/')
->withDomain('break-first.eu')
->withSecure(true)
->withHttpOnly(true);
$cookies = $cookies->add($cookie);
}
// Other stuff
}
And where I try reading it :
function index(){
$cookies = $this->getRequest()->getCookieCollection();
dd($cookies);
}
I expect having a cookie named "id", but I don't have it. Only CAKEPHP and pll_language are showing up.
First things first, CakePHP provides authentication functionality with cookie authentication, you may want to have a look at that instead of driving a custom solution.
Cookbook > Plugins > Authentication
That being said, what you're doing there will create a cookie collection object, which however is just that, a lone object somewhere in space, it won't affect the state of your application, in order for that to happen you have to actually modify the response object.
However what you're trying to do there doesn't require cookie collections in the first place, you can simply read and write cookies directly via the methods provided by the request and response objects, like:
// will be `null` in case the cookie doesn't exist
$cookie = $this->getRequest()->getCookie('id');
// responses are immutable, they need to be reassinged
this->setResponse(
$this->getResponse()->withCookie(
(new Cookie('id'))
->withValue($id)
->withExpiry(new DateTime('+999 year'))
->withPath('/')
->withDomain('break-first.eu')
->withSecure(true)
->withHttpOnly(true)
)
);
And if you where to use a cookie collection for whatever reason, then you'd use withCookieCollection() to pass it into the response:
$this->setResponse($this->getResponse()->withCookieCollection($cookies));
If you run into strict typing errors, you could for example create a custom reponse class with an overridden Response::convertCookieToArray() method and cast the string to an integer there (make sure that PHP_INT_MAX covers your target date timestamp, 32-Bit incompatibility is why the fix that landed in CakePHP 4.x, probably won't come to 3.x), something like:
src/Http/Response.php
namespace App\Http;
use Cake\Http\Cookie\CookieInterface;
use Cake\Http\Response as CakeResponse;
class Response extends CakeResponse
{
protected function convertCookieToArray(CookieInterface $cookie)
{
$data = parent::convertCookieToArray($cookie);
$data['expire'] = (int)$data['expire'];
return $data;
}
}
You can pass that into the app in your webroot/index.php file, as the second argument of the $server->run() call:
// ...
$server->emit($server->run(null, new \App\Http\Response()));
See also
Cookbook > Request & Response Objects > Request > Cookies
Cookbook > Request & Response Objects > Response > Setting Cookies

Spring webflux data in ReactJs UI

I am playing around with spring webflux. I have created a project which would listen on a mongo capped collection and return the flux of data as and when it comes.
I am using #Tailablein my repository method.
My controller looks like this
#GetMapping("/findall")
public Flux<Product>> findAll() {
return productRepository.findAllProducts().;
}
This is working perfectly fine. I tested this by addind a doOnNext(...), Whenever there is a new item added to my capped collection, consumer inside the doOnNext is executed.
Now I want this to be displayed on the browser. And I wanted to do with ReactJs(I am completely new to frontend).
So far, I couldn't find any way to display the flux data in browser. What are the options by which I can achieve this.
I tried SSE(Server Sent Event) like this
componentDidMount() {
this.eventSource = new EventSource('http://localhost:8080/findall');
this.eventSource.addEventListener('product', (data) => {
let json = JSON.parse(data.data)
this.state.products.push(json.name)
this.setState ( {
products : this.state.products
})
});
}
This works perfectly fine, but for this to work, I had to change my server side code like this
#GetMapping("/findall")
public Flux<ServerSentEvent<Product>> findAll() {
return productRepository.findAllProducts().map(data -> ServerSentEvent.<Product>builder().event("product").data(data).build());
}
This, in my opinion is a bit tightly coupled because, UI should know the event type('product') to listen to.
Is there any other way to handle stream of events from UI side(particularly with reactjs) ?
You shouldn't have to change your controller in order to stream data to the browser. The following code snippet should work:
#GetMapping(path="/findall", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
#ResponseBody
public Flux<Product>> findAll() {
return productRepository.findAllProducts();
}
You can see this feature being used in this workshop and this sample app if you'd like to see a complete working examples.

Session Handling in Angular JS, with Spring MVC

I am creating a project in AngularJs at frontend and Spring MVC in backend.
Now assume when a used logged in and if he wants to update his information, for this i have created an api which request for emailid and update the rest object in database of that email id
Now i have some questions,
1.) I dont want to use CookieStore or others sessionStorage or localstorage (because of my personal vulnerability experience and also i want to use session only) in Angular, how can i do it in angular with Spring MVC.
2.) How can i retrieve the email id from session to update data?
3.)If a user goes to another page how can i maintain that session in another page, how can i check that session is there and user is authentic to see the page
Read a lot about it but unable to find the exact solution with session. Answer over there is manage it by cookieStore.or localstorage, Please help
Let's try and see what is happening here using cookies is the right way to this, you may think it is not safe but is the safest way to do it. With cookies you will be sharing the same session in all tabs, so you can handle in all tabs and share it.
There is also an alternative option and is using URL rewriting, quoting #vanje in this question in stackoverflow
the session is only identified via a URL parameter containing the session ID. So every internal URL of your web application has to be enhanced with this parameter using the method HttpServletResponse.encodeURL(). If you are using a web framework like Wicket, chances are good that this is already done for you.
Lets go now with the Angular JS - Spring MVC approach:
There is no need to access the session within the Angular JS front-end, if you need to use it and you are using JSP you may use scriplet to retrieve the information openening a <%= session.getAttribute("user") %> , but as I said there is no need to do this. You may call your function, and retrieve this information in your controller in Spring.
You have a controller in angular JS that calls with http to your REST controller in Spring such like this. assuming that you save your user first in session:
$scope.getUserInfo= function () {
$http.get(appContextPath +'/rest/getuser/').success(function (data) {
$scope.user= data;
});
};
You may have a request mapping for the URL above:
#RequestMapping(value = "/rest/getuser", method = RequestMethod.GET)
#ResponseBody
public User getUserInfo (HttpSession session) {
User nUser = session.getAttribute("user");
return nUser;
}
I think the best way is to create a method in your AngularJS controller and then call it.
Java code:
#RequestMapping(value = "/menu/get", method = RequestMethod.GET, headers="Accept=*/*")
public #ResponseBody Empleado showMenu(HttpSession session) {
Empleado empleado = (Empleado) session.getAttribute("empleado");
return empleado;
}
AngularJS code:
angular.module('myModule')
.controller('myMenuController', ['$scope', '$http'
function($scope, $http){
getEmpleadoInfo = function () {
$http.get(myContextPage + '/menu/get')
.then(function(data) {
$scope.empleado = data;
})
}
getEmpleadoInfo();
}]);
This way, when you load the page, the object will be loaded on the scope.

RPC call to external server

I am a new bie on GWT, I wrote an application on abc.com, I have another application i.e. xyz.com, xyz.com?id=1 provides me a data in json format, I was thinking to find a way that how to get that json file in abc.com via RPC call, because I have seen tutorials in which RPC calls are used to get data from its server. any help will be appreciated.
EDIT
I am trying to implement this in this StockWatcher tutorial
I changed my code slightly change to this
private static final String JSON_URL = "http://localhost/stockPrices.php?q=";
AND
private void refreshWatchList() {
if (stocks.size() == 0) {
return;
}
String url = JSON_URL;
// Append watch list stock symbols to query URL.
Iterator iter = stocks.iterator();
while (iter.hasNext()) {
url += iter.next();
if (iter.hasNext()) {
url += "+";
}
}
url = URL.encode(url);
MyJSONUtility.makeJSONRequest(url, new JSONHandler() {
#Override
public void handleJSON(JavaScriptObject obj) {
if (obj == null) {
displayError("Couldn't retrieve JSON");
return;
}
updateTable(asArrayOfStockData(obj));
}
});
}
before when I was requesting my url via RequestBuilder it was giving me an exception Couldn't retrieve JSON but now JSON is fetched and status code is 200 as I saw that in firebug but it is not updating on table. Kindly help me regarding this.
First, you need to understand the Same Origin Policy which explains how browsers implement a security model where JavaScript code running on a web page may not interact with any resource not originating from the same web site.
While GWT's HTTP client and RPC call can only fetch data from the same site where your application was loaded, you can get data from another server if it returns json in the right format. You must be interacting with a JSON service that can invoke user defined callback functions with the JSON data as argument.
Second, see How to Fetch JSON DATA

Resources