Начало работы с React.
This commit is contained in:
parent
537fffe177
commit
13b10d97ac
@ -0,0 +1,27 @@
|
|||||||
|
package premium_store.configuration;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.models.Components;
|
||||||
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
|
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||||
|
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class OpenAPI30Configuration {
|
||||||
|
public static final String API_PREFIX = "/api/1.0";
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public OpenAPI customizeOpenAPI() {
|
||||||
|
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
|
||||||
|
return new OpenAPI()
|
||||||
|
.addSecurityItem(new SecurityRequirement()
|
||||||
|
.addList(securitySchemeName))
|
||||||
|
.components(new Components()
|
||||||
|
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
|
||||||
|
.name(securitySchemeName)
|
||||||
|
.type(SecurityScheme.Type.HTTP)
|
||||||
|
.scheme("bearer")
|
||||||
|
.bearerFormat("JWT")));
|
||||||
|
}
|
||||||
|
}
|
@ -2,70 +2,89 @@ package premium_store.configuration;
|
|||||||
|
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.http.HttpMethod;
|
import org.springframework.http.HttpMethod;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
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.builders.HttpSecurity;
|
||||||
import org.springframework.security.config.annotation.web.builders.WebSecurity;
|
|
||||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
|
||||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||||
import premium_store.controller.controller.UserSignupMvcController;
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||||
|
import premium_store.controller.controller.GameClientController;
|
||||||
import premium_store.model.UserRole;
|
import premium_store.model.UserRole;
|
||||||
import premium_store.service.GameClientService;
|
import premium_store.service.GameClientService;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableWebSecurity
|
@EnableWebSecurity
|
||||||
@EnableGlobalMethodSecurity(
|
@EnableMethodSecurity(
|
||||||
securedEnabled = true
|
securedEnabled = true
|
||||||
)
|
)
|
||||||
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
|
public class SecurityConfiguration {
|
||||||
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
|
||||||
private static final String LOGIN_URL = "/login";
|
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
|
||||||
private final GameClientService clientService;
|
private final GameClientService userService;
|
||||||
|
private final JwtFilter jwtFilter;
|
||||||
|
|
||||||
public SecurityConfiguration(GameClientService clientService) {
|
public SecurityConfiguration(GameClientService userService) {
|
||||||
this.clientService = clientService;
|
this.userService = userService;
|
||||||
|
this.jwtFilter = new JwtFilter(userService);
|
||||||
createAdminOnStartup();
|
createAdminOnStartup();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void createAdminOnStartup() {
|
private void createAdminOnStartup() {
|
||||||
final String admin = "admin";
|
final String admin = "admin";
|
||||||
if (clientService.findByLogin(admin) == null) {
|
if (userService.findByLogin(admin) == null) {
|
||||||
log.info("Admin user successfully created");
|
log.info("Admin user successfully created");
|
||||||
clientService.addClient(admin, "adminemail@gmail.com", admin, 100, admin, UserRole.ADMIN);
|
userService.addClient(admin, "admin@gmail.com", admin, admin, UserRole.ADMIN);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Bean
|
||||||
public void configure(HttpSecurity http) throws Exception {
|
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||||
http.headers().frameOptions().sameOrigin().and()
|
http.cors()
|
||||||
.cors().and()
|
.and()
|
||||||
.csrf().disable()
|
.csrf().disable()
|
||||||
|
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||||
|
.and()
|
||||||
.authorizeRequests()
|
.authorizeRequests()
|
||||||
.antMatchers(UserSignupMvcController.SIGNUP_URL).permitAll()
|
.antMatchers("/", SPA_URL_MASK).permitAll()
|
||||||
.antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
|
.antMatchers(HttpMethod.POST, GameClientController.URL_LOGIN).permitAll()
|
||||||
.anyRequest().authenticated()
|
.antMatchers(HttpMethod.POST, GameClientController.URL_SING_UP).permitAll()
|
||||||
|
.antMatchers(HttpMethod.POST, GameClientController.URL_WHO_AM_I).permitAll()
|
||||||
|
.anyRequest()
|
||||||
|
.authenticated()
|
||||||
.and()
|
.and()
|
||||||
.formLogin()
|
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
|
||||||
.loginPage(LOGIN_URL).permitAll()
|
.anonymous();
|
||||||
.and()
|
return http.build();
|
||||||
.logout().permitAll();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Bean
|
||||||
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
|
public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception {
|
||||||
auth.userDetailsService(clientService);
|
AuthenticationManagerBuilder authenticationManagerBuilder = http
|
||||||
|
.getSharedObject(AuthenticationManagerBuilder.class);
|
||||||
|
authenticationManagerBuilder.userDetailsService(userService);
|
||||||
|
return authenticationManagerBuilder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Bean
|
||||||
public void configure(WebSecurity web) {
|
public WebSecurityCustomizer webSecurityCustomizer() {
|
||||||
web.ignoring()
|
return (web) -> web.ignoring()
|
||||||
.antMatchers("/css/**")
|
.antMatchers(HttpMethod.OPTIONS, "/**")
|
||||||
.antMatchers("/js/**")
|
.antMatchers("/*.js")
|
||||||
.antMatchers("/templates/**")
|
.antMatchers("/*.html")
|
||||||
.antMatchers("/webjars/**");
|
.antMatchers("/*.css")
|
||||||
|
.antMatchers("/assets/**")
|
||||||
|
.antMatchers("/favicon.ico")
|
||||||
|
.antMatchers("/.js", "/.css")
|
||||||
|
.antMatchers("/swagger-ui/index.html")
|
||||||
|
.antMatchers("/webjars/**")
|
||||||
|
.antMatchers("/swagger-resources/**")
|
||||||
|
.antMatchers("/v3/api-docs/**")
|
||||||
|
.antMatchers("/h2-console");
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,18 +1,26 @@
|
|||||||
package premium_store.configuration;
|
package premium_store.configuration;
|
||||||
|
|
||||||
|
import org.springframework.boot.web.server.ErrorPage;
|
||||||
|
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
|
||||||
|
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class WebConfiguration implements WebMvcConfigurer {
|
public class WebConfiguration implements WebMvcConfigurer {
|
||||||
public static final String REST_API = "/api";
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void addViewControllers(ViewControllerRegistry registry) {
|
public void addViewControllers(ViewControllerRegistry registry) {
|
||||||
WebMvcConfigurer.super.addViewControllers(registry);
|
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
|
||||||
registry.addViewController("login");
|
registry.addViewController("/notFound").setViewName("forward:/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
|
||||||
|
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -0,0 +1,11 @@
|
|||||||
|
package premium_store.configuration.jwt;
|
||||||
|
|
||||||
|
public class JwtException extends RuntimeException {
|
||||||
|
public JwtException(Throwable throwable) {
|
||||||
|
super(throwable);
|
||||||
|
}
|
||||||
|
|
||||||
|
public JwtException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,74 @@
|
|||||||
|
package premium_store.configuration.jwt;
|
||||||
|
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.filter.GenericFilterBean;
|
||||||
|
import premium_store.service.GameClientService;
|
||||||
|
|
||||||
|
import javax.servlet.FilterChain;
|
||||||
|
import javax.servlet.ServletException;
|
||||||
|
import javax.servlet.ServletRequest;
|
||||||
|
import javax.servlet.ServletResponse;
|
||||||
|
import javax.servlet.http.HttpServletRequest;
|
||||||
|
import javax.servlet.http.HttpServletResponse;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class JwtFilter extends GenericFilterBean {
|
||||||
|
private static final String AUTHORIZATION = "Authorization";
|
||||||
|
public static final String TOKEN_BEGIN_STR = "Bearer ";
|
||||||
|
|
||||||
|
private final GameClientService userService;
|
||||||
|
|
||||||
|
public JwtFilter(GameClientService userService) {
|
||||||
|
this.userService = userService;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getTokenFromRequest(HttpServletRequest request) {
|
||||||
|
String bearer = request.getHeader(AUTHORIZATION);
|
||||||
|
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
|
||||||
|
return bearer.substring(TOKEN_BEGIN_STR.length());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void raiseException(ServletResponse response, int status, String message) throws IOException {
|
||||||
|
if (response instanceof final HttpServletResponse httpResponse) {
|
||||||
|
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||||
|
httpResponse.setStatus(status);
|
||||||
|
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
|
||||||
|
response.getOutputStream().write(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void doFilter(ServletRequest request,
|
||||||
|
ServletResponse response,
|
||||||
|
FilterChain chain) throws IOException, ServletException {
|
||||||
|
if (request instanceof final HttpServletRequest httpRequest) {
|
||||||
|
final String token = getTokenFromRequest(httpRequest);
|
||||||
|
if (StringUtils.hasText(token)) {
|
||||||
|
try {
|
||||||
|
final UserDetails user = userService.loadUserByToken(token);
|
||||||
|
final UsernamePasswordAuthenticationToken auth =
|
||||||
|
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
} catch (JwtException e) {
|
||||||
|
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
|
||||||
|
return;
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
|
||||||
|
String.format("Internal error: %s", e.getMessage()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,27 @@
|
|||||||
|
package premium_store.configuration.jwt;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
|
||||||
|
public class JwtProperties {
|
||||||
|
private String devToken = "";
|
||||||
|
private Boolean isDev = true;
|
||||||
|
|
||||||
|
public String getDevToken() {
|
||||||
|
return devToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDevToken(String devToken) {
|
||||||
|
this.devToken = devToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean isDev() {
|
||||||
|
return isDev;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDev(Boolean dev) {
|
||||||
|
isDev = dev;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,102 @@
|
|||||||
|
package premium_store.configuration.jwt;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JwtProvider {
|
||||||
|
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
|
||||||
|
|
||||||
|
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
|
||||||
|
private final static String ISSUER = "auth0";
|
||||||
|
|
||||||
|
private final Algorithm algorithm;
|
||||||
|
private final JWTVerifier verifier;
|
||||||
|
|
||||||
|
public JwtProvider(JwtProperties jwtProperties) {
|
||||||
|
if (!jwtProperties.isDev()) {
|
||||||
|
LOG.info("Generate new JWT key for prod");
|
||||||
|
try {
|
||||||
|
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
|
||||||
|
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
|
||||||
|
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
|
||||||
|
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new JwtException(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
|
||||||
|
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
|
||||||
|
}
|
||||||
|
verifier = JWT.require(algorithm)
|
||||||
|
.withIssuer(ISSUER)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String bytesToHex(byte[] bytes) {
|
||||||
|
byte[] hexChars = new byte[bytes.length * 2];
|
||||||
|
for (int j = 0; j < bytes.length; j++) {
|
||||||
|
int v = bytes[j] & 0xFF;
|
||||||
|
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
|
||||||
|
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
|
||||||
|
}
|
||||||
|
return new String(hexChars, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String generateToken(String login) {
|
||||||
|
final Date issueDate = Date.from(LocalDate.now()
|
||||||
|
.atStartOfDay(ZoneId.systemDefault())
|
||||||
|
.toInstant());
|
||||||
|
final Date expireDate = Date.from(LocalDate.now()
|
||||||
|
.plusDays(15)
|
||||||
|
.atStartOfDay(ZoneId.systemDefault())
|
||||||
|
.toInstant());
|
||||||
|
return JWT.create()
|
||||||
|
.withIssuer(ISSUER)
|
||||||
|
.withIssuedAt(issueDate)
|
||||||
|
.withExpiresAt(expireDate)
|
||||||
|
.withSubject(login)
|
||||||
|
.sign(algorithm);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DecodedJWT validateToken(String token) {
|
||||||
|
try {
|
||||||
|
return verifier.verify(token);
|
||||||
|
} catch (JWTVerificationException e) {
|
||||||
|
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isTokenValid(String token) {
|
||||||
|
if (!StringUtils.hasText(token)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
validateToken(token);
|
||||||
|
return true;
|
||||||
|
} catch (JwtException e) {
|
||||||
|
LOG.error(e.getMessage());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<String> getLoginFromToken(String token) {
|
||||||
|
try {
|
||||||
|
return Optional.ofNullable(validateToken(token).getSubject());
|
||||||
|
} catch (JwtException e) {
|
||||||
|
LOG.error(e.getMessage());
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user