Skip to content

Part6 #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 42 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
f07a7fd
adding example files
jt1088 Jun 16, 2015
4ed4d5d
creating branch
jt1088 Jun 16, 2015
02a1d4b
added tutorial files
jt1088 Jun 25, 2015
7498629
updated readme for part 4
jt1088 Jun 29, 2015
1472665
Adding source files for web app
jt1088 Jun 30, 2015
e9f75d8
Adding source files for web app
jt1088 Jun 30, 2015
4d4df2a
creating new branch
jt1088 Jun 30, 2015
7decc81
updated for delete method
jt1088 Sep 10, 2015
c59d7a6
updating readme
jt1088 Sep 10, 2015
b9537ba
updating menu url
springframeworkguru Nov 19, 2015
767c81f
Updated pom.xml to use SpringBoot 1.4.2 and updated WebConfiguration …
Dec 6, 2016
aedd7ef
Merge pull request #13 from ximanta/part4
springframeworkguru Dec 6, 2016
7b113c0
Updated RepositoryConfiguration, ProductRepositoryTest, and SpringBoo…
Dec 7, 2016
057d71d
Merge pull request #16 from ximanta/part4
springframeworkguru Dec 7, 2016
bcf5851
Merge remote-tracking branch 'remotes/origin/part4' into part5
springframeworkguru Dec 7, 2016
3195809
Merge remote-tracking branch 'remotes/origin/part4' into part5
springframeworkguru Dec 7, 2016
05c2119
Merge branch 'part5' of https://github.com/springframeworkguru/spring…
springframeworkguru Dec 7, 2016
6446802
Added Spring Security for authentication and role-based authorization
Dec 10, 2016
64bd754
Merge pull request #17 from ximanta/part5
springframeworkguru Dec 10, 2016
6813313
added templates dir & temp file for git
springframeworkguru Dec 15, 2016
f7cc64d
Updated README.md
Dec 16, 2016
8e7b94a
Added DAO Provider implementation for authentication
Jan 17, 2017
c696392
Added DAO Provider implementation for authentication. Known Issues.
Jan 17, 2017
67c4035
Added UserServiceImpl
Jan 18, 2017
4668f5e
Added Bootstrap
Jan 22, 2017
f6a30f8
Added Bootstrap and JQuery CDN
Jan 22, 2017
6bd8e7d
Added Thymeleaf Authorization
Jan 23, 2017
f55cbba
Issue with NullPointerException in ProviderManager.authenticate
Jan 23, 2017
af72352
Resolved NullPointerException of AuthenticationProvider. Issue will i…
Jan 24, 2017
58669e6
Resolved NullPointerException of AuthenticationProvider Issue. Workin…
Jan 24, 2017
44a3235
Merge branch 'part6' into part6
springframeworkguru Jan 24, 2017
8ea9784
Removed unused annotations from CommonBeanConfig and updated all User…
Jan 26, 2017
4ab9016
Merge remote-tracking branch 'origin/part6' into part6
Jan 26, 2017
94ee954
Removed unused imports and createdBy comments
Jan 26, 2017
13921d0
Updated README.md
Jan 26, 2017
dda7c8b
Merge pull request #19 from ximanta/part6
springframeworkguru Jan 26, 2017
b0602c1
Enabled h2 console
Jan 27, 2017
9980ee7
Merge pull request #20 from ximanta/part6
springframeworkguru Jan 27, 2017
22768c2
updated Spring Boot version
springframeworkguru May 4, 2017
1e68e8c
updated Spring Boot version
springframeworkguru May 4, 2017
2614038
Updated to Spring Boot 2.2.2.RELEASE and Java 11
springframeworkguru May 11, 2020
b48686d
Updated to Spring Boot 2.2.2.RELEASE and Java 11
springframeworkguru May 11, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
# Spring Boot Web Application
This repository has the project files for a tutorial series on Spring Boot available from by website at [Spring Framework Guru](https://springframework.guru)

##Part 6
This repository has the project files for the post SPRING BOOT WEB APPLICATION, PART 6 – SPRING SECURITY WITH DAO Authentication Provider
that is part of the tutorial series on Spring Boot available from by website at [Spring Framework Guru](https://springfrspringframework.guru)

## Checkout the full tutorial here!
[Spring Boot - making Spring Fun again!](https://springframework.guru/spring-boot-web-application-part-1-spring-initializr/)
38 changes: 34 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.4.RELEASE</version>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<java.version>11</java.version>
</properties>

<dependencies>
Expand All @@ -36,21 +36,51 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


<!--WebJars-->

<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!--encryption lib-->
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.2</version>
</dependency>

<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt-springsecurity3</artifactId>
<version>1.9.2</version>
</dependency>

</dependencies>

<build>
Expand Down
128 changes: 128 additions & 0 deletions src/main/java/guru/springframework/bootstrap/SpringJpaBootstrap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package guru.springframework.bootstrap;

import guru.springframework.domain.Product;
import guru.springframework.domain.Role;
import guru.springframework.domain.User;
import guru.springframework.repositories.ProductRepository;
import guru.springframework.services.RoleService;
import guru.springframework.services.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
public class SpringJpaBootstrap implements ApplicationListener<ContextRefreshedEvent> {

private ProductRepository productRepository;
private UserService userService;
private RoleService roleService;

private Logger log = LoggerFactory.getLogger(SpringJpaBootstrap.class);

@Autowired
public void setProductRepository(ProductRepository productRepository) {
this.productRepository = productRepository;
}

@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}

@Autowired
public void setRoleService(RoleService roleService) {
this.roleService = roleService;
}


@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
loadProducts();
loadUsers();
loadRoles();
assignUsersToUserRole();
assignUsersToAdminRole();
}

private void loadProducts() {
Product shirt = new Product();
shirt.setDescription("Spring Framework Guru Shirt");
shirt.setPrice(new BigDecimal("18.95"));
shirt.setImageUrl("https://springframework.guru/wp-content/uploads/2015/04/spring_framework_guru_shirt-rf412049699c14ba5b68bb1c09182bfa2_8nax2_512.jpg");
shirt.setProductId("235268845711068308");
productRepository.save(shirt);

log.info("Saved Shirt - id: " + shirt.getId());

Product mug = new Product();
mug.setDescription("Spring Framework Guru Mug");
mug.setImageUrl("https://springframework.guru/wp-content/uploads/2015/04/spring_framework_guru_coffee_mug-r11e7694903c348e1a667dfd2f1474d95_x7j54_8byvr_512.jpg");
mug.setProductId("168639393495335947");
mug.setPrice(new BigDecimal("11.95"));
productRepository.save(mug);

log.info("Saved Mug - id:" + mug.getId());
}

private void loadUsers() {
User user1 = new User();
user1.setUsername("user");
user1.setPassword("user");
userService.saveOrUpdate(user1);

User user2 = new User();
user2.setUsername("admin");
user2.setPassword("admin");
userService.saveOrUpdate(user2);

}

private void loadRoles() {
Role role = new Role();
role.setRole("USER");
roleService.saveOrUpdate(role);
log.info("Saved role" + role.getRole());
Role adminRole = new Role();
adminRole.setRole("ADMIN");
roleService.saveOrUpdate(adminRole);
log.info("Saved role" + adminRole.getRole());
}
private void assignUsersToUserRole() {
List<Role> roles = (List<Role>) roleService.listAll();
List<User> users = (List<User>) userService.listAll();

roles.forEach(role -> {
if (role.getRole().equalsIgnoreCase("USER")) {
users.forEach(user -> {
if (user.getUsername().equals("user")) {
user.addRole(role);
userService.saveOrUpdate(user);
}
});
}
});
}
private void assignUsersToAdminRole() {
List<Role> roles = (List<Role>) roleService.listAll();
List<User> users = (List<User>) userService.listAll();

roles.forEach(role -> {
if (role.getRole().equalsIgnoreCase("ADMIN")) {
users.forEach(user -> {
if (user.getUsername().equals("admin")) {
user.addRole(role);
userService.saveOrUpdate(user);
}
});
}
});
}
}


62 changes: 62 additions & 0 deletions src/main/java/guru/springframework/config/SpringSecConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package guru.springframework.config;

import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SpringSecConfig extends WebSecurityConfigurerAdapter {

private AuthenticationProvider authenticationProvider;

@Autowired
@Qualifier("daoAuthenticationProvider")
public void setAuthenticationProvider(AuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}

@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder passwordEncoder =new BCryptPasswordEncoder();
return passwordEncoder;
}
@Bean("daoAuthenticationProvider")
public AuthenticationProvider daoAuthenticationProvider(UserDetailsService userDetailsService) {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(new BCryptPasswordEncoder());
provider.setUserDetailsService(userDetailsService);
return provider;
}


@Autowired
public void configureAuthManager(AuthenticationManagerBuilder authenticationManagerBuilder){
authenticationManagerBuilder.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests().antMatchers("/","/products","/product/show/*","/console/*","/h2-console/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().permitAll();

httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}


}
15 changes: 15 additions & 0 deletions src/main/java/guru/springframework/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package guru.springframework.config;
import org.h2.server.web.WebServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebConfig {
@Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package guru.springframework.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
@RequestMapping("/")
String index(){
return "index";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package guru.springframework.controllers;

import guru.springframework.domain.Product;
import guru.springframework.services.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ProductController {

private ProductService productService;

@Autowired
public void setProductService(ProductService productService) {
this.productService = productService;
}

@RequestMapping(value = "/products", method = RequestMethod.GET)
public String list(Model model){
model.addAttribute("products", productService.listAllProducts());
return "products";
}

@RequestMapping("product/show/{id}")
public String showProduct(@PathVariable Integer id, Model model){
model.addAttribute("product", productService.getProductById(id));
return "productshow";
}

@RequestMapping("product/edit/{id}")
public String edit(@PathVariable Integer id, Model model){
model.addAttribute("product", productService.getProductById(id));
return "productform";
}

@RequestMapping("product/new")
public String newProduct(Model model){
model.addAttribute("product", new Product());
return "productform";
}

@RequestMapping(value = "product", method = RequestMethod.POST)
public String saveProduct(Product product){
productService.saveProduct(product);
return "redirect:/product/show/" + product.getId();
}

@RequestMapping("product/delete/{id}")
public String delete(@PathVariable Integer id){
productService.deleteProduct(id);
return "redirect:/products";
}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(){
return "login";
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package guru.springframework.converters;

import guru.springframework.domain.User;
import guru.springframework.services.security.UserDetailsImpl;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;

@Component
public class UserToUserDetails implements Converter<User, UserDetails> {
@Override
public UserDetails convert(User user) {
UserDetailsImpl userDetails = new UserDetailsImpl();

if (user != null) {
userDetails.setUsername(user.getUsername());
userDetails.setPassword(user.getEncryptedPassword());
userDetails.setEnabled(user.getEnabled());
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
user.getRoles().forEach(role -> {
authorities.add(new SimpleGrantedAuthority(role.getRole()));
});
userDetails.setAuthorities(authorities);
}

return userDetails;
}
}
Loading