Opublikowany w SmartHouse, Spring

Spring security

W swojej aplikacji mam na razie 2 role:

  • USER
  • ADMIN

Gdzie wszystkie funkcje USER są dostępne dla ADMIN (include).

Można to zrealizować z wykorzystaniem:
Hierarchical Roles

JWT – JSON Web Token i Spring Security

Tutaj jest fajnie opisane jak zintegrować JWT ze Spring Security: https://www.bezkoder.com/spring-boot-react-jwt-auth/

Jeśli chodzi o reactjs to z użyciem CONTEXT (https://www.freecodecamp.org/news/react-context-for-beginners/) i obsługa opisana tutaj:

https://makinhs.medium.com/configuring-a-react-app-to-handle-authentication-without-redux-with-hooks-4424e9c30d73

Tutaj strona, którą czytam (do Reactjs):

https://www.learmoreseekmore.com/2022/09/reactjs-v18-authentication-with-jwt-accesstoken-and-refresh-token.html

i może jeszcze ta:

https://www.toptal.com/spring/spring-security-tutorial

Przygotowanie template strony React

  1. Używam BrowserRouter (opis: https://ibaslogic.com/routing-with-react-router/) zeby mozna bylo przechodzic z uzyciem url na rozne podstrony
  2. Instaluję JWT Decode Library: npm i jwt-decode
  3. Instaluję Axios Library: npm i axios
  4. Informacje autentykacyjne muszą być widoczne we wszystkich komponentach. Do tego celu używam ReactJS Context API https://hy.reactjs.org/docs/context.html

Zmiany w Spring backend

Zgodnie z video:

Tworzę klasę JwtService, przy okazji: adnotacja @Value(„${jwt.signingKey}”) przed nazwą metody lub zmiennej, pozwala na przypisanie jej wartości z pliku application.properties.

  1. Instalacja pluginu eclipse: https://projectlombok.org/setup/eclipse, zgodnie z : https://www.youtube.com/watch?v=UKQdv3cu2Ok&ab_channel=InterviewMania
  2. Nazwy ról muszą sie zaczynać od (prefix): ROLE_

Globalne ustawienie CORS:

Opublikowany w SmartHouse, Spring

React.js and Spring

Pierwsze kroki w zbudowaniu interfejsu użytkownika dla mojego sHouse z użyciem React.js, poczynie z uzyciem strony: https://spring.io/guides/tutorials/react-and-spring-data-rest/https://spring.io/guides/tutorials/react-and-spring-data-rest/

Po wrzuceniu do application.properties:

 spring.data.rest.base-path=/api

I dodaniu w pom.xml:

		  <dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-data-rest</artifactId>
		  </dependency>

Mogę wszystkich @Entity z interfejsem obsługującym, implementującym JpaRepository/CrudRepository i następnie w klasie @Controler lub @Component zarejestrowany obiekt jako @Autowired będzie dostępne w REST API.

Lista interfejsów widoczna pod linkiem localhost:8443/api (wyłączyłem tymczasowo SSL zeby skorzystac z ./curl)

Testowe zapytanie dodające:

./curl -i -X POST -H 'Content-Type:application/json' -d '{\"name\": \"wylacznikSwiatelTarasu\", \"description\":\"sluzy do przelaczania swiatla w podlodze tarasu\" }' localhost:8443/api/switchers

Metody inne niż GET-pobieranie (POST-tworzenie PUT/PATCH-update DELETE-kasowanie) nie działają dopóki nie doda się wyłączenia csrf:

http.csrf(c ->  c.ignoringAntMatchers("/api/**"));

Uruchomienie pierwszej strony w React.js

Wszystko zgodnie z instrukcja ze strony /https://spring.io/guides/tutorials/react-and-spring-data-rest/ pamiętając dodatkowo o:

  1. Przegraniu plików client.js i z katalogu api/js.
  2. w pliku webpack.conf.js podmiana linijki ‚devtool: sourcemap’ na devtool: ‚hidden-source-map’.
  3. Konfiguracja plugin w pom.xml
			<!-- tag::frontend-maven-plugin[] -->
			<plugin>
				<groupId>com.github.eirslett</groupId>
				<artifactId>frontend-maven-plugin</artifactId>
				<version>1.11.0</version>
				<configuration>
					<installDirectory>target</installDirectory>
				</configuration>
				<executions>
					<execution>
						<id>install node and npm</id>
						<goals>
							<goal>install-node-and-npm</goal>
						</goals>
						<configuration>
							<nodeVersion>v12.14.0</nodeVersion>
							<npmVersion>6.13.4</npmVersion>
						</configuration>
					</execution>												
					<execution>
						<id>npm install</id>
						<goals>
							<goal>npm</goal>
						</goals>
						<configuration>
							<arguments>install</arguments>
						</configuration>
					</execution>

                   <execution>
                       <id>webpack build</id>
                       <goals><goal>webpack</goal></goals>
                   </execution>

				</executions>
			</plugin>
			<!-- end::frontend-maven-plugin[] -->	

Później kolejno odpalane:

Run As -> Maven clean

Run As -> Maven install

Maven -> Update Project

Opublikowany w SmartHouse, Spring

Szkolenie safari spring-boot

„Modern Java recipes” – jego ksiazka

https://docs.google.com/document/d/1_qEcoGyl-QsycVMl_zCevTPoHW1V_q7OQsAKD437884/edit

http://www.kousenit.com/springboot/

https://spring.io/docs/reference

https://docs.spring.io/spring/docs/4.3.12.RELEASE/spring-framework-reference/htmlsingle/

https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/

http://spring.io/guides

 

 

http://localhost:8080/hello?name=Marcin

 

gradlew build

gradlew bootRun

ctrl-shift+t – tworzenie testu w intellij

 

PART 2:

AOP – Spring uzywa Aspect Oriented Programming (uzycie adnotacji)

zalecane jest konfigurowanie Spring za pomocą JavaConfig (w dalszym ciagu jest możliwe użycie oczywiście XML i Adnotacji)

JavaConfig to klasa, które używa metod do konfigurowania innych klas Spring

 

kazdy bean tworzony przez Spring jest Singletonem (zawsze jedna instancja)

mozna to nadpisać (zmienić), bo jest to dobre np dla pool managera,

dokumentacja Spring w 1 pliku: https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/htmlsingle/

Adnotacja @ComponentScan(„nazwa.pakietu”) moze pomoc jesli nie znajduje jakiegos Bean, gdzie ma skanowac

w resources mozna dodac plik.sql , ktory bedzie urachamiany.

Najpierw jest uruchamiany schema.sql, potem data.sql (mozna to skonfigurowac)

ctrl+shift+F10 zeby wystartowac wszystkie testy

Opublikowany w SmartHouse, Spring

Spring -Tomcat deployment

 

  • Trzeba zmienić w Maven wpis (pom.xml) na: war
  • Trzeb adodać jeszcze klasę inicjującą:

 

package sh..
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

public class ReadingListServletInitializer extends SpringBootServletInitializer{

@Override
protected SpringApplicationBilder configure(SpringApplicationBuilder builder){
return builder.sources(MOJA_KLASA_STARTOWA.class);
}
}

 

  • Teraz trzeba uruchomić maven: mvn package
  • ..i skopiować plik WAr (z katalogu „target”) do Tomcat webapps – Tomcat automatycznie zainstaluje aplikację.

 

Opublikowany w SmartHouse, Spring

Spring – zbudowanie strony do obslugi bledow

Customizing application error pages

I don’t know if you’ve encountered any errors while trying out the reading-list application, but if so you’ve probably seen an error page much like the one in figure 3.1.

Figure 3.1. Spring Boot’s default whitelabel error page.

Spring Boot offers this “whitelabel” error page by default as part of auto-configuration. Even though it’s slightly more attractive than a stack trace, it doesn’t compare with some of the great works of error art available on the internet. In the interest of presenting your application failures as masterpieces, you’ll probably want to create a custom error page for your applications.

The default error handler that’s auto-configured by Spring Boot looks for a view whose name is “error”. If it can’t find one, it uses its default whitelabel error view shown in figure 3.1. Therefore, the easiest way to customize the error page is to create a custom view that will resolve for a view named “error”.

Ultimately this depends on the view resolvers in place when the error view is being resolved. This includes

  • Any bean that implements Spring’s View interface and has a bean ID of “error” (resolved by Spring’s BeanNameViewResolver)
  • A Thymeleaf template named “error.html” if Thymeleaf is configured
  • A FreeMarker template named “error.ftl” if FreeMarker is configured
  • A Velocity template named “error.vm” if Velocity is configured
  • A JSP template named “error.jsp” if using JSP views

Because we’re using Thymeleaf for the reading-list application, all we must do to customize the error page is create a file named “error.html” and place it in the templates folder along with our other application templates. Listing 3.7 shows a simple, yet effective replacement for the default whitelabel error page.

Listing 3.7. Custom error page for the reading-list application

This custom error template should be named “error.html” and placed in the templates directory for the Thymeleaf template resolver to find. For a typical Maven or Gradle build, that means putting it in src/main/resources/templates so that it’s at the root of the classpath during runtime.

For the most part, this is a simple Thymeleaf template that displays an image and some error text. There are two specific pieces of information that it also renders: the request path of the error and the exception message. These aren’t the only details available to an error page, however. By default, Spring Boot makes the following error attributes available to the error view:

  • timestamp—The time that the error occurred
  • status—The HTTP status code
  • error—The error reason
  • exception—The class name of the exception
  • message—The exception message (if the error was caused by an exception)
  • errors—Any errors from a BindingResult exception (if the error was caused by an exception)
  • trace—The exception stack trace (if the error was caused by an exception)
  • path—The URL path requested when the error occurred

Some of these attributes, such as path, are useful when communicating the problem to the user. Others, such as trace, should be used sparingly, be hidden, or be used cleverly on the error page to keep the error page as user-friendly as possible.

You’ll also notice that the template references an image named MissingPage.png. The actual content of the image is unimportant, so feel free to flex your graphic design muscles and come up with an image that suits you. But be sure to put it in src/main/resources/static or src/main/resources/public so that it can be served when the application is running.

Opublikowany w Spring

Spring, ważne wiadomości

https://github.com/enetwiz/spring-examples/blob/master/modules/HibernateUsage/README.md :

Anotacja @Bean nad metoda – oznacza, ze kontekst Springa utworzy obiekt POJO o referencji/id zgodny z nazwa metody np.

* @Bean public HelloBean helloBean() { return new HelloBean(); } *

oznacza to samo co:

HelloBean helloBean = new HelloBean();

 

Budowanie zapytań w JpaRepository za pomocą nazwy metody:

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods