Authentication proves who a user is (username and password), while authorization decides what that proven user is allowed to do. Spring Security handles them in two separate steps: first the user is authenticated, and only then the access rules for roles are checked. Keeping them separate is what lets a university system give Admin, Faculty and Student users different powers over the same application. A failed authentication returns 401 Unauthorized, while a failed authorization returns 403 Forbidden.
Features
- Authentication of users from MySQL using
UserDetailsServiceand BCrypt password hashing - Role-based authorization for three roles: ADMIN, FACULTY and STUDENT
- URL-level rules (
/api/admin/**,/api/faculty/**,/api/student/**) - Data-level authorization with
@PreAuthorize: a student can open only their own profile - Different JSON messages for
401(authentication failed) and403(authorization failed) - A
/api/auth/meendpoint that shows the authenticated user and their roles
Authentication vs Authorization Types
Side-by-side comparison
| Aspect | Authentication | Authorization |
|---|---|---|
| Question answered | Who are you? | What are you allowed to do? |
| Happens | First | After authentication succeeds |
| Input | Username and password (credentials) | Roles / authorities of the authenticated user |
| Failure result | 401 Unauthorized |
403 Forbidden |
| Spring Security parts | BasicAuthenticationFilter, AuthenticationManager, UserDetailsService, PasswordEncoder |
AuthorizationFilter, authorizeHttpRequests, @PreAuthorize |
| University example | Faculty member logs in with a valid password | Faculty can create courses but cannot manage user accounts |
Authentication types
| Type | Explanation |
|---|---|
| Password-based (Basic / Form login) | The user sends a username and password. Used in this project (HTTP Basic). |
| Token-based (JWT) | The user logs in once, receives a token and sends it with each request. |
| Multi-factor | A second proof, such as an OTP, is required in addition to the password. |
Authorization types
| Type | Explanation |
|---|---|
| Role-based (RBAC) | Access depends on the role: ADMIN, FACULTY, STUDENT. Used here for URL rules. |
| URL-based | Rules attached to URL patterns in SecurityFilterChain. |
| Method-based | Rules on service methods with @PreAuthorize. |
| Ownership / data-level | Access depends on whose data is requested, e.g. #username == authentication.name. Used here for profiles. |
Hands-on Experiment: University Management System with Authentication and Authorization
To build a university application that authenticates users from MySQL and authorizes access for Admin, Faculty and Student roles, showing clearly when a request fails authentication (401) and when it fails authorization (403).
Software/Tools Required
- JDK 17
- Spring Boot 3.x
- Maven
- MySQL 8.x
- IDE (IntelliJ IDEA / Eclipse / STS)
- Postman
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
Open https://start.spring.io and select:
| Setting | Value |
|---|---|
| Project | Maven |
| Language | Java |
| Spring Boot | 3.3.x |
| Group | com.example |
| Artifact | university-management-system |
| Packaging | Jar |
| Java | 17 |
| Dependencies | Spring Web, Spring Security, Spring Data JPA, MySQL Driver |
Click Generate, extract the zip and open it in your IDE.
Step 2: Project Structure
university-management-system
├── pom.xml
└── src/main
├── java/com/example/university
│ ├── UniversityManagementApplication.java
│ ├── entity
│ │ ├── UserAccount.java
│ │ └── Course.java
│ ├── repository
│ │ ├── UserAccountRepository.java
│ │ └── CourseRepository.java
│ ├── service
│ │ ├── UserAccountService.java
│ │ ├── CourseService.java
│ │ ├── DataInitializer.java
│ │ └── SecurityConfig.java
│ └── controller
│ ├── AuthController.java
│ ├── AdminController.java
│ ├── FacultyController.java
│ ├── StudentController.java
│ └── ProfileController.java
└── resources
└── application.properties
Step 3: Creating the files according to the project structure
package com.example.university.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "courses")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String code;
@Column(nullable = false)
private String name;
private Integer credits;
// username of the faculty member who teaches the course
private String facultyUsername;
public Course() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getCredits() { return credits; }
public void setCredits(Integer credits) { this.credits = credits; }
public String getFacultyUsername() { return facultyUsername; }
public void setFacultyUsername(String facultyUsername) { this.facultyUsername = facultyUsername; }
}
package com.example.university.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "user_accounts")
public class UserAccount {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String fullName;
@Column(nullable = false, unique = true)
private String username;
// Accepted in requests, never returned in responses
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Column(nullable = false)
private String password;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String department;
// ADMIN, FACULTY or STUDENT
private String role;
public UserAccount() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; }
public String getRole() { return role; }
public void setRole(String role) { this.role = role; }
}
package com.example.university.repository;
import com.example.university.entity.Course;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CourseRepository extends JpaRepository<Course, Long> {
List<Course> findByFacultyUsername(String facultyUsername);
boolean existsByCode(String code);
}
package com.example.university.repository;
import com.example.university.entity.UserAccount;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional;
public interface UserAccountRepository extends JpaRepository<UserAccount, Long> {
Optional<UserAccount> findByUsername(String username);
List<UserAccount> findByRole(String role);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
}
package com.example.university.service;
import com.example.university.entity.Course;
import com.example.university.repository.CourseRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CourseService {
private final CourseRepository courseRepository;
public CourseService(CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
public List<Course> getAll() {
return courseRepository.findAll();
}
public List<Course> getByFaculty(String facultyUsername) {
return courseRepository.findByFacultyUsername(facultyUsername);
}
public Course create(Course course, String facultyUsername) {
if (course.getCode() == null || course.getCode().trim().isEmpty()
|| course.getName() == null || course.getName().trim().isEmpty()) {
throw new IllegalArgumentException("code and name are required");
}
if (course.getCredits() == null || course.getCredits() <= 0) {
throw new IllegalArgumentException("credits must be greater than 0");
}
if (courseRepository.existsByCode(course.getCode())) {
throw new IllegalArgumentException("Course code already exists");
}
course.setId(null);
course.setFacultyUsername(facultyUsername);
return courseRepository.save(course);
}
}
package com.example.university.service;
import com.example.university.entity.Course;
import com.example.university.entity.UserAccount;
import com.example.university.repository.CourseRepository;
import com.example.university.repository.UserAccountRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/**
* Creates sample accounts (ADMIN, FACULTY, two STUDENTS) and two courses
* the first time the application starts.
*/
@Component
public class DataInitializer implements CommandLineRunner {
private final UserAccountRepository userAccountRepository;
private final CourseRepository courseRepository;
private final PasswordEncoder passwordEncoder;
public DataInitializer(UserAccountRepository userAccountRepository, CourseRepository courseRepository,
PasswordEncoder passwordEncoder) {
this.userAccountRepository = userAccountRepository;
this.courseRepository = courseRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
public void run(String... args) {
if (userAccountRepository.count() == 0) {
userAccountRepository.save(user("Admin User", "admin", "Admin@123", "admin@university.edu", "Administration", "ADMIN"));
userAccountRepository.save(user("Dr. Rao", "faculty", "Faculty@123", "rao@university.edu", "Computer Science", "FACULTY"));
userAccountRepository.save(user("Sam Student", "student", "Student@123", "sam@university.edu", "Computer Science", "STUDENT"));
userAccountRepository.save(user("Nina Student", "nina", "Nina@123", "nina@university.edu", "Computer Science", "STUDENT"));
}
if (courseRepository.count() == 0) {
courseRepository.save(course("CS101", "Introduction to Programming", 4, "faculty"));
courseRepository.save(course("CS201", "Data Structures", 4, "faculty"));
}
}
private UserAccount user(String fullName, String username, String rawPassword,
String email, String department, String role) {
UserAccount user = new UserAccount();
user.setFullName(fullName);
user.setUsername(username);
user.setPassword(passwordEncoder.encode(rawPassword));
user.setEmail(email);
user.setDepartment(department);
user.setRole(role);
return user;
}
private Course course(String code, String name, int credits, String facultyUsername) {
Course course = new Course();
course.setCode(code);
course.setName(name);
course.setCredits(credits);
course.setFacultyUsername(facultyUsername);
return course;
}
}
package com.example.university.service;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import java.io.IOException;
/**
* Security configuration. Kept in the service package because only four packages are used.
*
* AUTHENTICATION = proving who you are -> failure gives 401 Unauthorized
* AUTHORIZATION = what you are allowed to do -> failure gives 403 Forbidden
*/
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// AUTHORIZATION rules (checked only after authentication succeeded)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error", "/api/public/**", "/api/auth/register").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/faculty/**").hasAnyRole("FACULTY", "ADMIN")
.requestMatchers("/api/student/**").hasRole("STUDENT")
.anyRequest().authenticated())
// AUTHENTICATION mechanism: HTTP Basic (username and password in the header)
.httpBasic(Customizer.withDefaults())
.exceptionHandling(ex -> ex
// Not logged in, or wrong username / password
.authenticationEntryPoint((request, response, authException) ->
writeJson(response, 401, "Unauthorized",
"Authentication failed - login credentials are missing or incorrect"))
// Logged in, but the role is not allowed to do this
.accessDeniedHandler((request, response, accessDeniedException) ->
writeJson(response, 403, "Forbidden",
"Authorization failed - your role is not allowed to access this resource")));
return http.build();
}
private static void writeJson(HttpServletResponse response, int status, String error, String message)
throws IOException {
response.setStatus(status);
response.setContentType("application/json");
response.getWriter().write("{\"status\":" + status
+ ",\"error\":\"" + error + "\",\"message\":\"" + message + "\"}");
}
}
package com.example.university.service;
import com.example.university.entity.UserAccount;
import com.example.university.repository.UserAccountRepository;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@Service
public class UserAccountService implements UserDetailsService {
private static final Set<String> VALID_ROLES = Set.of("ADMIN", "FACULTY", "STUDENT");
private final UserAccountRepository userAccountRepository;
private final PasswordEncoder passwordEncoder;
public UserAccountService(UserAccountRepository userAccountRepository, PasswordEncoder passwordEncoder) {
this.userAccountRepository = userAccountRepository;
this.passwordEncoder = passwordEncoder;
}
// ---------- AUTHENTICATION: who are you? ----------
// Called by Spring Security during login to load the user from MySQL
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserAccount user = userAccountRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
return User.withUsername(user.getUsername())
.password(user.getPassword())
.roles(user.getRole())
.build();
}
// Public self-registration: always creates a STUDENT
public UserAccount register(UserAccount user) {
return save(user, "STUDENT");
}
// Admin creates any kind of account (ADMIN, FACULTY or STUDENT)
public UserAccount createByAdmin(UserAccount user) {
String role = user.getRole() == null ? "" : user.getRole().trim().toUpperCase();
if (!VALID_ROLES.contains(role)) {
throw new IllegalArgumentException("role must be ADMIN, FACULTY or STUDENT");
}
return save(user, role);
}
// ---------- AUTHORIZATION: what are you allowed to do? ----------
public List<UserAccount> getAll() {
return userAccountRepository.findAll();
}
public List<UserAccount> getByRole(String role) {
return userAccountRepository.findByRole(role);
}
public Optional<UserAccount> findByUsername(String username) {
return userAccountRepository.findByUsername(username);
}
// DATA-LEVEL AUTHORIZATION: ADMIN and FACULTY can open any profile,
// everybody else can open only their own profile.
@PreAuthorize("hasAnyRole('ADMIN','FACULTY') or #username == authentication.name")
public Optional<UserAccount> getProfile(String username) {
return userAccountRepository.findByUsername(username);
}
private UserAccount save(UserAccount user, String role) {
if (isBlank(user.getFullName()) || isBlank(user.getUsername()) || isBlank(user.getPassword())
|| isBlank(user.getEmail()) || isBlank(user.getDepartment())) {
throw new IllegalArgumentException("fullName, username, password, email and department are required");
}
if (userAccountRepository.existsByUsername(user.getUsername())) {
throw new IllegalArgumentException("Username already exists");
}
if (userAccountRepository.existsByEmail(user.getEmail())) {
throw new IllegalArgumentException("Email already registered");
}
user.setId(null);
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setRole(role);
return userAccountRepository.save(user);
}
private boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
}
package com.example.university.controller;
import com.example.university.entity.UserAccount;
import com.example.university.service.UserAccountService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
// ADMIN only (rule "/api/admin/**" in SecurityConfig)
@RestController
@RequestMapping("/api/admin")
public class AdminController {
private final UserAccountService userAccountService;
public AdminController(UserAccountService userAccountService) {
this.userAccountService = userAccountService;
}
@GetMapping("/users")
public List<UserAccount> allUsers() {
return userAccountService.getAll();
}
@PostMapping("/users")
public ResponseEntity<?> createUser(@RequestBody UserAccount user) {
try {
UserAccount saved = userAccountService.createByAdmin(user);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
}
package com.example.university.controller;
import com.example.university.entity.UserAccount;
import com.example.university.service.UserAccountService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class AuthController {
private final UserAccountService userAccountService;
public AuthController(UserAccountService userAccountService) {
this.userAccountService = userAccountService;
}
// Public: student self-registration
@PostMapping("/auth/register")
public ResponseEntity<?> register(@RequestBody UserAccount user) {
try {
UserAccount saved = userAccountService.register(user);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
// Public: no login required
@GetMapping("/public/info")
public Map<String, String> info() {
return Map.of(
"system", "University Management System",
"message", "Public endpoint - no login required");
}
// Any logged-in user: the result of AUTHENTICATION (who) and the roles used for AUTHORIZATION (what)
@GetMapping("/auth/me")
public Map<String, Object> me(Authentication authentication) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("username", authentication.getName());
result.put("authenticated", authentication.isAuthenticated());
result.put("roles", authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority).toList());
return result;
}
}
package com.example.university.controller;
import com.example.university.entity.Course;
import com.example.university.entity.UserAccount;
import com.example.university.service.CourseService;
import com.example.university.service.UserAccountService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
// FACULTY and ADMIN (rule "/api/faculty/**" in SecurityConfig)
@RestController
@RequestMapping("/api/faculty")
public class FacultyController {
private final CourseService courseService;
private final UserAccountService userAccountService;
public FacultyController(CourseService courseService, UserAccountService userAccountService) {
this.courseService = courseService;
this.userAccountService = userAccountService;
}
// Courses taught by the logged-in faculty member
@GetMapping("/courses")
public List<Course> myCourses(Authentication authentication) {
return courseService.getByFaculty(authentication.getName());
}
@PostMapping("/courses")
public ResponseEntity<?> createCourse(@RequestBody Course course, Authentication authentication) {
try {
Course saved = courseService.create(course, authentication.getName());
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
@GetMapping("/students")
public List<UserAccount> students() {
return userAccountService.getByRole("STUDENT");
}
}
package com.example.university.controller;
import com.example.university.entity.UserAccount;
import com.example.university.service.UserAccountService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Any logged-in user may call this URL, but UserAccountService.getProfile()
* (@PreAuthorize) decides whose profile the caller may actually read.
*/
@RestController
@RequestMapping("/api/profiles")
public class ProfileController {
private final UserAccountService userAccountService;
public ProfileController(UserAccountService userAccountService) {
this.userAccountService = userAccountService;
}
@GetMapping("/{username}")
public ResponseEntity<UserAccount> profile(@PathVariable String username) {
return userAccountService.getProfile(username)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
}
package com.example.university.controller;
import com.example.university.entity.Course;
import com.example.university.entity.UserAccount;
import com.example.university.service.CourseService;
import com.example.university.service.UserAccountService;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
// STUDENT only (rule "/api/student/**" in SecurityConfig)
@RestController
@RequestMapping("/api/student")
public class StudentController {
private final CourseService courseService;
private final UserAccountService userAccountService;
public StudentController(CourseService courseService, UserAccountService userAccountService) {
this.courseService = courseService;
this.userAccountService = userAccountService;
}
@GetMapping("/dashboard")
public Map<String, Object> dashboard(Authentication authentication) {
UserAccount student = userAccountService.findByUsername(authentication.getName()).orElseThrow();
return Map.of(
"message", "Welcome to the student dashboard, " + student.getFullName(),
"department", student.getDepartment(),
"availableCourses", courseService.getAll().size());
}
@GetMapping("/courses")
public List<Course> courses() {
return courseService.getAll();
}
}
package com.example.university;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UniversityManagementApplication {
public static void main(String[] args) {
SpringApplication.run(UniversityManagementApplication.class, args);
}
}
spring.application.name=university-management-system
server.port=8080
# MySQL (database is created automatically if it does not exist)
spring.datasource.url=jdbc:mysql://localhost:3306/university_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
# JPA / Hibernate
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=falseCode language: PHP (php)
Step 4: Run the UniversityManagementApplication


