Advertisement
Tvor0zhok

Untitled

Nov 21st, 2023
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.15 KB | None | 0 0
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  4. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  5. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  6.  
  7. @Configuration
  8. @EnableWebSecurity
  9. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  10.  
  11. @Override
  12. protected void configure(HttpSecurity http) throws Exception {
  13. http.csrf().disable()
  14. .authorizeRequests()
  15. .antMatchers("/auth").permitAll() // Разрешить доступ к /auth всем
  16. .anyRequest().authenticated()
  17. .and()
  18. .addFilter(new JwtAuthenticationFilter(authenticationManager()))
  19. .addFilter(new JwtAuthorizationFilter(authenticationManager()))
  20. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  21. }
  22.  
  23. // Дополнительные настройки, если необходимо
  24. }
  25.  
  26. import io.jsonwebtoken.Jwts;
  27. import io.jsonwebtoken.SignatureAlgorithm;
  28. import org.springframework.beans.factory.annotation.Value;
  29. import org.springframework.stereotype.Component;
  30.  
  31. import java.util.Date;
  32.  
  33. @Component
  34. public class JwtTokenProvider {
  35.  
  36. @Value("${jwt.secret}")
  37. private String secretKey;
  38.  
  39. @Value("${jwt.expiration}")
  40. private long validityInMilliseconds;
  41.  
  42. public String createToken(String username) {
  43. Date now = new Date();
  44. Date validity = new Date(now.getTime() + validityInMilliseconds);
  45.  
  46. return Jwts.builder()
  47. .setSubject(username)
  48. .setIssuedAt(now)
  49. .setExpiration(validity)
  50. .signWith(SignatureAlgorithm.HS256, secretKey)
  51. .compact();
  52. }
  53.  
  54. // Дополнительные методы для проверки токена и обновления
  55. }
  56.  
  57. import org.springframework.web.bind.annotation.PostMapping;
  58. import org.springframework.web.bind.annotation.RestController;
  59.  
  60. import javax.servlet.http.Cookie;
  61. import javax.servlet.http.HttpServletResponse;
  62.  
  63. @RestController
  64. public class AuthController {
  65.  
  66. private final JwtTokenProvider jwtTokenProvider;
  67.  
  68. // Инъекция зависимости через конструктор
  69.  
  70. @PostMapping("/auth")
  71. public void authenticate(HttpServletResponse response) {
  72. // Логика аутентификации
  73. String username = "exampleUser"; // Получите имя пользователя из запроса
  74.  
  75. // Генерация токенов
  76. String accessToken = jwtTokenProvider.createToken(username);
  77. String refreshToken = jwtTokenProvider.createToken(username);
  78.  
  79. // Установка Cookie для токенов
  80. response.addCookie(new Cookie("access_token", accessToken));
  81. response.addCookie(new Cookie("refresh_token", refreshToken));
  82. }
  83.  
  84. // Дополнительные методы для обработки /refresh и др.
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement