Skip to content

Commit 8ef8cea

Browse files
committed
Refactoring
Signed-off-by: Kvark900 <kvant800@gmail.com>
1 parent 04f458c commit 8ef8cea

35 files changed

+469
-430
lines changed

pom.xml

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
<parent>
1212
<groupId>org.springframework.boot</groupId>
1313
<artifactId>spring-boot-starter-parent</artifactId>
14-
<version>1.5.4.RELEASE</version>
14+
<version>2.1.8.RELEASE</version>
1515
</parent>
1616

1717
<properties>
@@ -50,20 +50,14 @@
5050
<dependency>
5151
<groupId>org.springframework.boot</groupId>
5252
<artifactId>spring-boot-starter-security</artifactId>
53-
<version>1.5.9.RELEASE</version>
53+
<version>2.1.8.RELEASE</version>
5454
</dependency>
5555
<!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
5656
<dependency>
5757
<groupId>io.jsonwebtoken</groupId>
5858
<artifactId>jjwt</artifactId>
5959
<version>0.9.0</version>
6060
</dependency>
61-
<dependency>
62-
<groupId>com.fasterxml.jackson.datatype</groupId>
63-
<artifactId>jackson-datatype-hibernate4</artifactId>
64-
</dependency>
65-
66-
6761
</dependencies>
6862

6963
<build>

routes-test.http

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
###
2+
GET http://localhost:8080/authors
3+
Content-Type: application/json
4+
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTU4NTQ4MTgzOSwiaWF0IjoxNTg0ODc3MDM5fQ.NwFdUKJqmyAvkLvX5g90Q-d1eL4i3lHOR0oK9SRDjwdI0i5I9G5D3T-P3grvteiCatZ3672Gd9Ojoq5hvJDJPA
5+
6+
###
7+
GET http://localhost:8080/books
8+
Content-Type: application/json
9+
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImV4cCI6MTU4NTQ4MTgzOSwiaWF0IjoxNTg0ODc3MDM5fQ.NwFdUKJqmyAvkLvX5g90Q-d1eL4i3lHOR0oK9SRDjwdI0i5I9G5D3T-P3grvteiCatZ3672Gd9Ojoq5hvJDJPA
10+
11+
12+
### Bad credentials
13+
POST http://localhost:8080/auth
14+
Content-Type: application/json
15+
16+
{
17+
"username": "admin",
18+
"password": "admin1"
19+
}
20+
21+
###
22+
23+
### Succces
24+
POST http://localhost:8080/auth
25+
Content-Type: application/json
26+
27+
{
28+
"username": "admin",
29+
"password": "admin"
30+
}
31+
32+
###
33+

src/main/java/com/kvark900/BootifulApplication.java

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
package com.kvark900;
22

3-
import com.fasterxml.jackson.databind.Module;
4-
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
53
import org.springframework.boot.SpringApplication;
64
import org.springframework.boot.autoconfigure.SpringBootApplication;
75
import org.springframework.context.annotation.Bean;
@@ -28,9 +26,4 @@ public void addCorsMappings(CorsRegistry registry) {
2826
};
2927
}
3028

31-
@Bean
32-
public Module hibernate4Module()
33-
{
34-
return new Hibernate4Module();
35-
}
3629
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.kvark900.api.configuration.setupDataLoaders;
1+
package com.kvark900.api.configuration.dataLoaders;
22

33
import com.kvark900.api.model.Author;
44
import com.kvark900.api.model.Book;
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package com.kvark900.api.configuration.dataLoaders;
2+
3+
import com.kvark900.api.configuration.security.user.*;
4+
import org.springframework.context.ApplicationListener;
5+
import org.springframework.context.event.ContextRefreshedEvent;
6+
import org.springframework.stereotype.Component;
7+
import org.springframework.transaction.annotation.Transactional;
8+
9+
import java.util.Collections;
10+
import java.util.Date;
11+
import java.util.List;
12+
13+
@Component
14+
public class UsersLoader implements ApplicationListener<ContextRefreshedEvent> {
15+
private boolean dataLoaded = false;
16+
private RoleService roleService;
17+
private UserService userService;
18+
19+
public UsersLoader(RoleService roleService, UserService userService) {
20+
this.roleService = roleService;
21+
this.userService = userService;
22+
}
23+
24+
@Override
25+
@Transactional
26+
public void onApplicationEvent(final ContextRefreshedEvent contextRefreshedEvent) {
27+
if (dataLoaded) return;
28+
List<Role> adminRoles = Collections.singletonList(createRoleIfNotFound(RoleName.ROLE_ADMIN));
29+
List<Role> userRoles = Collections.singletonList(createRoleIfNotFound(RoleName.ROLE_USER));
30+
createUserIfNotFound("admin", "$2a$08$lDnHPz7eUkSi6ao14Twuau08mzhWrL4kyZGGU5xfiGALO/Vxd5DOi",
31+
"admin", "admin", "admin@admin.com",
32+
true, new Date(1514764800000L), adminRoles);
33+
createUserIfNotFound("user", "$2a$08$UkVvwpULis18S19S5pZFn.YHPZt3oaqHZnDwqbCW9pft6uFtkXKDC",
34+
"user", "user", "enabled@user.com",
35+
true, new Date(1514764800000L), userRoles);
36+
createUserIfNotFound("disabled", "$2a$08$UkVvwpULis18S19S5pZFn.YHPZt3oaqHZnDwqbCW9pft6uFtkXKDC",
37+
"user", "user", "disabled@user.com",
38+
false, new Date(1514764800000L), userRoles);
39+
dataLoaded = true;
40+
}
41+
42+
@Transactional
43+
Role createRoleIfNotFound(RoleName name) {
44+
if (roleService.roleExists(name)) return null;
45+
Role role = new Role(name);
46+
roleService.save(role);
47+
return role;
48+
}
49+
50+
@Transactional
51+
void createUserIfNotFound(String userName, String password, String firstName,
52+
String lastName, String email, boolean enabled,
53+
Date lastPasswordResetDate, List<Role> roles) {
54+
if (userService.userExists(email)) return;
55+
User user = new User();
56+
user.setUsername(userName);
57+
user.setPassword(password);
58+
user.setFirstname(firstName);
59+
user.setLastname(lastName);
60+
user.setEmail(email);
61+
user.setEnabled(enabled);
62+
user.setLastPasswordResetDate(lastPasswordResetDate);
63+
user.setRoles(roles);
64+
userService.save(user);
65+
}
66+
}
67+

src/main/java/com/kvark900/api/configuration/security/JwtAuthenticationRequest.java renamed to src/main/java/com/kvark900/api/configuration/security/AuthenticationRequest.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,18 @@
33
import java.io.Serializable;
44

55

6-
public class JwtAuthenticationRequest implements Serializable {
6+
public class AuthenticationRequest implements Serializable {
77

88
private static final long serialVersionUID = -8445943548965154778L;
99

1010
private String username;
1111
private String password;
1212

13-
public JwtAuthenticationRequest() {
13+
public AuthenticationRequest() {
1414
super();
1515
}
1616

17-
public JwtAuthenticationRequest(String username, String password) {
17+
public AuthenticationRequest(String username, String password) {
1818
this.setUsername(username);
1919
this.setPassword(password);
2020
}

src/main/java/com/kvark900/api/configuration/security/JwtAuthenticationResponse.java renamed to src/main/java/com/kvark900/api/configuration/security/AuthenticationResponse.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33
import java.io.Serializable;
44

55

6-
public class JwtAuthenticationResponse implements Serializable {
6+
public class AuthenticationResponse implements Serializable {
77

88
private static final long serialVersionUID = 1250166508152483573L;
99

1010
private final String token;
1111

12-
public JwtAuthenticationResponse(String token) {
12+
public AuthenticationResponse(String token) {
1313
this.token = token;
1414
}
1515

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package com.kvark900.api.configuration.security;
2+
3+
import io.jsonwebtoken.ExpiredJwtException;
4+
import org.slf4j.Logger;
5+
import org.slf4j.LoggerFactory;
6+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7+
import org.springframework.security.core.context.SecurityContextHolder;
8+
import org.springframework.security.core.userdetails.UserDetails;
9+
import org.springframework.security.core.userdetails.UserDetailsService;
10+
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
11+
import org.springframework.web.filter.OncePerRequestFilter;
12+
13+
import javax.servlet.FilterChain;
14+
import javax.servlet.ServletException;
15+
import javax.servlet.http.HttpServletRequest;
16+
import javax.servlet.http.HttpServletResponse;
17+
import java.io.IOException;
18+
19+
public class JWTTokenFilter extends OncePerRequestFilter {
20+
21+
private final Logger logger = LoggerFactory.getLogger(this.getClass());
22+
23+
private UserDetailsService userDetailsService;
24+
private JWTUtil jwtUtil;
25+
private String tokenHeader;
26+
27+
public JWTTokenFilter(UserDetailsService userDetailsService, JWTUtil jwtUtil, String tokenHeader) {
28+
this.userDetailsService = userDetailsService;
29+
this.jwtUtil = jwtUtil;
30+
this.tokenHeader = tokenHeader;
31+
}
32+
33+
@Override
34+
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
35+
authorizeRequest(request);
36+
chain.doFilter(request, response);
37+
}
38+
39+
private void authorizeRequest(HttpServletRequest request) {
40+
logger.debug("Processing authentication for '{}'", request.getRequestURL());
41+
42+
final String requestHeader = request.getHeader(this.tokenHeader);
43+
44+
if (requestHeader == null || !requestHeader.startsWith("Bearer ")) {
45+
logger.warn("Authorization failed. No JWT token found");
46+
return;
47+
}
48+
49+
String username;
50+
String authToken = requestHeader.substring(7);
51+
52+
try {
53+
username = jwtUtil.getUsernameFromToken(authToken);
54+
} catch (IllegalArgumentException e) {
55+
logger.error("Error during getting username from token", e);
56+
return;
57+
} catch (ExpiredJwtException e) {
58+
logger.warn("The token has expired", e);
59+
return;
60+
}
61+
62+
if (username == null || SecurityContextHolder.getContext().getAuthentication() != null) return;
63+
64+
logger.debug("Security context was null, so authorizing user '{}'...", username);
65+
66+
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
67+
68+
if (!jwtUtil.validateToken(authToken, userDetails)) {
69+
logger.error("Not a valid token!!!");
70+
return;
71+
}
72+
73+
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
74+
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
75+
logger.info("Authorized user '{}', setting security context...", username);
76+
SecurityContextHolder.getContext().setAuthentication(authentication);
77+
}
78+
}

src/main/java/com/kvark900/api/configuration/security/JwtTokenUtil.java renamed to src/main/java/com/kvark900/api/configuration/security/JWTUtil.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import java.util.function.Function;
1717

1818
@Component
19-
public class JwtTokenUtil implements Serializable {
19+
public class JWTUtil implements Serializable {
2020

2121
static final String CLAIM_KEY_USERNAME = "sub";
2222
static final String CLAIM_KEY_CREATED = "iat";

src/main/java/com/kvark900/api/configuration/security/JwtAuthenticationEntryPoint.java

Lines changed: 0 additions & 25 deletions
This file was deleted.

0 commit comments

Comments
 (0)