Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.annotation.web.configuration.WebSecurityConfigurerAdapter;
- @Configuration
- @EnableWebSecurity
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable()
- .authorizeRequests()
- .antMatchers("/auth").permitAll() // Разрешить доступ к /auth всем
- .anyRequest().authenticated()
- .and()
- .addFilter(new JwtAuthenticationFilter(authenticationManager()))
- .addFilter(new JwtAuthorizationFilter(authenticationManager()))
- .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
- }
- // Дополнительные настройки, если необходимо
- }
- import io.jsonwebtoken.Jwts;
- import io.jsonwebtoken.SignatureAlgorithm;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- import java.util.Date;
- @Component
- public class JwtTokenProvider {
- @Value("${jwt.secret}")
- private String secretKey;
- @Value("${jwt.expiration}")
- private long validityInMilliseconds;
- public String createToken(String username) {
- Date now = new Date();
- Date validity = new Date(now.getTime() + validityInMilliseconds);
- return Jwts.builder()
- .setSubject(username)
- .setIssuedAt(now)
- .setExpiration(validity)
- .signWith(SignatureAlgorithm.HS256, secretKey)
- .compact();
- }
- // Дополнительные методы для проверки токена и обновления
- }
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RestController;
- import javax.servlet.http.Cookie;
- import javax.servlet.http.HttpServletResponse;
- @RestController
- public class AuthController {
- private final JwtTokenProvider jwtTokenProvider;
- // Инъекция зависимости через конструктор
- @PostMapping("/auth")
- public void authenticate(HttpServletResponse response) {
- // Логика аутентификации
- String username = "exampleUser"; // Получите имя пользователя из запроса
- // Генерация токенов
- String accessToken = jwtTokenProvider.createToken(username);
- String refreshToken = jwtTokenProvider.createToken(username);
- // Установка Cookie для токенов
- response.addCookie(new Cookie("access_token", accessToken));
- response.addCookie(new Cookie("refresh_token", refreshToken));
- }
- // Дополнительные методы для обработки /refresh и др.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement