Authorization and Authentication in Java: A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Authorization and Authentication in Java: Core Concepts and Tools



Authentication and authorization are two fundamental pillars of security for any web application. In the Java ecosystem, there are many mature libraries and frameworks for these tasks. In this article, we will thoroughly examine the key tools, their features, and provide practical code examples.



1. Basic Concepts

Before moving on to the tools, it is important to clearly distinguish the terms:

  • Authentication — verifying the user's identity (who are you?). Usually done via login/password, tokens, or biometrics.
  • Authorization — verifying access rights (what are you allowed to do?). Determines whether a user can perform certain actions.


2. Spring Security — The De Facto Standard

Spring Security is the most popular framework for ensuring security in Java applications. It provides a comprehensive solution for both authentication and authorization.



2.1. Basic Authentication Setup

To include Spring Security, add the dependency to pom.xml:

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


Minimal configuration with in-memory authentication:

import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.provisioning.InMemoryUserDetailsManager;import org.springframework.security.web.SecurityFilterChain;

@Configurationpublic class SecurityConfig {

@Bean public InMemoryUserDetailsManager userDetailsManager() { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); }

@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authz -> authz .requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() ) .formLogin(login -> login.defaultSuccessUrl("/home")) .httpBasic(); return http.build(); }}


3. JWT (JSON Web Tokens) for Stateless Authentication

JWT allows implementing authentication without maintaining state on the server. The token contains all necessary information about the user and is signed with a secret key.



3.1. Generating JWT Using the jjwt Library

Add the dependency:

<dependency>    <groupId>io.jsonwebtoken</groupId>    <artifactId>jjwt-api</artifactId>    <version>0.12.5</version></dependency>


Example of creating and verifying a token:

import io.jsonwebtoken.Jwts;import io.jsonwebtoken.SignatureAlgorithm;import io.jsonwebtoken.security.Keys;import javax.crypto.SecretKey;import java.util.Date;

public class JwtUtil {

private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256); private static final long EXPIRATION_TIME = 3600000; // 1 hour

public static String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTi

Recommendations