authentication with spring security
This commit is contained in:
+1
-1
@@ -25,7 +25,7 @@ dependencies {
|
|||||||
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
|
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
|
||||||
implementation 'org.flywaydb:flyway-core'
|
implementation 'org.flywaydb:flyway-core'
|
||||||
implementation 'org.flywaydb:flyway-database-postgresql'
|
implementation 'org.flywaydb:flyway-database-postgresql'
|
||||||
implementation 'org.springframework.security:spring-security-crypto'
|
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||||
implementation 'org.bouncycastle:bcprov-jdk18on:1.84'
|
implementation 'org.bouncycastle:bcprov-jdk18on:1.84'
|
||||||
runtimeOnly 'org.postgresql:postgresql'
|
runtimeOnly 'org.postgresql:postgresql'
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package com.example.mtusi_messenger.config;
|
||||||
|
|
||||||
|
import com.example.mtusi_messenger.security.ApiAuthenticationFilter;
|
||||||
|
import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider;
|
||||||
|
import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint;
|
||||||
|
import com.example.mtusi_messenger.service.AuthenticationService;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.authentication.ProviderManager;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class SecurityConfig {
|
||||||
|
@Bean
|
||||||
|
AuthenticationManager authenticationManager(DatabaseAuthenticationProvider provider) {
|
||||||
|
return new ProviderManager(provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RestAuthenticationEntryPoint basicAuthenticationEntryPoint(ObjectMapper mapper) {
|
||||||
|
return new RestAuthenticationEntryPoint(
|
||||||
|
mapper,
|
||||||
|
"Basic realm=\"messenger\", charset=\"UTF-8\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
RestAuthenticationEntryPoint bearerAuthenticationEntryPoint(ObjectMapper mapper) {
|
||||||
|
return new RestAuthenticationEntryPoint(mapper, "Bearer realm=\"messenger\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
ApiAuthenticationFilter apiAuthenticationFilter(
|
||||||
|
AuthenticationManager authenticationManager,
|
||||||
|
AuthenticationService authenticationService,
|
||||||
|
@Qualifier("basicAuthenticationEntryPoint") RestAuthenticationEntryPoint basicAuthenticationEntryPoint,
|
||||||
|
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
|
||||||
|
) {
|
||||||
|
return new ApiAuthenticationFilter(
|
||||||
|
authenticationManager,
|
||||||
|
authenticationService,
|
||||||
|
basicAuthenticationEntryPoint,
|
||||||
|
bearerAuthenticationEntryPoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
FilterRegistrationBean<ApiAuthenticationFilter> disableServletFilterRegistration(
|
||||||
|
ApiAuthenticationFilter filter
|
||||||
|
) {
|
||||||
|
var registration = new FilterRegistrationBean<>(filter);
|
||||||
|
registration.setEnabled(false);
|
||||||
|
return registration;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
SecurityFilterChain securityFilterChain(
|
||||||
|
HttpSecurity http,
|
||||||
|
ApiAuthenticationFilter apiAuthenticationFilter,
|
||||||
|
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
|
||||||
|
) throws Exception {
|
||||||
|
http
|
||||||
|
.csrf(csrf -> csrf.disable())
|
||||||
|
.formLogin(form -> form.disable())
|
||||||
|
.httpBasic(basic -> basic.disable())
|
||||||
|
.logout(logout -> logout.disable())
|
||||||
|
.requestCache(cache -> cache.disable())
|
||||||
|
.sessionManagement(session -> session
|
||||||
|
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
|
.exceptionHandling(errors -> errors
|
||||||
|
.authenticationEntryPoint(bearerAuthenticationEntryPoint))
|
||||||
|
.authorizeHttpRequests(authorize -> authorize
|
||||||
|
.requestMatchers(HttpMethod.GET, "/health/**").permitAll()
|
||||||
|
.requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll()
|
||||||
|
.anyRequest().authenticated())
|
||||||
|
.addFilterBefore(apiAuthenticationFilter, AnonymousAuthenticationFilter.class);
|
||||||
|
return http.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,16 +2,16 @@ package com.example.mtusi_messenger.controller;
|
|||||||
|
|
||||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import com.example.mtusi_messenger.dto.*;
|
import com.example.mtusi_messenger.dto.*;
|
||||||
import com.example.mtusi_messenger.model.Chat;
|
import com.example.mtusi_messenger.model.Chat;
|
||||||
import com.example.mtusi_messenger.service.ChatService;
|
import com.example.mtusi_messenger.service.ChatService;
|
||||||
import com.example.mtusi_messenger.service.AuthenticationService;
|
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@@ -24,23 +24,22 @@ import static com.example.mtusi_messenger.service.UuidValidator.parse;
|
|||||||
public class ChatController {
|
public class ChatController {
|
||||||
|
|
||||||
private final ChatService chats;
|
private final ChatService chats;
|
||||||
private final AuthenticationService authentication;
|
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ResponseEntity<ChatResponse> create(HttpServletRequest req,
|
public ResponseEntity<ChatResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
|
||||||
@Valid @RequestBody CreateChatRequest body
|
@Valid @RequestBody CreateChatRequest body
|
||||||
) {
|
) {
|
||||||
UUID userId = authentication.requireBearer(req).id();
|
UUID userId = principal.user().id();
|
||||||
Chat c = chats.create(body, userId);
|
Chat c = chats.create(body, userId);
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c));
|
return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public ChatPageResponse list(HttpServletRequest req,
|
public ChatPageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
|
||||||
@RequestParam(required = false) String limit,
|
@RequestParam(required = false) String limit,
|
||||||
@RequestParam(required = false) String cursor
|
@RequestParam(required = false) String cursor
|
||||||
) {
|
) {
|
||||||
UUID userId = authentication.requireBearer(req).id();
|
UUID userId = principal.user().id();
|
||||||
int parsedLimit = validateLimit(limit);
|
int parsedLimit = validateLimit(limit);
|
||||||
validateCursorPresence(cursor);
|
validateCursorPresence(cursor);
|
||||||
List<Chat> page = chats.page(userId, parsedLimit, cursor);
|
List<Chat> page = chats.page(userId, parsedLimit, cursor);
|
||||||
@@ -51,10 +50,10 @@ public class ChatController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{chatId}")
|
@GetMapping("/{chatId}")
|
||||||
public ChatResponse get(HttpServletRequest req,
|
public ChatResponse get(@AuthenticationPrincipal SessionPrincipal principal,
|
||||||
@PathVariable String chatId
|
@PathVariable String chatId
|
||||||
) {
|
) {
|
||||||
UUID userId = authentication.requireBearer(req).id();
|
UUID userId = principal.user().id();
|
||||||
return ChatResponse.from(chats.getAccessible(parse(chatId), userId));
|
return ChatResponse.from(chats.getAccessible(parse(chatId), userId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,16 +2,16 @@ package com.example.mtusi_messenger.controller;
|
|||||||
|
|
||||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
import com.example.mtusi_messenger.exception.ApiExceptions;
|
||||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import com.example.mtusi_messenger.dto.*;
|
import com.example.mtusi_messenger.dto.*;
|
||||||
import com.example.mtusi_messenger.model.Message;
|
import com.example.mtusi_messenger.model.Message;
|
||||||
import com.example.mtusi_messenger.service.MessageService;
|
import com.example.mtusi_messenger.service.MessageService;
|
||||||
import com.example.mtusi_messenger.service.AuthenticationService;
|
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@@ -23,26 +23,25 @@ import static com.example.mtusi_messenger.service.UuidValidator.parse;
|
|||||||
@SecurityRequirement(name = "bearerAuth")
|
@SecurityRequirement(name = "bearerAuth")
|
||||||
public class MessageController {
|
public class MessageController {
|
||||||
private final MessageService messages;
|
private final MessageService messages;
|
||||||
private final AuthenticationService authentication;
|
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ResponseEntity<MessageResponse> create(HttpServletRequest req,
|
public ResponseEntity<MessageResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
|
||||||
@PathVariable String chatId,
|
@PathVariable String chatId,
|
||||||
@Valid @RequestBody CreateMessageRequest body
|
@Valid @RequestBody CreateMessageRequest body
|
||||||
) {
|
) {
|
||||||
UUID userId = authentication.requireBearer(req).id();
|
UUID userId = principal.user().id();
|
||||||
UUID parsedChatId = parse(chatId);
|
UUID parsedChatId = parse(chatId);
|
||||||
Message m = messages.create(parsedChatId, userId, body);
|
Message m = messages.create(parsedChatId, userId, body);
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse.from(m));
|
return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse.from(m));
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public MessagePageResponse list(HttpServletRequest req,
|
public MessagePageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
|
||||||
@PathVariable String chatId,
|
@PathVariable String chatId,
|
||||||
@RequestParam(required = false) String limit,
|
@RequestParam(required = false) String limit,
|
||||||
@RequestParam(required=false) String cursor
|
@RequestParam(required=false) String cursor
|
||||||
) {
|
) {
|
||||||
UUID userId = authentication.requireBearer(req).id();
|
UUID userId = principal.user().id();
|
||||||
UUID parsedChatId = parse(chatId);
|
UUID parsedChatId = parse(chatId);
|
||||||
int parsedLimit = validateLimit(limit);
|
int parsedLimit = validateLimit(limit);
|
||||||
if (cursor != null && cursor.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
|
if (cursor != null && cursor.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
|
||||||
|
|||||||
@@ -3,11 +3,13 @@ package com.example.mtusi_messenger.controller;
|
|||||||
import com.example.mtusi_messenger.dto.SessionResponse;
|
import com.example.mtusi_messenger.dto.SessionResponse;
|
||||||
import com.example.mtusi_messenger.dto.UserResponse;
|
import com.example.mtusi_messenger.dto.UserResponse;
|
||||||
import com.example.mtusi_messenger.service.AuthenticationService;
|
import com.example.mtusi_messenger.service.AuthenticationService;
|
||||||
|
import com.example.mtusi_messenger.model.User;
|
||||||
|
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
@@ -21,8 +23,8 @@ public class SessionController {
|
|||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
@SecurityRequirement(name = "basicAuth")
|
@SecurityRequirement(name = "basicAuth")
|
||||||
public ResponseEntity<SessionResponse> create(HttpServletRequest request) {
|
public ResponseEntity<SessionResponse> create(@AuthenticationPrincipal User user) {
|
||||||
var issued = authentication.login(request);
|
var issued = authentication.issueSession(user);
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(new SessionResponse(
|
return ResponseEntity.status(HttpStatus.CREATED).body(new SessionResponse(
|
||||||
issued.token(),
|
issued.token(),
|
||||||
"Bearer",
|
"Bearer",
|
||||||
@@ -32,8 +34,8 @@ public class SessionController {
|
|||||||
|
|
||||||
@DeleteMapping("/current")
|
@DeleteMapping("/current")
|
||||||
@SecurityRequirement(name = "bearerAuth")
|
@SecurityRequirement(name = "bearerAuth")
|
||||||
public ResponseEntity<Void> revoke(HttpServletRequest request) {
|
public ResponseEntity<Void> revoke(@AuthenticationPrincipal SessionPrincipal principal) {
|
||||||
authentication.logout(request);
|
authentication.revoke(principal);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
package com.example.mtusi_messenger.controller;
|
package com.example.mtusi_messenger.controller;
|
||||||
|
|
||||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import com.example.mtusi_messenger.dto.*;
|
import com.example.mtusi_messenger.dto.*;
|
||||||
import com.example.mtusi_messenger.service.AuthenticationService;
|
|
||||||
import com.example.mtusi_messenger.service.UserService;
|
import com.example.mtusi_messenger.service.UserService;
|
||||||
|
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/v1/users")
|
@RequestMapping("/api/v1/users")
|
||||||
@@ -17,7 +17,6 @@ import com.example.mtusi_messenger.service.UserService;
|
|||||||
public class UserController {
|
public class UserController {
|
||||||
|
|
||||||
private final UserService users;
|
private final UserService users;
|
||||||
private final AuthenticationService authentication;
|
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
|
public ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
|
||||||
@@ -27,7 +26,7 @@ public class UserController {
|
|||||||
|
|
||||||
@GetMapping("/me")
|
@GetMapping("/me")
|
||||||
@SecurityRequirement(name = "bearerAuth")
|
@SecurityRequirement(name = "bearerAuth")
|
||||||
public UserResponse me(HttpServletRequest request) {
|
public UserResponse me(@AuthenticationPrincipal SessionPrincipal principal) {
|
||||||
return UserResponse.from(authentication.requireBearer(request));
|
return UserResponse.from(principal.user());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package com.example.mtusi_messenger.security;
|
||||||
|
|
||||||
|
import com.example.mtusi_messenger.service.AuthenticationService;
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.Enumeration;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class ApiAuthenticationFilter extends OncePerRequestFilter {
|
||||||
|
private static final String AUTHORIZATION = "Authorization";
|
||||||
|
private static final String SESSION_PATH = "/api/v1/auth/sessions";
|
||||||
|
|
||||||
|
private final AuthenticationManager authenticationManager;
|
||||||
|
private final AuthenticationService sessions;
|
||||||
|
private final RestAuthenticationEntryPoint basicEntryPoint;
|
||||||
|
private final RestAuthenticationEntryPoint bearerEntryPoint;
|
||||||
|
|
||||||
|
public ApiAuthenticationFilter(
|
||||||
|
AuthenticationManager authenticationManager,
|
||||||
|
AuthenticationService sessions,
|
||||||
|
RestAuthenticationEntryPoint basicEntryPoint,
|
||||||
|
RestAuthenticationEntryPoint bearerEntryPoint
|
||||||
|
) {
|
||||||
|
this.authenticationManager = authenticationManager;
|
||||||
|
this.sessions = sessions;
|
||||||
|
this.basicEntryPoint = basicEntryPoint;
|
||||||
|
this.bearerEntryPoint = bearerEntryPoint;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(
|
||||||
|
HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
FilterChain filterChain
|
||||||
|
) throws ServletException, IOException {
|
||||||
|
boolean basicLogin = HttpMethod.POST.matches(request.getMethod())
|
||||||
|
&& SESSION_PATH.equals(request.getRequestURI());
|
||||||
|
if (isPublicRequest(request) && !basicLogin) {
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Authentication authentication = basicLogin
|
||||||
|
? authenticateBasic(request)
|
||||||
|
: authenticateBearer(request);
|
||||||
|
var context = SecurityContextHolder.createEmptyContext();
|
||||||
|
context.setAuthentication(authentication);
|
||||||
|
SecurityContextHolder.setContext(context);
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
} catch (AuthenticationException e) {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
(basicLogin ? basicEntryPoint : bearerEntryPoint)
|
||||||
|
.commence(request, response, e);
|
||||||
|
} finally {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Authentication authenticateBasic(HttpServletRequest request) {
|
||||||
|
String header = singleAuthorizationHeader(request);
|
||||||
|
if (!header.startsWith("Basic ") || header.length() == 6) {
|
||||||
|
throw new BadCredentialsException("Invalid Basic credentials");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
byte[] decoded = Base64.getDecoder().decode(header.substring(6));
|
||||||
|
String credentials = new String(decoded, StandardCharsets.UTF_8);
|
||||||
|
int separator = credentials.indexOf(':');
|
||||||
|
if (separator <= 0) {
|
||||||
|
throw new BadCredentialsException("Invalid Basic credentials");
|
||||||
|
}
|
||||||
|
return authenticationManager.authenticate(
|
||||||
|
UsernamePasswordAuthenticationToken.unauthenticated(
|
||||||
|
credentials.substring(0, separator),
|
||||||
|
credentials.substring(separator + 1)));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new BadCredentialsException("Invalid Basic credentials", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Authentication authenticateBearer(HttpServletRequest request) {
|
||||||
|
String header = singleAuthorizationHeader(request);
|
||||||
|
if (!header.startsWith("Bearer ") || header.length() == 7) {
|
||||||
|
throw new BadCredentialsException("Invalid Bearer token");
|
||||||
|
}
|
||||||
|
String token = header.substring(7);
|
||||||
|
if (!token.matches("[A-Za-z0-9_-]{43}")) {
|
||||||
|
throw new BadCredentialsException("Invalid Bearer token");
|
||||||
|
}
|
||||||
|
SessionPrincipal principal = sessions.authenticateBearer(token);
|
||||||
|
return UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private String singleAuthorizationHeader(HttpServletRequest request) {
|
||||||
|
Enumeration<String> values = request.getHeaders(AUTHORIZATION);
|
||||||
|
if (values == null || !values.hasMoreElements()) {
|
||||||
|
throw new BadCredentialsException("Authentication required");
|
||||||
|
}
|
||||||
|
String value = values.nextElement();
|
||||||
|
if (values.hasMoreElements()) {
|
||||||
|
throw new BadCredentialsException("Multiple Authorization headers");
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isPublicRequest(HttpServletRequest request) {
|
||||||
|
String path = request.getRequestURI();
|
||||||
|
return path.startsWith("/health/")
|
||||||
|
|| (HttpMethod.POST.matches(request.getMethod())
|
||||||
|
&& "/api/v1/users".equals(path));
|
||||||
|
}
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
package com.example.mtusi_messenger.security;
|
||||||
|
|
||||||
|
import com.example.mtusi_messenger.repository.UserRepository;
|
||||||
|
import org.springframework.security.authentication.AuthenticationProvider;
|
||||||
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class DatabaseAuthenticationProvider implements AuthenticationProvider {
|
||||||
|
private final UserRepository users;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final String dummyPasswordHash;
|
||||||
|
|
||||||
|
public DatabaseAuthenticationProvider(UserRepository users, PasswordEncoder passwordEncoder) {
|
||||||
|
this.users = users;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
|
||||||
|
String username = authentication.getName();
|
||||||
|
String password = String.valueOf(authentication.getCredentials());
|
||||||
|
var stored = users.findCredentialsByUsername(username);
|
||||||
|
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
|
||||||
|
.filter(hash -> hash.startsWith("$argon2"))
|
||||||
|
.orElse(dummyPasswordHash);
|
||||||
|
|
||||||
|
boolean matches;
|
||||||
|
try {
|
||||||
|
matches = passwordEncoder.matches(password, passwordHash);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
matches = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stored.isEmpty() || !matches) {
|
||||||
|
throw new BadCredentialsException("Invalid credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
return UsernamePasswordAuthenticationToken.authenticated(
|
||||||
|
stored.get().user(),
|
||||||
|
null,
|
||||||
|
List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supports(Class<?> authentication) {
|
||||||
|
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package com.example.mtusi_messenger.security;
|
||||||
|
|
||||||
|
import com.example.mtusi_messenger.dto.ErrorResponse;
|
||||||
|
import com.example.mtusi_messenger.web.RequestIdFilter;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.core.AuthenticationException;
|
||||||
|
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||||
|
private final ObjectMapper mapper;
|
||||||
|
private final String challenge;
|
||||||
|
|
||||||
|
public RestAuthenticationEntryPoint(ObjectMapper mapper, String challenge) {
|
||||||
|
this.mapper = mapper;
|
||||||
|
this.challenge = challenge;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void commence(
|
||||||
|
HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
AuthenticationException exception
|
||||||
|
) throws IOException {
|
||||||
|
String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE);
|
||||||
|
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
|
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
|
response.setCharacterEncoding("UTF-8");
|
||||||
|
response.setHeader("WWW-Authenticate", challenge);
|
||||||
|
mapper.writeValue(response.getOutputStream(), new ErrorResponse(
|
||||||
|
new ErrorResponse.ErrorBody("unauthorized", "Authentication required", requestId)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.example.mtusi_messenger.security;
|
||||||
|
|
||||||
|
import com.example.mtusi_messenger.model.User;
|
||||||
|
|
||||||
|
public record SessionPrincipal(User user, byte[] tokenHash) {
|
||||||
|
public SessionPrincipal {
|
||||||
|
tokenHash = tokenHash.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] tokenHash() {
|
||||||
|
return tokenHash.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,12 @@
|
|||||||
package com.example.mtusi_messenger.service;
|
package com.example.mtusi_messenger.service;
|
||||||
|
|
||||||
import com.example.mtusi_messenger.exception.ApiExceptions;
|
|
||||||
import com.example.mtusi_messenger.model.Session;
|
import com.example.mtusi_messenger.model.Session;
|
||||||
import com.example.mtusi_messenger.model.User;
|
import com.example.mtusi_messenger.model.User;
|
||||||
import com.example.mtusi_messenger.repository.SessionRepository;
|
import com.example.mtusi_messenger.repository.SessionRepository;
|
||||||
import com.example.mtusi_messenger.repository.UserRepository;
|
import com.example.mtusi_messenger.repository.UserRepository;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import com.example.mtusi_messenger.security.SessionPrincipal;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
@@ -16,24 +15,19 @@ import java.security.NoSuchAlgorithmException;
|
|||||||
import java.security.SecureRandom;
|
import java.security.SecureRandom;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
import java.util.Enumeration;
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class AuthenticationService {
|
public class AuthenticationService {
|
||||||
private static final String AUTHORIZATION = "Authorization";
|
|
||||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||||
|
|
||||||
private final UserRepository users;
|
private final UserRepository users;
|
||||||
private final SessionRepository sessions;
|
private final SessionRepository sessions;
|
||||||
private final PasswordEncoder passwordEncoder;
|
|
||||||
private final long ttlSeconds;
|
private final long ttlSeconds;
|
||||||
private final String dummyPasswordHash;
|
|
||||||
|
|
||||||
public AuthenticationService(
|
public AuthenticationService(
|
||||||
UserRepository users,
|
UserRepository users,
|
||||||
SessionRepository sessions,
|
SessionRepository sessions,
|
||||||
PasswordEncoder passwordEncoder,
|
|
||||||
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
|
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
|
||||||
) {
|
) {
|
||||||
if (ttlSeconds <= 0) {
|
if (ttlSeconds <= 0) {
|
||||||
@@ -41,30 +35,10 @@ public class AuthenticationService {
|
|||||||
}
|
}
|
||||||
this.users = users;
|
this.users = users;
|
||||||
this.sessions = sessions;
|
this.sessions = sessions;
|
||||||
this.passwordEncoder = passwordEncoder;
|
|
||||||
this.ttlSeconds = ttlSeconds;
|
this.ttlSeconds = ttlSeconds;
|
||||||
this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public IssuedSession login(HttpServletRequest request) {
|
public IssuedSession issueSession(User user) {
|
||||||
BasicCredentials credentials = parseBasic(singleAuthorizationHeader(request, true));
|
|
||||||
var stored = users.findCredentialsByUsername(credentials.username());
|
|
||||||
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
|
|
||||||
.filter(hash -> hash.startsWith("$argon2"))
|
|
||||||
.orElse(dummyPasswordHash);
|
|
||||||
|
|
||||||
boolean passwordMatches;
|
|
||||||
try {
|
|
||||||
passwordMatches = passwordEncoder.matches(credentials.password(), passwordHash);
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
passwordMatches = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (stored.isEmpty() || !passwordMatches) {
|
|
||||||
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
|
|
||||||
}
|
|
||||||
|
|
||||||
User user = stored.get().user();
|
|
||||||
String token = newToken();
|
String token = newToken();
|
||||||
Instant createdAt = Instant.now();
|
Instant createdAt = Instant.now();
|
||||||
Instant expiresAt = createdAt.plusSeconds(ttlSeconds);
|
Instant expiresAt = createdAt.plusSeconds(ttlSeconds);
|
||||||
@@ -74,69 +48,24 @@ public class AuthenticationService {
|
|||||||
hashToken(token),
|
hashToken(token),
|
||||||
createdAt,
|
createdAt,
|
||||||
expiresAt));
|
expiresAt));
|
||||||
|
|
||||||
return new IssuedSession(token, expiresAt, user);
|
return new IssuedSession(token, expiresAt, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
public User requireBearer(HttpServletRequest request) {
|
public SessionPrincipal authenticateBearer(String token) {
|
||||||
String token = parseBearer(singleAuthorizationHeader(request, false));
|
byte[] tokenHash = hashToken(token);
|
||||||
UUID userId = sessions.findActiveUserId(hashToken(token))
|
UUID userId = sessions.findActiveUserId(tokenHash)
|
||||||
.orElseThrow(() -> ApiExceptions.unauthorizedBearer("Invalid or expired session"));
|
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||||
return users.findById(userId)
|
User user = users.findById(userId)
|
||||||
.orElseThrow(() -> ApiExceptions.unauthorizedBearer("Invalid or expired session"));
|
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
|
||||||
|
return new SessionPrincipal(user, tokenHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void logout(HttpServletRequest request) {
|
public void revoke(SessionPrincipal principal) {
|
||||||
String token = parseBearer(singleAuthorizationHeader(request, false));
|
if (!sessions.revoke(principal.tokenHash())) {
|
||||||
if (!sessions.revoke(hashToken(token))) {
|
throw new BadCredentialsException("Invalid or expired session");
|
||||||
throw ApiExceptions.unauthorizedBearer("Invalid or expired session");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private String singleAuthorizationHeader(HttpServletRequest request, boolean basic) {
|
|
||||||
Enumeration<String> values = request.getHeaders(AUTHORIZATION);
|
|
||||||
if (values == null || !values.hasMoreElements()) {
|
|
||||||
throw basic
|
|
||||||
? ApiExceptions.unauthorizedBasic("Authentication required")
|
|
||||||
: ApiExceptions.unauthorizedBearer("Authentication required");
|
|
||||||
}
|
|
||||||
String value = values.nextElement();
|
|
||||||
if (values.hasMoreElements()) {
|
|
||||||
throw basic
|
|
||||||
? ApiExceptions.unauthorizedBasic("Invalid Authorization header")
|
|
||||||
: ApiExceptions.unauthorizedBearer("Invalid Authorization header");
|
|
||||||
}
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private BasicCredentials parseBasic(String header) {
|
|
||||||
if (!header.startsWith("Basic ") || header.length() == 6) {
|
|
||||||
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
byte[] decoded = Base64.getDecoder().decode(header.substring(6));
|
|
||||||
String value = new String(decoded, StandardCharsets.UTF_8);
|
|
||||||
int separator = value.indexOf(':');
|
|
||||||
if (separator <= 0) {
|
|
||||||
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
|
|
||||||
}
|
|
||||||
return new BasicCredentials(value.substring(0, separator), value.substring(separator + 1));
|
|
||||||
} catch (IllegalArgumentException e) {
|
|
||||||
throw ApiExceptions.unauthorizedBasic("Invalid credentials");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String parseBearer(String header) {
|
|
||||||
if (!header.startsWith("Bearer ") || header.length() == 7) {
|
|
||||||
throw ApiExceptions.unauthorizedBearer("Invalid bearer token");
|
|
||||||
}
|
|
||||||
String token = header.substring(7);
|
|
||||||
if (!token.matches("[A-Za-z0-9_-]{43}")) {
|
|
||||||
throw ApiExceptions.unauthorizedBearer("Invalid bearer token");
|
|
||||||
}
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String newToken() {
|
private String newToken() {
|
||||||
byte[] bytes = new byte[32];
|
byte[] bytes = new byte[32];
|
||||||
SECURE_RANDOM.nextBytes(bytes);
|
SECURE_RANDOM.nextBytes(bytes);
|
||||||
@@ -153,5 +82,4 @@ public class AuthenticationService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public record IssuedSession(String token, Instant expiresAt, User user) {}
|
public record IssuedSession(String token, Instant expiresAt, User user) {}
|
||||||
private record BasicCredentials(String username, String password) {}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,11 +6,14 @@ import jakarta.servlet.http.HttpServletRequest;
|
|||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import org.slf4j.MDC;
|
import org.slf4j.MDC;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.core.Ordered;
|
||||||
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.web.filter.OncePerRequestFilter;
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
|
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||||
public class RequestIdFilter extends OncePerRequestFilter {
|
public class RequestIdFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
public static final String HEADER = "X-Request-Id";
|
public static final String HEADER = "X-Request-Id";
|
||||||
|
|||||||
@@ -1,12 +1,6 @@
|
|||||||
ALTER TABLE users
|
ALTER TABLE users
|
||||||
ADD COLUMN password_hash text;
|
ADD COLUMN password_hash text;
|
||||||
|
|
||||||
-- V1 briefly existed without credentials. Such legacy rows cannot be given a
|
|
||||||
-- real password, so they receive a deliberately invalid value and cannot log in.
|
|
||||||
UPDATE users
|
|
||||||
SET password_hash = 'legacy-account-disabled'
|
|
||||||
WHERE password_hash IS NULL;
|
|
||||||
|
|
||||||
ALTER TABLE users
|
ALTER TABLE users
|
||||||
ALTER COLUMN password_hash SET NOT NULL;
|
ALTER COLUMN password_hash SET NOT NULL;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user