Lab6: JWT server-side is ready. It's frontend turn

This commit is contained in:
Сергей Полевой 2023-05-16 03:53:59 +04:00
parent c1a2e77e4d
commit 75f4b6a178
16 changed files with 624 additions and 166 deletions

View File

@ -6,6 +6,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta name="viewport" content="width=device-width,initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/chota@latest"> <link rel="stylesheet" href="https://unpkg.com/chota@latest">
<script src="https://code.jquery.com/jquery-3.7.0.slim.min.js" integrity="sha256-tG5mcZUtJsZvyKAxYLVXrmjKBVLd6VpVccqz/r4ypFE=" crossorigin="anonymous"></script>
<title>Социальная сеть</title> <title>Социальная сеть</title>
</head> </head>
<body class="container"> <body class="container">

View File

@ -1,44 +1,66 @@
<template> <template>
<div class="nav row"> <div class="nav row">
<div class="nav-left col-10"> <div class="nav-left col-10">
<router-link to="/customers" class="button primary clear">Профили</router-link> <router-link to="/customers" v-bind:class="'button primary ' + this.$route.path.startsWith('/customers')? 'clear' : ''">Профили</router-link>
<router-link to="/posts" class="button primary clear">Посты</router-link> <router-link to="/feed" v-bind:class="'button primary ' + this.$route.path.startsWith('/feed')? 'clear' : ''">Посты</router-link>
<router-link v-if="role === 'ADMIN'" to="/admin" v-bind:class="'button primary ' + this.$route.path.startsWith('/admin')? 'clear' : ''">Администрирование</router-link>
</div> </div>
<div class="nav-right col-2"> <div class="nav-right col-2">
<select class="form-select" style="font-size: 16px;" v-model="currentCustomerId"> <router-link v-if="" to="/login" v-bind:class="'button primary ' + this.$route.path.startsWith('/login')? 'clear' : ''">Войти</router-link>
<option value="-1" selected class="button dark outline" :on-click="updateCurrentCustomer()">Не выбран</option> <button v-on:click="logout()" v-bind:class="'button primary ' + this.$route.path.startsWith('/signup')? 'clear' : ''">Выйти</button>
<option v-for="customer in customers" v-bind:value="customer['id']" class="button dark outline" :on-click="updateCurrentCustomer()">{{ customer['username'] }}</option>
</select>
</div> </div>
</div> </div>
<router-view></router-view> <router-view></router-view>
</template> </template>
<script> <script>
import axios from 'axios'
export default { export default {
data() { data() {
return { return {
currentCustomerId: -1, token_value: localStorage.getItem("token"),
customers: [] role: ''
} }
}, },
methods: { methods: {
async updateCurrentCustomer() { logout() {
history.replaceState(this.currentCustomerId, ""); this.token = null
this.$router.push('login')
}
},
computed: {
token: {
get: function() {
return this.token_value
},
set: function(value) {
this.token_value = value
localStorage.setItem("token", value)
}
} }
}, },
async beforeMount() { async beforeMount() {
setInterval(async () => { if (localStorage.getItem("token") === null) {
const response = await axios.get('http://localhost:8080/api/customer'); return null;
this.customers = []; }
response.data.forEach(element => {
this.customers.push(element); let response = await fetch(
console.log(element); "http://localhost:8080/api/1.0/customer/role/" + localStorage.getItem("token"),
}); {
}, 500) method: "POST",
headers: {
}, "Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.role = await response.json()
const component = this
document.addEventListener('token_changed', function() {
component.token = localStorage.getItem("token")
})
}
} }
</script> </script>

View File

@ -4,15 +4,6 @@
<div class="row mb-5"> <div class="row mb-5">
<p class='is-center h2'>Профили</p> <p class='is-center h2'>Профили</p>
</div> </div>
<div class="row mb-5">
<div class="col"></div>
<div class="col-10 is-center">
<button class="button primary" data-bs-toggle="modal" data-bs-target="#customerCreate">
Добавить нового пользователя
</button>
</div>
<div class="col"></div>
</div>
<p class='h3 is-center row mb-5'>Список профилей</p> <p class='h3 is-center row mb-5'>Список профилей</p>
<div class="row"> <div class="row">
@ -20,20 +11,19 @@
<div v-for="customer in customers" class="row card mb-3"> <div v-for="customer in customers" class="row card mb-3">
<div class="row"> <div class="row">
<div class="col is-left h3">ID: {{ customer['id'] }}</div> <div class="col is-left h3">ID: {{ customer['id'] }}</div>
<div class="col is-center h3">Никнейм: {{ customer['username'] }}</div> <div class="col is-right h3">Никнейм: {{ customer['username'] }}</div>
<div class="col is-right h3">Пароль: {{ customer['password'] }}</div>
</div> </div>
<p class="row">Комментарии:</p> <p class="row">Комментарии:</p>
<div class="row" v-if="!(customer['comments'].length == 0)"> <div class="row" v-if="customer['comments'].length !== 0">
<div class="col"> <div class="col">
<div v-for="comment in customer['comments']" class="row is-left card mb-3"> <div v-for="comment in customer['comments']" class="row is-left card mb-3">
<div class="row is-left h4">"{{ comment['content'] }}" - к посту '{{ comment['postTitle'] }}' от пользователя {{ comment['postAuthor'] }}</div> <div class="row is-left h4">"{{ comment['content'] }}" - к посту "{{ comment['postTitle'] }}" от пользователя {{ comment['postAuthor'] }}</div>
</div> </div>
</div> </div>
</div> </div>
<p v-else class="row">Нет комментариев</p> <p v-else class="row">Нет комментариев</p>
<p class="row">Посты: </p> <p class="row">Посты: </p>
<div class="row" v-if="!(customer['posts'].length == 0)"> <div class="row" v-if="customer['posts'].length !== 0">
<div class="col"> <div class="col">
<div v-for="post in customer['posts']" class="row is-left card mb-3"> <div v-for="post in customer['posts']" class="row is-left card mb-3">
<div class="row is-center h1">{{ post['title'] }}</div> <div class="row is-center h1">{{ post['title'] }}</div>
@ -42,128 +32,115 @@
</div> </div>
</div> </div>
<p v-else class="row">Нет постов</p> <p v-else class="row">Нет постов</p>
<div class="row" v-if="customer['id'] == currentCustomerId"> <div class="row" v-if="currentCustomerId === customer['id']">
<button v-on:click="deleteUser(customer['id'])" class="col button dark outline">Удалить</button> <button v-on:click="deleteCustomer(customer)" class="button dark outline is-full-width">Удалить</button>
<button v-on:click="selectedCustomer = customer; usernameModal=customer['username'];passwordModal=customer['password']" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button> <button v-on:click="prepareEditModal(customer)" class="col button primary outline" data-bs-toggle="modal" data-bs-target="#customerEdit">Редактировать</button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!-- Modal -->
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="customerCreateLabel">Создать профиль</h5>
</div>
<div class="modal-body text-center">
<p>Логин</p>
<textarea v-model='usernameModal' id="usernameText" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea v-model='passwordModal' id="passwordText" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary" v-on:click='createUser'>Сохранить</button>
</div>
</div>
</div>
</div>
<!-- Modal --> <!-- Modal -->
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true"> <div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">
<div class="modal-dialog" role="document"> <div class="modal-dialog" role="document">
<div class="modal-content"> <div class="modal-content" id="edit-customer-form">
<div class="modal-header"> <div class="modal-header">
<h5 class="modal-title" id="customerEditLabel">Редактировать профиль</h5> <h5 class="modal-title" id="customerEditLabel">Редактировать профиль</h5>
</div>
<div class="modal-body text-center">
<p>Логин</p>
<textarea name="username" id="usernameTextE" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea name="password" id="passwordTextE" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button v-on:click="editCustomer()" type="button" class="btn btn-primary"> data-bs-dismiss="modal"Изменить</button>
</div>
</div> </div>
<div class="modal-body text-center">
<p>Логин</p>
<textarea v-model='usernameModal' id="usernameText" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea v-model='passwordModal' id="passwordText" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary" v-on:click='editUser'>Изменить</button>
</div>
</div>
</div> </div>
</div> </div>
</template> </template>
<script> <script>
import axios from 'axios'
export default { export default {
data() { data() {
return { return {
customers: [], customers: [],
usernameModal: '',
passwordModal: '',
selectedCustomer: {},
currentCustomerId: -1 currentCustomerId: -1
} }
}, },
methods: { methods: {
async createUser(){ async updateCustomers() {
let customer = { const response = await fetch(
username: this.usernameModal, "http://localhost:8080/api/1.0/customer",
password: this.passwordModal {
}; method: "GET",
const response = await axios.post('http://localhost:8080/api/customer', customer); headers: {
this.refreshList(); "Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.customers = await response.json()
}, },
async deleteUser(id) { async getCurrentCustomer() {
const response = await axios.delete('http://localhost:8080/api/customer/' + id); const response = await fetch(
this.refreshList(); "http://localhost:8080/api/1.0/customer/me",
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
}
}
)
this.currentCustomerId = (await response.json())['id']
}, },
async editUser() { prepareEditModal(customer) {
let customer = { $("#usernameTextE").val(customer['username'])
username: this.usernameModal,
password: this.passwordModal
};
const response = await axios.put('http://localhost:8080/api/customer/' + this.selectedCustomer['id'], customer);
this.refreshList();
}, },
async refreshList() { async deleteCustomer() {
this.customers = []; await fetch(
if (this.$route.params.id === "") { "http://localhost:8080/api/1.0/customer/" + this.currentCustomerId,
const response = await axios.get('http://localhost:8080/api/customer'); {
response.data.forEach(element => { method: "DELETE",
this.customers.push(element); headers: {
console.log(element); "Authorization": "Bearer " + localStorage.getItem("token")
}); }
} else { }
const response = await axios.get('http://localhost:8080/api/customer/' + this.$route.params.id); )
this.customers.push(response.data)
localStorage.clear()
this.$router.push("login")
},
async editCustomer() {
await fetch(
"http://localhost:8080/api/1.0/customer/" + this.currentCustomerId,
{
method: "GET",
headers: {
"Authorization": "Bearer " + localStorage.getItem("token")
},
body: JSON.stringify({
username: $("usernameTextE").val(),
password: $("passwordTextE").val()
})
}
)
await this.updateCustomers()
} }
},
}, },
async mounted() { async beforeMount() {
this.currentCustomerId = history.state; if (localStorage.getItem("token") === null) {
setInterval(async () => this.currentCustomerId = history.state, 50) this.$router.replace("login")
if (this.$route.params.id === "") {
const response = await axios.get('http://localhost:8080/api/customer');
response.data.forEach(element => {
this.customers.push(element);
console.log(element);
});
} else {
const response = await axios.get('http://localhost:8080/api/customer/' + this.$route.params.id);
this.customers.push(response.data)
} }
}, await Promise.all([this.updateCustomers(), this.getCurrentCustomer()])
async beforeRouteUpdate(to, from) { }
this.$route.params.id = to.params.id;
this.refreshList();
},
} }
</script> </script>

View File

@ -0,0 +1,61 @@
<template>
<div class="row">
<div class="col"></div>
<div class="col-6">
<div class="row mb-3">
<label>Имя пользователя: <input type="text" id="username" required /></label>
</div>
<div class="row mb-3">
<label>Пароль: <input type="password" id="password" required /></label>
</div>
<div class="row mb-3 alert alert-danger" v-if="error !== null" role="alert">
{{ error }}
</div>
<div class="row mt-3">
<div class="col-4"></div>
<button v-on:click="login()" type="button" class="button primary col" id="enter">Войти</button>
<div class="col-4"></div>
</div>
<div class="row mt-5">
<router-link to="/login" class="button primary outline">Регистрация</router-link>
</div>
</div>
<div class="col"></div>
</div>
</template>
<script>
export default {
data() {
return {
error: null
}
},
methods: {
async login() {
let response = await fetch(
"http://localhost:8080/api/1.0/customer/jwt/login",
{
method: "POST",
body: JSON.stringify({
username: $("#username").val(),
password: $("#password").val()
})
}
)
if (response.statusCode !== 200) {
this.error = await response.text()
} else {
localStorage.setItem("token", await response.text())
document.dispatchEvent(new Event("token_changed"))
this.$router.push("feed")
}
}
}
}
</script>
<style>
</style>

View File

@ -0,0 +1,66 @@
<template>
<div class="row">
<div class="col"></div>
<div class="col-6">
<div class="row">
<label>Имя пользователя: <input type="text" id="username" required /></label>
</div>
<div class="row">
<label>Пароль: <input v-on:change="check()" type="password" id="password" required /></label>
</div>
<div class="row">
<label>Пароль повторно: <input v-on:change="check()" type="password" id="confirm-password" required /></label>
</div>
<div class="row mb-3 alert alert-danger" v-if="error !== null" role="alert">
{{ error }}
</div>
<div class="row mt-3">
<div class="col-4"></div>
<button v-on:click="register()" class="button primary col" id="enter" disabled>Регистрация</button>
<div class="col-4"></div>
</div>
</div>
<div class="col"></div>
</div>
</template>
<script>
export default {
data() {
return {
error: null
}
},
methods: {
check() {
if ($("#password").val() !== $("#confirm-password").val()) {
$("#enter").removeAttr("disabled")
} else {
$("#enter").attr("disabled", "disabled")
}
},
async register() {
const response = await fetch(
"http://localhost:8080/api/1.0/customer",
{
method: "POST",
body: JSON.stringify({
username: $("#username").val(),
password: $("#password").val()
})
}
)
if (response.statusCode !== 200) {
this.error = await response.text()
} else {
this.$router.push("login")
}
}
}
}
</script>
<style>
</style>

View File

@ -3,20 +3,24 @@ import App from './App'
import { createRouter, createWebHistory } from "vue-router" import { createRouter, createWebHistory } from "vue-router"
import Customers from './components/Customers' import Customers from './components/Customers'
import Posts from './components/Posts' import Feed from './components/Feed'
import Login from "@/components/Login.vue";
const routes = [ const routes = [
{ {
path: '/customers/:id?', path: '/customers/:id?',
name: "Customers", name: "Customers",
component: Customers, component: Customers
props: true
}, },
{ {
path: '/posts', path: '/feed',
name: "Posts", name: "Feed",
component: Posts, component: Feed
props: true },
{
path: '/login',
name: "Login",
component: Login
} }
] ]

View File

@ -0,0 +1,11 @@
package np.something.Exceptions;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,28 @@
package np.something;
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 np.something.security.JwtFilter;
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")));
}
}

View File

@ -1,18 +1,31 @@
package np.something; package np.something;
import np.something.security.SecurityConfiguration;
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"; public static final String REST_API = OpenAPI30Configuration.API_PREFIX;
@Override @Override
public void addViewControllers(ViewControllerRegistry registry) { public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry); WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("login"); registry.addViewController("login");
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
} }
@Override @Override

View File

@ -5,6 +5,7 @@ import np.something.DTO.CustomerDto;
import np.something.WebConfiguration; import np.something.WebConfiguration;
import np.something.model.Customer; import np.something.model.Customer;
import np.something.services.*; import np.something.services.*;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@ -12,6 +13,7 @@ import java.util.List;
@RestController @RestController
@RequestMapping(WebConfiguration.REST_API + "/customer") @RequestMapping(WebConfiguration.REST_API + "/customer")
public class CustomerController { public class CustomerController {
public static final String URL_LOGIN = "/jwt/login";
private final CustomerService customerService; private final CustomerService customerService;
public CustomerController(CustomerService customerService) { public CustomerController(CustomerService customerService) {
@ -50,4 +52,31 @@ public class CustomerController {
public void deleteAllCustomers(){ public void deleteAllCustomers(){
customerService.deleteAllCustomers(); customerService.deleteAllCustomers();
} }
@GetMapping("/find/{username}")
public CustomerDto getCustomerByUsername(@PathVariable String username) {
return new CustomerDto(customerService.findByUsername(username));
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid CustomerDto customerDto) {
return customerService.loginAndGetToken(customerDto);
}
@GetMapping ("/me")
CustomerDto getCurrentCustomer(@RequestHeader(HttpHeaders.AUTHORIZATION) String token) {
return new CustomerDto(customerService.findByUsername(customerService.loadUserByToken(token).getUsername()));
}
@GetMapping("role/{token}")
public String getRoleByToken(@PathVariable String token) {
var userDetails = customerService.loadUserByToken(token);
Customer customer = customerService.findByUsername(userDetails.getUsername());
if (customer != null) {
return customer.getRole().toString();
}
return null;
}
} }

View File

@ -0,0 +1,73 @@
package np.something.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import np.something.Exceptions.JwtException;
import np.something.services.CustomerService;
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 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 CustomerService customerService;
public JwtFilter(CustomerService customerService) {
this.customerService = customerService;
}
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 = customerService.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);
}
}

View File

@ -0,0 +1,27 @@
package np.something.security;
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;
}
}

View File

@ -0,0 +1,108 @@
package np.something.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import np.something.Exceptions.JwtException;
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();
}
}
}

View File

@ -1,5 +1,7 @@
package np.something.security; package np.something.security;
import np.something.WebConfiguration;
import np.something.controllers.CustomerController;
import np.something.model.UserRole; import np.something.model.UserRole;
import np.something.mvc.UserSignUp; import np.something.mvc.UserSignUp;
import np.something.services.CustomerService; import np.something.services.CustomerService;
@ -13,6 +15,8 @@ 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.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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@ -20,10 +24,13 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class); private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
private static final String LOGIN_URL = "/login"; private static final String LOGIN_URL = "/login";
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private final CustomerService customerService; private final CustomerService customerService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(CustomerService customerService) { public SecurityConfiguration(CustomerService customerService) {
this.customerService = customerService; this.customerService = customerService;
this.jwtFilter = new JwtFilter(customerService);
createAdminOnStartup(); createAdminOnStartup();
} }
@ -35,20 +42,38 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
} }
} }
// @Override
// protected void configure(HttpSecurity http) throws Exception {
// http.headers().frameOptions().sameOrigin().and()
// .cors().and()
// .csrf().disable()
// .authorizeRequests()
// .antMatchers(UserSignUp.SIGNUP_URL).permitAll()
// .antMatchers(HttpMethod.GET, LOGIN_URL).permitAll()
// .anyRequest().authenticated()
// .and()
// .formLogin()
// .loginPage(LOGIN_URL).permitAll()
// .and()
// .logout().permitAll();
// }
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().sameOrigin().and() log.info("Creating security configuration");
.cors().and() http.cors()
.and()
.csrf().disable() .csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests() .authorizeRequests()
.antMatchers(UserSignUp.SIGNUP_URL).permitAll() .antMatchers("/", SPA_URL_MASK).permitAll()
.antMatchers(HttpMethod.GET, LOGIN_URL).permitAll() .antMatchers(HttpMethod.POST, WebConfiguration.REST_API + "/customer" + CustomerController.URL_LOGIN).permitAll()
.anyRequest().authenticated() .anyRequest()
.authenticated()
.and() .and()
.formLogin() .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.loginPage(LOGIN_URL).permitAll() .anonymous();
.and()
.logout().permitAll();
} }
@Override @Override
@ -62,6 +87,8 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
.antMatchers("/css/**") .antMatchers("/css/**")
.antMatchers("/js/**") .antMatchers("/js/**")
.antMatchers("/templates/**") .antMatchers("/templates/**")
.antMatchers("/webjars/**"); .antMatchers("/webjars/**")
.antMatchers("/swagger-resources/**")
.antMatchers("/v3/api-docs/**");
} }
} }

View File

@ -1,10 +1,14 @@
package np.something.services; package np.something.services;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import np.something.DTO.CustomerDto;
import np.something.Exceptions.CustomerNotFoundException; import np.something.Exceptions.CustomerNotFoundException;
import np.something.Exceptions.JwtException;
import np.something.model.Customer; import np.something.model.Customer;
import np.something.model.UserRole; import np.something.model.UserRole;
import np.something.repositories.CustomerRepository; import np.something.repositories.CustomerRepository;
import np.something.security.JwtProvider;
import np.something.util.validation.ValidatorUtil; import np.something.util.validation.ValidatorUtil;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
@ -20,12 +24,14 @@ public class CustomerService implements UserDetailsService {
private final CustomerRepository customerRepository; private final CustomerRepository customerRepository;
private final ValidatorUtil validatorUtil; private final ValidatorUtil validatorUtil;
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final JwtProvider jwtProvider;
public CustomerService(CustomerRepository customerRepository, public CustomerService(CustomerRepository customerRepository,
ValidatorUtil validatorUtil, PasswordEncoder passwordEncoder) { ValidatorUtil validatorUtil, PasswordEncoder passwordEncoder, JwtProvider jwtProvider) {
this.customerRepository = customerRepository; this.customerRepository = customerRepository;
this.validatorUtil = validatorUtil; this.validatorUtil = validatorUtil;
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
this.jwtProvider = jwtProvider;
} }
@Transactional @Transactional
@ -86,4 +92,29 @@ public class CustomerService implements UserDetailsService {
return new org.springframework.security.core.userdetails.User( return new org.springframework.security.core.userdetails.User(
customerEntity.getUsername(), customerEntity.getPassword(), Collections.singleton(customerEntity.getRole())); customerEntity.getUsername(), customerEntity.getPassword(), Collections.singleton(customerEntity.getRole()));
} }
public String loginAndGetToken(CustomerDto customerDto) {
try {
final Customer customer = findByUsername(customerDto.getUsername());
if (customer == null) {
throw new Exception("Login not found" + customerDto.getUsername());
}
if (!passwordEncoder.matches(customerDto.getPassword(), customer.getPassword())) {
throw new Exception("User not found" + customer.getUsername());
}
return jwtProvider.generateToken(customer.getUsername());
}
catch (Exception e) {
return null;
}
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> new JwtException("Token is not contain Login"));
return loadUserByUsername(userLogin);
}
} }

View File

@ -48,26 +48,6 @@
</div> </div>
</div> </div>
</div> </div>
<!-- Modal -->
<div class="modal fade" id="customerCreate" tabindex="-1" role="dialog" aria-labelledby="customerCreateLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form class="modal-content" th:action="@{/customers/}" method="post">
<div class="modal-header">
<h5 class="modal-title" id="customerCreateLabel">Создать профиль</h5>
</div>
<div class="modal-body text-center">
<p>Логин</p>
<textarea name="username" id="usernameTextC" cols="30" rows="1"></textarea>
<p>Пароль</p>
<textarea name="password" id="passwordTextC" cols="30" rows="1"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Сохранить</button>
</div>
</form>
</div>
</div>
<!-- Modal --> <!-- Modal -->
<div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true"> <div class="modal fade" id="customerEdit" tabindex="-1" role="dialog" aria-labelledby="customerEditLabel" aria-hidden="true">