Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 0 additions & 3 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ All Rights Reserved.
Licensed under the LinkedIn Learning Exercise File License (the "License").
See LICENSE in the project root for license information.

ATTRIBUTIONS:
[PLEASE PROVIDE ATTRIBUTIONS OR DELETE THIS AND THE ABOVE LINE “ATTRIBUTIONS”]

Please note, this project may automatically load third party code from external
repositories (for example, NPM modules, Composer packages, or other dependencies).
If so, such third party code may be subject to other license terms than as set
Expand Down
18 changes: 7 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ This is the repository for the LinkedIn Learning course `Spring 6: Spring Securi

## Course Description

This comprehensive Spring Security course provides an in-depth exploration of security implementation in Java applications, covering critical topics from core authentication concepts to advanced security techniques. Learn to implement various authentication methods including in-memory, JDBC, and LDAP authentication, master password hashing with bcrypt, develop form-based and OAuth2 authentication strategies, and secure WebFlux-based systems. The course progresses through practical implementations of controller method authorizations, login page configurations, and advanced security frameworks, equipping you with the skills to protect web applications using Spring Security's robust toolset across different architectural approaches.

_See the readme file in the main branch for updated instructions and information._
## Instructions
This repository has branches for each of the videos in the course. You can use the branch pop up menu in github to switch to a specific branch and take a look at the course at that stage, or you can add `/tree/BRANCH_NAME` to the URL to go to the branch you want to access.
Expand All @@ -24,24 +26,18 @@ To resolve this issue:
Add changes to git using this command: git add .
Commit changes using this command: git commit -m "some message"

## Installing
1. To use these exercise files, you must have the following installed:
- [list of requirements for course]
2. Clone this repository into your local machine using the terminal (Mac), CMD (Windows), or a GUI tool like SourceTree.
3. [Course-specific instructions]

## Instructor

Instructor name
Frank P Moley III

Instructor description
Principal Software Architect at Vertex, Inc.



Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/).
Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/frank-p-moley-iii?u=104).


[0]: # (Replace these placeholder URLs with actual course URLs)

[lil-course-url]: https://www.linkedin.com/learning/
[lil-thumbnail-url]: https://media.licdn.com/dms/image/v2/D4E0DAQG0eDHsyOSqTA/learning-public-crop_675_1200/B4EZVdqqdwHUAY-/0/1741033220778?e=2147483647&v=beta&t=FxUDo6FA8W8CiFROwqfZKL_mzQhYx9loYLfjN-LNjgA
[lil-course-url]: https://www.linkedin.com/learning/spring-6-spring-security
[lil-thumbnail-url]: https://media.licdn.com/dms/image/v2/D4E0DAQGM42dYNIUQUw/learning-public-crop_675_1200/B4EZaNvIdDHoAY-/0/1746134665323?e=2147483647&v=beta&t=_d-79CVF9PcZt994YTHF1qhQl94G3OXpRDEJLCb1qG4
34 changes: 31 additions & 3 deletions admin-web/pom.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
Expand Down Expand Up @@ -37,7 +37,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>annotationProcessor</scope>
<version>1.18.42</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -51,7 +51,16 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
Expand All @@ -63,6 +72,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand All @@ -71,6 +85,20 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.42</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>

</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.frankmoley.lil.admin_web.config;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests)-> requests
.requestMatchers("/", "/index").permitAll()
.requestMatchers("/customers/**").hasRole("USER")
.requestMatchers("/orders/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public GrantedAuthoritiesMapper authoritiesMapper() {
SimpleAuthorityMapper authorityMapper = new SimpleAuthorityMapper();
// Converts "user" from DB to "ROLE_USER" internally
authorityMapper.setConvertToUpperCase(true);
// Optional: Sets a default role if none found
return authorityMapper;
}

@Bean
public UserDetailsService userDetailsService(DataSource dataSource){
return new JdbcUserDetailsManager(dataSource);
}

}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.frankmoley.lil.admin_web.web.controller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -23,43 +25,55 @@
@RequestMapping("/customers")
public class CustomerController {

private final CustomerRepository customerRepository;
private final OrderRepository orderRepository;
private final CustomerRepository customerRepository;
private final OrderRepository orderRepository;

public CustomerController(CustomerRepository customerRepository, OrderRepository orderRepository) {
this.customerRepository = customerRepository;
this.orderRepository = orderRepository;
}
public CustomerController(CustomerRepository customerRepository, OrderRepository orderRepository) {
this.customerRepository = customerRepository;
this.orderRepository = orderRepository;
}

@GetMapping
public String getAllUsers(Model model) {
Iterable<Customer> customersIterable = this.customerRepository.findAll();
List<Customer> customers = new ArrayList<>();
customersIterable.forEach(customers::add);
customers.sort(new Comparator<Customer>() {
@Override
public int compare(Customer o1, Customer o2) {
return o1.getName().compareTo(o2.getName());
}
});
model.addAttribute("customers", customers);
model.addAttribute("module", "customers");
return "customers";
}

@GetMapping(path = "/{id}")
public String getUser(@PathVariable("id") UUID customerId, Model model, Principal principal) {
Optional<Customer> customer = this.customerRepository.findById(customerId);
if (customer.isEmpty()) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found");
}
model.addAttribute("customer", customer.get());

// 1. Check if the principal is the expected token type
if (principal instanceof UsernamePasswordAuthenticationToken token) {
// 2. Iterate through authorities to find ROLE_ADMIN
boolean isAdmin = token.getAuthorities().stream()
.anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"));

// 3. Only load sensitive data if authorized
if (isAdmin) {
Iterable<Order> ordersIterable = this.orderRepository.findAllByCustomerId(customer.get().getId());
List<Order> orders = new ArrayList<>();
ordersIterable.forEach(orders::add);
model.addAttribute("module", "customers");
}
}

@GetMapping
public String getAllUsers(Model model) {
Iterable<Customer> customersIterable = this.customerRepository.findAll();
List<Customer> customers = new ArrayList<>();
customersIterable.forEach(customers::add);
customers.sort(new Comparator<Customer>() {
@Override
public int compare(Customer o1, Customer o2) {
return o1.getName().compareTo(o2.getName());
}
});
model.addAttribute("customers", customers);
model.addAttribute("module", "customers");
return "customers";
}

@GetMapping(path = "/{id}")
public String getUser(@PathVariable("id") UUID customerId, Model model) {
Optional<Customer> customer = this.customerRepository.findById(customerId);
if (customer.isEmpty()) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "entity not found");
return "detailed_customer";
}
model.addAttribute("customer", customer.get());
Iterable<Order> ordersIterable = this.orderRepository.findAllByCustomerId(customer.get().getId());
List<Order> orders = new ArrayList<>();
ordersIterable.forEach(orders::add);
model.addAttribute("orders", orders);
model.addAttribute("module", "customers");
return "detailed_customer";
}
}
9 changes: 8 additions & 1 deletion admin-web/src/main/resources/data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,11 @@ INSERT INTO customers (customer_id, name, contact_name, email, phone) values (RA

INSERT INTO orders (order_id, customer_id, order_info) values (RANDOM_UUID(), (SELECT customer_id FROM customers where name = 'Acme'), '1500 Widgets');
INSERT INTO orders (order_id, customer_id, order_info) values (RANDOM_UUID(), (SELECT customer_id FROM customers where name = 'Acme'), '3000 Widgets');
INSERT INTO orders (order_id, customer_id, order_info) values (RANDOM_UUID(), (SELECT customer_id FROM customers where name = 'Callahan Auto'), '200 Widgets');
INSERT INTO orders (order_id, customer_id, order_info) values (RANDOM_UUID(), (SELECT customer_id FROM customers where name = 'Callahan Auto'), '200 Widgets');

INSERT INTO users (username, password, enabled) values ('user', '{bcrypt}$2a$10$fpf1oIOBIH2c.k4HwBqbLe4EnXeL9il7b6rnUB9CWdE8MNp3yQyfK', true);
INSERT INTO users (username, password, enabled) values ('admin', '{bcrypt}$2a$10$fpf1oIOBIH2c.k4HwBqbLe4EnXeL9il7b6rnUB9CWdE8MNp3yQyfK', true);

INSERT INTO authorities (username, authority) values ('user', 'ROLE_USER');
INSERT INTO authorities (username, authority) values ('admin', 'ROLE_USER');
INSERT INTO authorities (username, authority) values ('admin', 'ROLE_ADMIN');
17 changes: 16 additions & 1 deletion admin-web/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,19 @@ CREATE TABLE orders(
customer_id UUID not null,
order_info varchar (2048) not null,
foreign key (customer_id) references customers(customer_id)
);
);

CREATE TABLE users (
username varchar_ignorecase(50) primary key,
password varchar_ignorecase(500) not null,
enabled boolean not null
);

CREATE TABLe authorities (
username varchar_ignorecase(50) not null,
authority varchar_ignorecase(50) not null,
foreign key(username) references users(username)
);

CREATE UNIQUE INDEX idx_auth_username on authorities (username,authority);

6 changes: 3 additions & 3 deletions admin-web/src/main/resources/templates/detailed_customer.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">

<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
Expand All @@ -22,7 +22,7 @@ <h5 class="card-subtitle" th:text="${customer.contactName}">Contact Name</h5>
<a class="btn btn-primary btn-sm" href="#" th:href="@{mailto:{to}(to=${customer.email})}">Send Email</a>
</div>
</div>
<div class="container">
<div class="container" sec:authorize="hasAuthority('ROLE_ADMIN')">
<table class="table">
<thead>
<th scope="col">Order Number</th>
Expand Down