Authorization and Authentication in Java: A Complete Guide with Examples
In modern web development, application security is one of the key aspects. In the Java ecosystem, there are several proven tools for implementing authentication (verifying user identity) and authorization (checking access rights). In this article, we will thoroughly examine the libraries and approaches that will help you secure your application.
Basic Concepts
Before moving on to the tools, it is important to distinguish between two concepts:
- Authentication — the process of verifying whether a user is who they claim to be (e.g., login and password).
- Authorization — determining which resources or actions are available to an authenticated user.
Spring Security — Industry Standard
Spring Security is a powerful framework for ensuring security in Java applications, especially in conjunction with Spring Boot. It provides ready-made mechanisms for authentication via form, HTTP Basic, OAuth2, LDAP, and many others.
Key features:
- Flexible configuration of security filter chains.
- Support for sessions and JWT tokens.
- Protection against CSRF attacks, XSS, Clickjacking.
- Integration with databases for storing users.
Example of a basic Spring Security configuration using JWT:
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.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.web.SecurityFilterChain;
@Configuration@EnableWebSecuritypublic class SecurityConfig {
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeHttpRequests(authz -> authz .requestMatchers("/api/auth/**").permitAll() .anyRequest().authenticated() ) .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); return http.build(); }}JWT (JSON Web Token) — Seamless Authorization
JWT is a compact and self-contained way to transmit data in JSON format between parties. In Java, the io.jsonwebtoken:jjwt library is often used for working with JWT.
How it works:
- The user sends a login/password.
- The server verifies the data and returns a JWT token.
- The client stores the token (e.g., in localStorage) and sends it in the
Authorization: Bearer <token>header. - The server verifies the token's signature and extracts the data (roles, identifier).
Example of JWT generation in Java:
import io.jsonwebtoken.Jwts;import io.jsonwebtoken.SignatureAlgorithm;import io.jsonwebtoken.security.Keys;import java.security.Key;import java.util.Date;
public class JwtUtil { private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
public static String generateToken(String username, String role) { return Jwts.builder() .setSubject(username) .claim("role", role) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour .signWith(SECRET_KEY) .compact(); }}