-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Spring security 6 and Third party APIs added
- Loading branch information
1 parent
a28125a
commit c2ad731
Showing
26 changed files
with
939 additions
and
51 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
70 changes: 70 additions & 0 deletions
70
src/main/java/zuhriddinscode/config/JwtAuthenticationFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package zuhriddinscode.config; | ||
|
||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import lombok.RequiredArgsConstructor; | ||
import org.apache.commons.lang3.StringUtils; | ||
import org.springframework.lang.NonNull; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.context.SecurityContext; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
import zuhriddinscode.service.JwtService; | ||
import zuhriddinscode.service.UserService; | ||
|
||
import java.io.IOException; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class JwtAuthenticationFilter extends OncePerRequestFilter { | ||
public static final String BEARER_PREFIX = "Bearer "; | ||
public static final String HEADER_NAME = "Authorization"; | ||
private final JwtService jwtService; | ||
private final UserService userService; | ||
|
||
@Override | ||
protected void doFilterInternal( | ||
@NonNull HttpServletRequest request, | ||
@NonNull HttpServletResponse response, | ||
@NonNull FilterChain filterChain | ||
) throws ServletException, IOException { | ||
|
||
// Получаем токен из заголовка | ||
var authHeader = request.getHeader(HEADER_NAME); | ||
if (StringUtils.isEmpty(authHeader) || !StringUtils.startsWith(authHeader, BEARER_PREFIX)) { | ||
filterChain.doFilter(request, response); | ||
return; | ||
} | ||
|
||
// Обрезаем префикс и получаем имя пользователя из токена | ||
var jwt = authHeader.substring(BEARER_PREFIX.length()); | ||
var username = jwtService.extractUserName(jwt); | ||
|
||
if (StringUtils.isNotEmpty(username) && SecurityContextHolder.getContext().getAuthentication() == null) { | ||
UserDetails userDetails = userService | ||
.userDetailsService() | ||
.loadUserByUsername(username); | ||
|
||
// Если токен валиден, то аутентифицируем пользователя | ||
if (jwtService.isTokenValid(jwt, userDetails)) { | ||
SecurityContext context = SecurityContextHolder.createEmptyContext(); | ||
|
||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( | ||
userDetails, | ||
null, | ||
userDetails.getAuthorities() | ||
); | ||
|
||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); | ||
context.setAuthentication(authToken); | ||
SecurityContextHolder.setContext(context); | ||
} | ||
} | ||
filterChain.doFilter(request, response); | ||
} | ||
} |
77 changes: 77 additions & 0 deletions
77
src/main/java/zuhriddinscode/config/SecurityConfiguration.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
package zuhriddinscode.config; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.authentication.AuthenticationProvider; | ||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider; | ||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; | ||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; | ||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
import org.springframework.web.cors.CorsConfiguration; | ||
import zuhriddinscode.service.UserService; | ||
|
||
import java.util.List; | ||
|
||
import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; | ||
|
||
@Configuration | ||
@EnableWebSecurity | ||
@EnableMethodSecurity | ||
@RequiredArgsConstructor | ||
public class SecurityConfiguration { | ||
|
||
private final JwtAuthenticationFilter jwtAuthenticationFilter; | ||
private final UserService userService; | ||
|
||
@Bean | ||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
http.csrf(AbstractHttpConfigurer::disable) | ||
// Своего рода отключение CORS (разрешение запросов со всех доменов) | ||
.cors(cors -> cors.configurationSource(request -> { | ||
var corsConfiguration = new CorsConfiguration(); | ||
corsConfiguration.setAllowedOriginPatterns(List.of("*")); | ||
corsConfiguration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); | ||
corsConfiguration.setAllowedHeaders(List.of("*")); | ||
corsConfiguration.setAllowCredentials(true); | ||
return corsConfiguration; | ||
})) | ||
// Настройка доступа к конечным точкам | ||
.authorizeHttpRequests(request -> request | ||
// Можно указать конкретный путь, * - 1 уровень вложенности, ** - любое количество уровней вложенности | ||
.requestMatchers("/auth/**").permitAll() | ||
.requestMatchers("/swagger-ui/**", "/swagger-resources/*", "/v3/api-docs/**").permitAll() | ||
.requestMatchers("/endpoint", "/admin/**").hasRole("ADMIN") | ||
.anyRequest().authenticated()) | ||
.sessionManagement(manager -> manager.sessionCreationPolicy(STATELESS)) | ||
.authenticationProvider(authenticationProvider()) | ||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); | ||
return http.build(); | ||
} | ||
|
||
@Bean | ||
public PasswordEncoder passwordEncoder() { | ||
return new BCryptPasswordEncoder(); | ||
} | ||
|
||
@Bean | ||
public AuthenticationProvider authenticationProvider() { | ||
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); | ||
authProvider.setUserDetailsService(userService.userDetailsService()); | ||
authProvider.setPasswordEncoder(passwordEncoder()); | ||
return authProvider; | ||
} | ||
|
||
@Bean | ||
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) | ||
throws Exception { | ||
return config.getAuthenticationManager(); | ||
} | ||
} |
35 changes: 35 additions & 0 deletions
35
src/main/java/zuhriddinscode/controller/AuthController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package zuhriddinscode.controller; | ||
|
||
import io.swagger.v3.oas.annotations.Operation; | ||
import io.swagger.v3.oas.annotations.tags.Tag; | ||
import jakarta.validation.Valid; | ||
import lombok.RequiredArgsConstructor; | ||
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 zuhriddinscode.domain.dto.JwtAuthenticationResponse; | ||
import zuhriddinscode.domain.dto.SignInRequest; | ||
import zuhriddinscode.domain.dto.SignUpRequest; | ||
import zuhriddinscode.service.AuthenticationService; | ||
|
||
@RestController | ||
@RequestMapping("/auth") | ||
@RequiredArgsConstructor | ||
@Tag(name = "Аутентификация") | ||
public class AuthController { | ||
|
||
private final AuthenticationService authenticationService; | ||
|
||
@Operation(summary = "Регистрация пользователя") | ||
@PostMapping("/sign-up") | ||
public JwtAuthenticationResponse signUp(@RequestBody @Valid SignUpRequest request) { | ||
return authenticationService.signUp(request); | ||
} | ||
|
||
@Operation(summary = "Авторизация пользователя") | ||
@PostMapping("/sign-in") | ||
public JwtAuthenticationResponse signIn(@RequestBody @Valid SignInRequest request) { | ||
return authenticationService.signIn(request); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.