Submitted:
10 January 2025
Posted:
13 January 2025
You are already at the latest version
Abstract
Keywords:
1. Introduction
2. Basic Authentication Method
How Does Basic Authentication work?
| Authorization: Basic <base64(username:password)> |
Example of the Process:

3. JWT-Based Authentication
| package com.example.Entries_Project.config; |
| @Component |
| @AllArgsConstructor |
| @Slf4j |
| public class JwtFilter extends OncePerRequestFilter { |
| private final JwtService jwtService; |
| private final UserDetailsService userDetailsService; |
| @Override |
| protected void doFilterInternal( |
| @Nonnull HttpServletRequest request, |
| @Nonnull HttpServletResponse response, |
| @Nonnull FilterChain filterChain |
| ) throws ServletException, IOException { |
| String header = request.getHeader("Authorization"); |
| if (header != null && header.startsWith("Bearer ")) { |
| try { |
| String jwt = header.substring(7); |
| String email = jwtService.getUserEmailFromToken(jwt); |
| if (email != null && SecurityContextHolder.getContext().getAuthentication() == null) { |
| var user = userDetailsService.loadUserByUsername(email); |
| SecurityContextHolder.getContext().setAuthentication( |
| new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()) |
| ); |
| } |
| } catch (ExpiredJwtException e) { |
| response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); |
| log.info("JWT expired: {}", e.getMessage()); |
| } catch (Exception e) { |
| log.info("Invalid JWT: {}", e.getMessage()); |
| } |
| } |
| filterChain.doFilter(request, response); |
| } |
| } |
| package com.example.Entries_Project.config; |
| @Service |
| public class JwtService { |
| private final UserRepository userRepository; |
| @Value("${jwt.secret-key}") |
| private String secretKey; |
| @Value("${jwt.expiration}") |
| private long expiration; |
| public JwtService(UserRepository userRepository) { |
| this.userRepository = userRepository; |
| } |
| public String generateToken(UserDetails userDetails) { |
| Map<String, Object> claims = new HashMap<>(); |
| String role = userDetails.getAuthorities().toString(); |
| claims.put("role", role); |
| Date issuedDate = new Date(); |
| Date expireDate = new Date(issuedDate.getTime() + expiration); |
| return Jwts.builder() |
| .setClaims(claims) |
| .setSubject(userDetails.getUsername()) |
| .setIssuedAt(issuedDate) |
| .setExpiration(expireDate) |
| .signWith(getSignInKey(), SignatureAlgorithm.HS256) |
| .compact(); |
| } |
| public Claims getClaimsFromToken(String token) { |
| return Jwts.parserBuilder() |
| .setSigningKey(getSignInKey()) |
| .build() |
| .parseClaimsJws(token) |
| .getBody(); |
| } |
| public String getUserEmailFromToken(String token) { |
| return getClaimsFromToken(token).getSubject(); |
| } |
| public User getUserFromToken(String token) { |
| token = token.substring(7); |
| String email = getUserEmailFromToken(token); |
| return userRepository.findByEmail(email).orElseThrow(() -> new CustomException("User not found", HttpStatus.NOT_FOUND)); |
| } |
| private Key getSignInKey() { |
| byte[] keyBytes = Decoders.BASE64.decode(secretKey); |
| return Keys.hmacShaKeyFor(keyBytes); |
| } |
| } |
4. OAuth2 Authentication
The Main Roles in OAuth 2:
Configuring Spring for OAuth 2.0
- Create a Spring Boot project
- Add spring-boot-starter-oauth2-client and spring-boot-starter-security dependencies
- In the security configuration class, configure OAuth2LoginConfigurer
| @EnableWebSecurity |
| public class SecurityConfig extends WebSecurityConfigurerAdapter { |
| @Override |
| protected void configure(HttpSecurity http) throws Exception { |
| http |
| .authorizeRequests() |
| .anyRequest().authenticated() |
| .and() |
| .oauth2Login(); |
| } |
| @Bean |
| public ClientRegistrationRepository clientRegistrationRepository() { |
| return new InMemoryClientRegistrationRepository(this.googleClientRegistration()); |
| } |
| private ClientRegistration googleClientRegistration() { |
| return ClientRegistration |
| .withRegistrationId("google") |
| .clientId("123456") |
| .clientSecret("secret") |
| .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC) |
| .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) |
| .redirectUriTemplate("{baseUrl}/login/oauth2/code/{registrationId}") |
| .scope("openid", "profile", "email", "address", "phone") |
| .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") |
| .tokenUri("https://www.googleapis.com/oauth2/v4/token") |
| .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") |
| .userNameAttributeName(IdTokenClaimNames.SUB) |
| .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") |
| .clientName("Google") |
| .build(); |
| } |
| } |
Summary
References
- Аутентификация (OAuth 2.0) в Spring Security https://teletype.in/@datanoob/autentifikaciya-oauth-2-0-v-spring-security.
- Реализация JWT в Spring Boot https://struchkov.dev/blog/ru/jwt-implementation-in-spring/.
- JWT-аутентификация при пoмoщи Spring Boot 3 и Spring Security 6 https://habr.com/ru/articles/784508/.
- Authentication in Spring Security https://www.geeksforgeeks.org/authentication-in-spring-security/.
- Basic-аутентификация в Spring Security https://alexkosarev.name/2023/05/31/basic-authentication-in-spring-security/.
- Как рабoтает аутентификация и автoризация в Spring Security с испoльзoванием JWT тoкена? https://dzen.ru/a/ZZbjesiprDdVRrsz.
- API Authentication and Authorization: Basic Authentication, JWT, OAuth2.0, and OpenID Connect https://medium.com/@raykipkorir/api-authentication-and-authorization-basic-authentication-jwt-oauth2-0-and-openid-connect-20aaeb5bf28b.
- Эсеналиева Г.А. Максимизация безoпаснoсти сoвременных инфoрмациoнных систем // ВЕСТНИК КЫРГЫЗСКОГО ГОСУДАРСТВЕННОГО УНИВЕРСИТЕТА СТРОИТЕЛЬСТВА, ТРАНСПОРТА И АРХИТЕКТУРЫ ИМ. Н.ИСАНОВА. - 2014. - № 2 -P. 74-76.
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content. |
© 2025 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license (http://creativecommons.org/licenses/by/4.0/).