From 6029d52bf459b596c1584e13c3c65cf0042898fd Mon Sep 17 00:00:00 2001 From: Antoine Duquenoy Date: Mon, 1 Oct 2018 22:34:58 +0200 Subject: [PATCH] Spring Security opérationnel --- PFE06/src/main/java/com/PFE/ServerManager/Customer.java | 20 ++++++++++++++------ PFE06/src/main/java/com/PFE/ServerManager/MainController.java | 66 +++++++++++++++++++++++++++++++++++------------------------------- PFE06/src/main/java/com/PFE/ServerManager/Role.java | 4 ++++ PFE06/src/main/java/com/PFE/ServerManager/SecurityConfig.java | 27 ++++++++++++++++++++------- PFE06/src/main/java/com/PFE/ServerManager/WebMvcConfig.java | 16 ++++++++++++++++ PFE06/src/main/resources/application.properties | 4 ++-- PFE06/src/main/resources/data.sql | 8 +++++--- PFE06/src/main/resources/templates/denied.html | 16 ++++++++++++++++ PFE06/src/main/resources/templates/home.html | 14 ++++++++++++-- PFE06/src/main/resources/templates/login.html | 4 ++-- 10 files changed, 126 insertions(+), 53 deletions(-) create mode 100644 PFE06/src/main/java/com/PFE/ServerManager/WebMvcConfig.java create mode 100644 PFE06/src/main/resources/templates/denied.html diff --git a/PFE06/src/main/java/com/PFE/ServerManager/Customer.java b/PFE06/src/main/java/com/PFE/ServerManager/Customer.java index 01d7ef9..7ed447e 100644 --- a/PFE06/src/main/java/com/PFE/ServerManager/Customer.java +++ b/PFE06/src/main/java/com/PFE/ServerManager/Customer.java @@ -1,6 +1,7 @@ package com.PFE.ServerManager; import javax.persistence.*; +import java.util.Set; @Entity @Table(name = "customer") // NE PAS utiliser "User" car c'est un mot clef réservé pour PostgreSQL @@ -16,24 +17,31 @@ public class Customer{ @Column(name = "password") private String password; - @ManyToOne(cascade = CascadeType.ALL) + @Column(name = "active") + private int active; + + @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "customer_role", joinColumns = @JoinColumn(name = "customer_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) - //private Set roles; - private Role role; + private Set roles; - public void setRole(Role role) { - this.role = role; - } + public void setRoles(Set roles) { this.roles = roles; } + public Set getRoles() { return roles; } public void setId(Integer id) { this.customer_id = id; } + public Integer getCustomer_id() { return customer_id; } public void setPseudo(String pseudo) { this.pseudo = pseudo; } + public String getPseudo() { return pseudo; } public void setPassword(String password) { this.password = password; } + public String getPassword() { return password; } + + public void setActive(int active) { this.active = active; } + public int getActive() { return active; } } \ No newline at end of file diff --git a/PFE06/src/main/java/com/PFE/ServerManager/MainController.java b/PFE06/src/main/java/com/PFE/ServerManager/MainController.java index dcb46af..1c2916f 100644 --- a/PFE06/src/main/java/com/PFE/ServerManager/MainController.java +++ b/PFE06/src/main/java/com/PFE/ServerManager/MainController.java @@ -4,6 +4,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; +import java.util.HashSet; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.Authentication; @Controller public class MainController { @@ -14,9 +18,22 @@ public class MainController { @Autowired RoleRepository roleRepository; - @RequestMapping(value="/") - public String home(){ - return "home"; + @Autowired + BCryptPasswordEncoder bCryptPasswordEncoder; + + @GetMapping(value="/") + public String homeRedirection(){ + return "redirect:home"; + } + + @GetMapping(value="/home") + public ModelAndView home() { + ModelAndView modelAndView = new ModelAndView(); + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + Customer customer = customerRepository.findByPseudo(auth.getName()); + modelAndView.addObject("customerName", customer.getPseudo()); + modelAndView.setViewName("home"); + return modelAndView; } @GetMapping(path="/registration") @@ -24,20 +41,28 @@ public class MainController { return "registration";//fait le lien automatiquement avec le page html du même nom //return "redirect:/...."; } + @GetMapping(path="/denied") + public String denied() { + return "denied"; + } + @PostMapping(path="/registration") public ModelAndView addNewUser(@RequestParam String pseudo, @RequestParam String password) { //Model map, ModelAndView ou l'utilisation direct comme dans la méthode précédente sont 3 méthodes qui permettent d'envoyer des informations et donc de changer l'apparence d'une page ModelAndView modelAndView = new ModelAndView(); // il n'est peut être pas utile d'utiliser ModelAndView Customer n = new Customer(); n.setPseudo(pseudo); - n.setPassword(password); + n.setPassword(bCryptPasswordEncoder.encode(password)); + n.setActive(1); Customer temp = customerRepository.findByPseudo(pseudo); - /*Role nRole = roleRepository.findByRole("ADMIN"); - n.setRoles(new HashSet(Arrays.asList(nRole)));*/ Role role = new Role(); // l'utilisation d'un role au lieu d'un tableau semble valide, ormis la première ligne de la table qui n'est pas utilisé role.setRole("ADMIN"); - n.setRole(role); + + HashSet hset = new HashSet(); + hset.add(role); + + n.setRoles(hset); if(temp != null) { modelAndView.addObject("ok", "l'utilisateur existe déjà"); @@ -46,45 +71,24 @@ public class MainController { else { modelAndView.addObject("ok", "l'utilisateur a bien été ajouté"); customerRepository.save(n); - } + } modelAndView.setViewName("registration"); return modelAndView; } @GetMapping(path="/login") - public ModelAndView login(){ + public ModelAndView login() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("login"); return modelAndView; } - //////// Ne fonctionne pas ///////// - /*public String login() { - return "login"; //return "redirect:/...."; //to send a request to redirect the current page - }*/ - /* - @PostMapping(path="/login") - public ModelAndView connexion(@RequestParam String pseudo, @RequestParam String password) { - // @RequestParam means it is a parameter from the GET or POST request - //the model Map is used by thymeleaf as a storage for values display on the html page, this is the same way for ModelAndView - ModelAndView modelAndView = new ModelAndView(); - Customer temp = customerRepository.findByPseudo(pseudo); - if(temp != null) { - modelAndView.addObject("error", "vous etes autorisé à être sur cette page"); - } - else{ - modelAndView.addObject("error", "vous n'etes pas autorisé à être sur cette page"); - } - modelAndView.setViewName("login"); - return modelAndView; - }*/ - ////////////////////////// @GetMapping(path="/all") public @ResponseBody Iterable getAllUsers() { return customerRepository.findAll(); } - @RequestMapping(value="/success") + @GetMapping(value="/success") public String success(){ return "success"; } diff --git a/PFE06/src/main/java/com/PFE/ServerManager/Role.java b/PFE06/src/main/java/com/PFE/ServerManager/Role.java index bf3560c..dd5affb 100644 --- a/PFE06/src/main/java/com/PFE/ServerManager/Role.java +++ b/PFE06/src/main/java/com/PFE/ServerManager/Role.java @@ -21,4 +21,8 @@ public class Role { public void setRole(String role) { this.role = role; } + public String getRole() { return role; } + + public void setRole_id(Integer role_id) { this.role_id = role_id; } + public Integer getRole_id() { return role_id; } } \ No newline at end of file diff --git a/PFE06/src/main/java/com/PFE/ServerManager/SecurityConfig.java b/PFE06/src/main/java/com/PFE/ServerManager/SecurityConfig.java index 0de7503..dff960a 100644 --- a/PFE06/src/main/java/com/PFE/ServerManager/SecurityConfig.java +++ b/PFE06/src/main/java/com/PFE/ServerManager/SecurityConfig.java @@ -6,6 +6,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.sql.DataSource; @@ -17,27 +19,38 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { DataSource dataSource; @Autowired + private BCryptPasswordEncoder passwordEncoder; + + @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication() .dataSource(dataSource) - .usersByUsernameQuery("select pseudo, password from customer where pseudo=?") - .authoritiesByUsernameQuery("select u.pseudo, r.role from customer u inner join customer_role ur on(u.customer_id=ur.customer_id) inner join role r on(ur.role_id=r.role_id) where u.pseudo=?"); + .passwordEncoder(passwordEncoder) + .usersByUsernameQuery("select pseudo, password , active from customer where pseudo=?") + .authoritiesByUsernameQuery("select c.pseudo, r.role from customer c inner join customer_role cr on(c.customer_id=cr.customer_id) inner join role r on(cr.role_id=r.role_id) where c.pseudo=?"); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() - .antMatchers("/").permitAll() + .antMatchers("/home").hasAuthority("ADMIN") .antMatchers("/registration").permitAll() .antMatchers("/login").permitAll() - //.antMatchers("/registration").hasRole("ADMIN").anyRequest().authenticated() + .antMatchers("/denied").permitAll() + .anyRequest().authenticated() .and() .formLogin() - .loginPage("/login").failureUrl("/login?error=true").defaultSuccessUrl("/success") + .loginPage("/login").failureUrl("/login?error=true") + .defaultSuccessUrl("/success") + .usernameParameter("pseudo") + .passwordParameter("password") .and() .logout() - .permitAll(); - //http.exceptionHandling().accessDeniedPage("/403"); + .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) + .logoutSuccessUrl("/") + .and() + .exceptionHandling() + .accessDeniedPage("/denied"); } } \ No newline at end of file diff --git a/PFE06/src/main/java/com/PFE/ServerManager/WebMvcConfig.java b/PFE06/src/main/java/com/PFE/ServerManager/WebMvcConfig.java new file mode 100644 index 0000000..fd7a001 --- /dev/null +++ b/PFE06/src/main/java/com/PFE/ServerManager/WebMvcConfig.java @@ -0,0 +1,16 @@ +package com.PFE.ServerManager; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + @Bean + public BCryptPasswordEncoder bCryptpasswordEncoder() { + return new BCryptPasswordEncoder(); + } + +} \ No newline at end of file diff --git a/PFE06/src/main/resources/application.properties b/PFE06/src/main/resources/application.properties index bb9b2d6..b7fb345 100644 --- a/PFE06/src/main/resources/application.properties +++ b/PFE06/src/main/resources/application.properties @@ -8,9 +8,9 @@ spring.jpa.hibernate.ddl-auto=create #"update" met à jour la base données #Simon Postgres config : -spring.datasource.url=jdbc:postgresql://localhost:5432/sql_only +spring.datasource.url=jdbc:postgresql://localhost:3306/sql_only spring.datasource.username=postgres -spring.datasource.password=idalurf123 +spring.datasource.password=admin #Antoine Postgres config : #spring.datasource.url=jdbc:postgresql://localhost:3302/sql_only diff --git a/PFE06/src/main/resources/data.sql b/PFE06/src/main/resources/data.sql index 98ec008..0465efc 100644 --- a/PFE06/src/main/resources/data.sql +++ b/PFE06/src/main/resources/data.sql @@ -1,6 +1,8 @@ /* ce fichier doit être placé dans les ressources afin d'être utilisé */ INSERT INTO "role" VALUES (1,'ADMIN'); -/*INSERT INTO "customer" VALUES (10,1,'Feutrier','Simon'); -INSERT INTO "customer" VALUES (11,1,'Duquenoy','Antoine'); +/* +INSERT INTO "customer" VALUES (1,1,'Feutrier','Simon'); +INSERT INTO "customer" VALUES (2,1,'Duquenoy','Antoine'); INSERT INTO "customer_role" VALUES (1,1); -INSERT INTO "customer_role" VALUES (2,1);*/ \ No newline at end of file +INSERT INTO "customer_role" VALUES (2,1); +*/ \ No newline at end of file diff --git a/PFE06/src/main/resources/templates/denied.html b/PFE06/src/main/resources/templates/denied.html new file mode 100644 index 0000000..6b12fb8 --- /dev/null +++ b/PFE06/src/main/resources/templates/denied.html @@ -0,0 +1,16 @@ + + + + + + Access Denied + + +

Access Denied !

+ +
+ +
+ + + \ No newline at end of file diff --git a/PFE06/src/main/resources/templates/home.html b/PFE06/src/main/resources/templates/home.html index 50d943b..4a2b035 100644 --- a/PFE06/src/main/resources/templates/home.html +++ b/PFE06/src/main/resources/templates/home.html @@ -6,7 +6,17 @@ Page d'accueil -connexion -enregistrer des utilisateurs + + Connexion + Enregistrer des utilisateurs + +
+ +
+ + +

est connecté(e) !

+ + \ No newline at end of file diff --git a/PFE06/src/main/resources/templates/login.html b/PFE06/src/main/resources/templates/login.html index 4bac2e0..8284378 100644 --- a/PFE06/src/main/resources/templates/login.html +++ b/PFE06/src/main/resources/templates/login.html @@ -6,7 +6,7 @@
-
Ajouter de nouveaux utilisateurs :
+
Se connecter :
@@ -16,7 +16,7 @@
- +