Skip to content

Commit 766d6ae

Browse files
committed
1.Unify the json process lib to jackson.
2.Use jackson lib to process the yaml file. 3.Add security feature. Password will be encoded using Bcrypt in Spring Security and store user info in yml format. 4.Make security check parameters configurable. 5.Add CommonUitls to offer some common functions such as BcryptEncoder, yamlParse, getProjectRootFolder,etc.
1 parent 3c384d3 commit 766d6ae

File tree

16 files changed

+432
-164
lines changed

16 files changed

+432
-164
lines changed

docs/index.pdf

0 Bytes
Binary file not shown.

pom.xml

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,17 @@
210210
<artifactId>jackson-databind</artifactId>
211211
<version>${jackson.version}</version>
212212
</dependency>
213+
<!-- convert Java 8 date and time classes to JSON representation using the @JsonFormat annotation-->
214+
<dependency>
215+
<groupId>com.fasterxml.jackson.datatype</groupId>
216+
<artifactId>jackson-datatype-jsr310</artifactId>
217+
</dependency>
218+
<dependency>
219+
<groupId>com.fasterxml.jackson.dataformat</groupId>
220+
<artifactId>jackson-dataformat-yaml</artifactId>
221+
<version>${jackson.version}</version>
222+
</dependency>
223+
213224
<dependency>
214225
<groupId>org.apache.commons</groupId>
215226
<artifactId>commons-collections4</artifactId>
@@ -238,22 +249,6 @@
238249
<artifactId>curator-framework</artifactId>
239250
<version>2.11.0</version>
240251
</dependency>
241-
<!-- convert Java 8 date and time classes to JSON representation using the @JsonFormat annotation-->
242-
<dependency>
243-
<groupId>com.fasterxml.jackson.datatype</groupId>
244-
<artifactId>jackson-datatype-jsr310</artifactId>
245-
</dependency>
246-
<dependency>
247-
<groupId>org.yaml</groupId>
248-
<artifactId>snakeyaml</artifactId>
249-
<version>${snakeyaml.version}</version>
250-
</dependency>
251-
<dependency>
252-
<groupId>net.sf.json-lib</groupId>
253-
<artifactId>json-lib</artifactId>
254-
<version>2.4</version>
255-
<classifier>jdk15</classifier>
256-
</dependency>
257252
</dependencies>
258253

259254
<build>

security/security.yml

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
test4:
3+
password: "$2a$10$M9g/YgjQUuEH05RZklnm3u1JWoyRApv/Bfxwe0EiOFMKl2ghQvDK2"
4+
role: "user"
5+
test2:
6+
password: "$2a$10$xUisqGbg1lC.F62bwAZ0KuIJ/ltIg.0erANK1rz/gi1qVbRzkb.KC"
7+
role: "user"
8+
test3:
9+
password: "$2a$10$5L.EQBqNKBPLsbflg3mYUuZGmH7jh6IUjB6nyecLPo1rGKLu5LXAW"
10+
role: "user"
11+
test:
12+
password: "$2a$10$tXq/tF9d5COfuRbS0eyfdOrsgv2mn.xhKT3TdWY8007dsIEhDpItS"
13+
role: "user"
14+
admin:
15+
password: "$2a$10$cwkLeAFbPSNWEvjnL.w2FeoEPIv.MMEb0Pk541TiuqGRHP.x8ReoK"
16+
role: "admin"
17+
test1:
18+
password: "$2a$10$knZ1h7KIDJeJuJdpmspt9utL.UajESzTlox7X/DFA4YcINbb3TFdC"
19+
role: "user"
20+
tina:
21+
password: "$2a$10$e6UbRpWtOP43A/QCOmNCGuJ3BN9OoToiF0HAiZgMW3ktnzvQkjQfC"
22+
role: "string"

security/securityFile.txt

Lines changed: 0 additions & 2 deletions
This file was deleted.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
package org.gnuhpc.bigdata.config;
22

3+
import org.gnuhpc.bigdata.utils.CommonUtils;
4+
5+
import java.io.File;
6+
37
public class JMXConfig {
48
public static final String JMX_WAIT_TIMEOUT = "jmx.wait_timeout";
59
public static final String JMX_FETCH_TIMEOUT = "jmx.fetch_timeout";
610
public static final String RMI_CONNECT_TIMEOUT = "rmi.connect_timeout";
711
public static final String RMI_HANDSHAKE_TIMEOUT = "rmi.handshake_timeout";
812
public static final String RMI_RESPONSE_TIMEOUT = "rmi.response_timeout";
913
public static final String JMX_PROTOCOL = "service:jmx:rmi:///jndi/rmi://";
14+
public static final String JMX_FILTER_DIR = CommonUtils.PROJECT_ROOT_FOLDER + File.separator + "JMXFilterTemplate";
1015
}

src/main/java/org/gnuhpc/bigdata/config/WebSecurityConfig.java

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package org.gnuhpc.bigdata.config;
22

3-
import org.gnuhpc.bigdata.service.UserDetailsServiceImp;
3+
import org.gnuhpc.bigdata.security.BasicAuthenticationPoint;
4+
import org.gnuhpc.bigdata.security.UserDetailsServiceImp;
5+
import org.gnuhpc.bigdata.utils.CommonUtils;
46
import org.springframework.beans.factory.annotation.Autowired;
57
import org.springframework.beans.factory.annotation.Value;
68
import org.springframework.context.annotation.Bean;
9+
import org.springframework.context.annotation.Configuration;
710
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
811
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
912
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@@ -12,28 +15,38 @@
1215
import org.springframework.security.core.userdetails.UserDetailsService;
1316
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
1417

18+
import java.io.File;
19+
20+
@Configuration
1521
@EnableWebSecurity
1622
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
23+
public static final String SECURITY_FILE_PATH = CommonUtils.PROJECT_ROOT_FOLDER + File.separator +
24+
"security" + File.separator + "security.yml";
25+
1726
@Autowired
1827
private BasicAuthenticationPoint basicAuthenticationPoint;
1928

29+
@Value("${server.security.check}")
30+
private boolean securityCheck;
31+
@Value("${server.security.checkInitDelay}")
32+
private int checkInitDelay;
33+
@Value("${server.security.checkSecurityInterval}")
34+
private int checkSecurityInterval;
35+
2036
@Bean
2137
public UserDetailsService userDetailsService() {
22-
return new UserDetailsServiceImp();
38+
return new UserDetailsServiceImp(securityCheck, checkInitDelay, checkSecurityInterval);
2339
};
2440

2541
@Bean
2642
public BCryptPasswordEncoder passwordEncoder() {
2743
return new BCryptPasswordEncoder();
2844
};
2945

30-
@Value("${server.security}")
31-
private boolean security;
32-
3346
@Override
3447
protected void configure(HttpSecurity http) throws Exception {
3548
http.csrf().disable();
36-
if (security) {
49+
if (securityCheck) {
3750
http.authorizeRequests().antMatchers("/api", "/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/v2/**").permitAll()
3851
.anyRequest().authenticated();
3952
http.httpBasic().authenticationEntryPoint(basicAuthenticationPoint);
@@ -48,4 +61,8 @@ protected void configure(HttpSecurity http) throws Exception {
4861
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
4962
auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
5063
}
64+
65+
public static void main(String[] args) {
66+
System.out.println(new BCryptPasswordEncoder().encode("admin1234"));
67+
}
5168
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package org.gnuhpc.bigdata.controller;
2+
3+
import io.swagger.annotations.Api;
4+
import io.swagger.annotations.ApiOperation;
5+
import lombok.extern.log4j.Log4j;
6+
import org.gnuhpc.bigdata.constant.GeneralResponseState;
7+
import org.gnuhpc.bigdata.model.GeneralResponse;
8+
import org.gnuhpc.bigdata.model.User;
9+
import org.gnuhpc.bigdata.service.UserService;
10+
import org.springframework.beans.factory.annotation.Autowired;
11+
import org.springframework.validation.BindingResult;
12+
import org.springframework.web.bind.annotation.*;
13+
14+
import javax.validation.Valid;
15+
import java.util.List;
16+
17+
@Log4j
18+
@RestController
19+
@Api(value = "/users", description = "Security User Management Controller.")
20+
public class UserController {
21+
@Autowired
22+
private UserService userService;
23+
24+
@GetMapping("/users")
25+
@ApiOperation(value = "Get user list.")
26+
public List<String> listUser() {
27+
return userService.listUser();
28+
}
29+
30+
@PostMapping("/users")
31+
@ApiOperation(value = "Add user.")
32+
public GeneralResponse addUser(@RequestBody@Valid User user, BindingResult results) {
33+
if (results.hasErrors()) {
34+
return new GeneralResponse(GeneralResponseState.failure, results.getFieldError().getDefaultMessage());
35+
}
36+
log.info("Receive add user request: username:" + user.getUsername());
37+
return userService.addUser(user);
38+
}
39+
40+
@PutMapping("/users")
41+
@ApiOperation(value = "Modify user information.")
42+
public GeneralResponse modifyUser(@RequestBody@Valid User user, BindingResult results) {
43+
if (results.hasErrors()) {
44+
return new GeneralResponse(GeneralResponseState.failure, results.getFieldError().getDefaultMessage());
45+
}
46+
log.info("Receive modify user request: username:" + user.getUsername());
47+
return userService.modifyUser(user);
48+
}
49+
50+
@DeleteMapping("/users/{username}")
51+
@ApiOperation(value = "Delete user.")
52+
public GeneralResponse delUser(@PathVariable String username) {
53+
log.info("Receive delete user request: username:" + username);
54+
return userService.delUser(username);
55+
}
56+
}

src/main/java/org/gnuhpc/bigdata/exception/RestErrorResponse.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ public class RestErrorResponse {
3030
private List<RestSubError> subErrorList;
3131

3232
public RestErrorResponse() {
33+
//this.timestamp = new Date();
3334
this.timestamp = LocalDateTime.now();
3435
}
3536

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,26 @@
11
package org.gnuhpc.bigdata.model;
22

3+
import lombok.AllArgsConstructor;
34
import lombok.Getter;
45
import lombok.Setter;
6+
import org.hibernate.validator.constraints.NotBlank;
7+
import org.hibernate.validator.constraints.NotEmpty;
8+
9+
import javax.validation.constraints.NotNull;
510

611
@Getter
712
@Setter
13+
@AllArgsConstructor
814
public class User {
15+
@NotNull(message = "Username can not be null.")
16+
@NotBlank(message = "Username can not be blank.")
917
private String username;
18+
19+
@NotNull(message = "Password can not be null.")
20+
@NotBlank(message = "Password can not be blank.")
1021
private String password;
11-
private String role;
1222

13-
public User(String username, String password, String role) {
14-
this.username = username;
15-
this.password = password;
16-
this.role = role;
17-
}
23+
@NotNull(message = "Role can not be null.")
24+
@NotBlank(message = "Role can not be blank.")
25+
private String role;
1826
}

src/main/java/org/gnuhpc/bigdata/config/BasicAuthenticationPoint.java renamed to src/main/java/org/gnuhpc/bigdata/security/BasicAuthenticationPoint.java

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
1-
package org.gnuhpc.bigdata.config;
1+
package org.gnuhpc.bigdata.security;
22

3-
import net.sf.json.JSONObject;
4-
import net.sf.json.JsonConfig;
5-
import net.sf.json.processors.JsonValueProcessor;
3+
import com.fasterxml.jackson.core.JsonGenerator;
4+
import com.fasterxml.jackson.databind.JsonSerializer;
5+
import com.fasterxml.jackson.databind.ObjectMapper;
6+
import com.fasterxml.jackson.databind.SerializerProvider;
7+
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
8+
import lombok.NoArgsConstructor;
69
import org.gnuhpc.bigdata.exception.RestErrorResponse;
10+
import org.springframework.boot.jackson.JsonComponent;
711
import org.springframework.http.HttpStatus;
812
import org.springframework.security.core.AuthenticationException;
913
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
@@ -25,29 +29,25 @@ public void commence(HttpServletRequest request, HttpServletResponse response, A
2529
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
2630
String error = "Authenciation Error:" + authEx.getClass().getCanonicalName();
2731
RestErrorResponse restAuthenticationError = new RestErrorResponse(HttpStatus.UNAUTHORIZED, error, authEx);
28-
/**
29-
* Translate field LocalDateTime to uniform the response format.
30-
*/
31-
JsonConfig jsonConfig = new JsonConfig();
32-
jsonConfig.registerJsonValueProcessor(LocalDateTime.class, new JsonValueProcessor() {
33-
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
34-
@Override
35-
public Object processObjectValue(String propertyName, Object date,JsonConfig config) {
36-
return df.format((LocalDateTime)date);
37-
}
38-
39-
@Override
40-
public Object processArrayValue(Object date, JsonConfig config) {
41-
return df.format((LocalDateTime)date);
42-
}
43-
});
44-
45-
response.getWriter().print(JSONObject.fromObject(restAuthenticationError, jsonConfig).toString());
32+
ObjectMapper mapper = new ObjectMapper();
33+
JavaTimeModule javaTimeModule = new JavaTimeModule();
34+
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
35+
mapper.registerModule(javaTimeModule);
36+
response.getWriter().print(mapper.writeValueAsString(restAuthenticationError));
4637
}
4738

4839
@Override
4940
public void afterPropertiesSet() throws Exception {
5041
setRealmName("Contact Big Data Infrastructure Team to get available accounts.");
5142
super.afterPropertiesSet();
5243
}
44+
45+
@JsonComponent
46+
@NoArgsConstructor
47+
private class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
48+
@Override
49+
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider sp) throws IOException{
50+
gen.writeString(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
51+
}
52+
}
5353
}

0 commit comments

Comments
 (0)