Update version and change formating

This commit is contained in:
Ardiansyah
2021-05-27 21:31:30 +07:00
parent 1954cfbdf5
commit f3fd409bdc
17 changed files with 251 additions and 291 deletions

10
pom.xml
View File

@@ -14,7 +14,7 @@
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version> <version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
@@ -22,6 +22,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version> <java.version>11</java.version>
<io.jsonwebtoken.version>0.11.2</io.jsonwebtoken.version>
</properties> </properties>
<dependencies> <dependencies>
@@ -40,18 +41,18 @@
<dependency> <dependency>
<groupId>io.jsonwebtoken</groupId> <groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId> <artifactId>jjwt-api</artifactId>
<version>0.11.1</version> <version>${io.jsonwebtoken.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.jsonwebtoken</groupId> <groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId> <artifactId>jjwt-impl</artifactId>
<version>0.11.1</version> <version>${io.jsonwebtoken.version}</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.jsonwebtoken</groupId> <groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <artifactId>jjwt-jackson</artifactId>
<version>0.11.1</version> <version>${io.jsonwebtoken.version}</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
@@ -87,5 +88,4 @@
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class SpringBootWebfluxJjwtApplication { public class SpringBootWebfluxJjwtApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(SpringBootWebfluxJjwtApplication.class, args); SpringApplication.run(SpringBootWebfluxJjwtApplication.class, args);
} }
} }

View File

@@ -11,7 +11,5 @@ import lombok.ToString;
*/ */
@Data @NoArgsConstructor @AllArgsConstructor @ToString @Data @NoArgsConstructor @AllArgsConstructor @ToString
public class Message { public class Message {
private String content;
private String content;
} }

View File

@@ -21,62 +21,55 @@ import lombok.ToString;
*/ */
@ToString @AllArgsConstructor @NoArgsConstructor @ToString @AllArgsConstructor @NoArgsConstructor
public class User implements UserDetails { public class User implements UserDetails {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
private String username; private String username;
private String password;
private String password; @Getter @Setter
private Boolean enabled;
@Getter @Setter @Getter @Setter
private Boolean enabled; private List<Role> roles;
@Override
@Getter @Setter public String getUsername() {
private List<Role> roles; return username;
}
@Override public void setUsername(String username) {
public String getUsername() { this.username = username;
return username; }
}
public void setUsername(String username) {
this.username = username;
}
@Override @Override
public boolean isAccountNonExpired() { public boolean isAccountNonExpired() {
return false; return false;
} }
@Override @Override
public boolean isAccountNonLocked() { public boolean isAccountNonLocked() {
return false; return false;
} }
@Override @Override
public boolean isCredentialsNonExpired() { public boolean isCredentialsNonExpired() {
return false; return false;
} }
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return this.enabled; return this.enabled;
} }
@Override @Override
public Collection<? extends GrantedAuthority> getAuthorities() { public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(authority -> new SimpleGrantedAuthority(authority.name())).collect(Collectors.toList()); return this.roles.stream().map(authority -> new SimpleGrantedAuthority(authority.name())).collect(Collectors.toList());
} }
@JsonIgnore @JsonIgnore
@Override @Override
public String getPassword() { public String getPassword() {
return password; return password;
} }
@JsonProperty
@JsonProperty public void setPassword(String password) {
public void setPassword(String password) { this.password = password;
this.password = password; }
}
} }

View File

@@ -21,24 +21,23 @@ import reactor.core.publisher.Mono;
@RestController @RestController
public class AuthenticationREST { public class AuthenticationREST {
@Autowired @Autowired
private JWTUtil jwtUtil; private JWTUtil jwtUtil;
@Autowired
@Autowired private PBKDF2Encoder passwordEncoder;
private PBKDF2Encoder passwordEncoder;
@Autowired @Autowired
private UserService userService; private UserService userService;
@RequestMapping(value = "/login", method = RequestMethod.POST) @RequestMapping(value = "/login", method = RequestMethod.POST)
public Mono<ResponseEntity<?>> login(@RequestBody AuthRequest ar) { public Mono<ResponseEntity<?>> login(@RequestBody AuthRequest ar) {
return userService.findByUsername(ar.getUsername()).map((userDetails) -> { return userService.findByUsername(ar.getUsername()).map((userDetails) -> {
if (passwordEncoder.encode(ar.getPassword()).equals(userDetails.getPassword())) { if (passwordEncoder.encode(ar.getPassword()).equals(userDetails.getPassword())) {
return ResponseEntity.ok(new AuthResponse(jwtUtil.generateToken(userDetails))); return ResponseEntity.ok(new AuthResponse(jwtUtil.generateToken(userDetails)));
} else { } else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
} }
}).defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()); }).defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build());
} }
} }

View File

@@ -14,22 +14,19 @@ import reactor.core.publisher.Mono;
*/ */
@RestController @RestController
public class ResourceREST { public class ResourceREST {
@RequestMapping(value = "/resource/user", method = RequestMethod.GET)
@RequestMapping(value = "/resource/user", method = RequestMethod.GET) @PreAuthorize("hasRole('USER')")
@PreAuthorize("hasRole('USER')") public Mono<ResponseEntity<?>> user() {
public Mono<ResponseEntity<?>> user() { return Mono.just(ResponseEntity.ok(new Message("Content for user")));
return Mono.just(ResponseEntity.ok(new Message("Content for user"))); }
} @RequestMapping(value = "/resource/admin", method = RequestMethod.GET)
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "/resource/admin", method = RequestMethod.GET) public Mono<ResponseEntity<?>> admin() {
@PreAuthorize("hasRole('ADMIN')") return Mono.just(ResponseEntity.ok(new Message("Content for admin")));
public Mono<ResponseEntity<?>> admin() { }
return Mono.just(ResponseEntity.ok(new Message("Content for admin"))); @RequestMapping(value = "/resource/user-or-admin", method = RequestMethod.GET)
} @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public Mono<ResponseEntity<?>> userOrAdmin() {
@RequestMapping(value = "/resource/user-or-admin", method = RequestMethod.GET) return Mono.just(ResponseEntity.ok(new Message("Content for user or admin")));
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')") }
public Mono<ResponseEntity<?>> userOrAdmin() {
return Mono.just(ResponseEntity.ok(new Message("Content for user or admin")));
}
} }

View File

@@ -19,28 +19,26 @@ import java.util.List;
@Component @Component
public class AuthenticationManager implements ReactiveAuthenticationManager { public class AuthenticationManager implements ReactiveAuthenticationManager {
@Autowired @Autowired
private JWTUtil jwtUtil; private JWTUtil jwtUtil;
@Override
@Override @SuppressWarnings("unchecked")
@SuppressWarnings("unchecked") public Mono<Authentication> authenticate(Authentication authentication) {
public Mono<Authentication> authenticate(Authentication authentication) { String authToken = authentication.getCredentials().toString();
String authToken = authentication.getCredentials().toString(); try {
String username = jwtUtil.getUsernameFromToken(authToken);
try { if (!jwtUtil.validateToken(authToken)) {
String username = jwtUtil.getUsernameFromToken(authToken); return Mono.empty();
if (!jwtUtil.validateToken(authToken)) { }
return Mono.empty(); Claims claims = jwtUtil.getAllClaimsFromToken(authToken);
} List<String> rolesMap = claims.get("role", List.class);
Claims claims = jwtUtil.getAllClaimsFromToken(authToken); List<GrantedAuthority> authorities = new ArrayList<>();
List<String> rolesMap = claims.get("role", List.class); for (String rolemap : rolesMap) {
List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(rolemap));
for (String rolemap : rolesMap) { }
authorities.add(new SimpleGrantedAuthority(rolemap)); return Mono.just(new UsernamePasswordAuthenticationToken(username, null, authorities));
} } catch (Exception e) {
return Mono.just(new UsernamePasswordAuthenticationToken(username, null, authorities)); return Mono.empty();
} catch (Exception e) { }
return Mono.empty(); }
}
}
} }

View File

@@ -13,8 +13,8 @@ import org.springframework.web.reactive.config.WebFluxConfigurer;
@EnableWebFlux @EnableWebFlux
public class CORSFilter implements WebFluxConfigurer { public class CORSFilter implements WebFluxConfigurer {
@Override @Override
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*"); registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
} }
} }

View File

@@ -21,60 +21,52 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
public class JWTUtil { public class JWTUtil {
@Value("${springbootwebfluxjjwt.jjwt.secret}")
@Value("${springbootwebfluxjjwt.jjwt.secret}") private String secret;
private String secret; @Value("${springbootwebfluxjjwt.jjwt.expiration}")
private String expirationTime;
@Value("${springbootwebfluxjjwt.jjwt.expiration}")
private String expirationTime;
private Key key; private Key key;
@PostConstruct @PostConstruct
public void init(){ public void init(){
this.key = Keys.hmacShaKeyFor(secret.getBytes()); this.key = Keys.hmacShaKeyFor(secret.getBytes());
} }
public Claims getAllClaimsFromToken(String token) { public Claims getAllClaimsFromToken(String token) {
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody(); return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
} }
public String getUsernameFromToken(String token) {
public String getUsernameFromToken(String token) { return getAllClaimsFromToken(token).getSubject();
return getAllClaimsFromToken(token).getSubject(); }
} public Date getExpirationDateFromToken(String token) {
return getAllClaimsFromToken(token).getExpiration();
public Date getExpirationDateFromToken(String token) { }
return getAllClaimsFromToken(token).getExpiration(); private Boolean isTokenExpired(String token) {
} final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
private Boolean isTokenExpired(String token) { }
final Date expiration = getExpirationDateFromToken(token); public String generateToken(User user) {
return expiration.before(new Date()); Map<String, Object> claims = new HashMap<>();
} claims.put("role", user.getRoles());
return doGenerateToken(claims, user.getUsername());
public String generateToken(User user) { }
Map<String, Object> claims = new HashMap<>();
claims.put("role", user.getRoles());
return doGenerateToken(claims, user.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String username) { private String doGenerateToken(Map<String, Object> claims, String username) {
Long expirationTimeLong = Long.parseLong(expirationTime); //in second Long expirationTimeLong = Long.parseLong(expirationTime); //in second
final Date createdDate = new Date();
final Date createdDate = new Date(); final Date expirationDate = new Date(createdDate.getTime() + expirationTimeLong * 1000);
final Date expirationDate = new Date(createdDate.getTime() + expirationTimeLong * 1000);
return Jwts.builder() return Jwts.builder()
.setClaims(claims) .setClaims(claims)
.setSubject(username) .setSubject(username)
.setIssuedAt(createdDate) .setIssuedAt(createdDate)
.setExpiration(expirationDate) .setExpiration(expirationDate)
.signWith(key) .signWith(key)
.compact(); .compact();
} }
public Boolean validateToken(String token) {
public Boolean validateToken(String token) { return !isTokenExpired(token);
return !isTokenExpired(token); }
}
} }

View File

@@ -15,36 +15,33 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
public class PBKDF2Encoder implements PasswordEncoder{ public class PBKDF2Encoder implements PasswordEncoder{
@Value("${springbootwebfluxjjwt.password.encoder.secret}")
@Value("${springbootwebfluxjjwt.password.encoder.secret}") private String secret;
private String secret;
@Value("${springbootwebfluxjjwt.password.encoder.iteration}") @Value("${springbootwebfluxjjwt.password.encoder.iteration}")
private Integer iteration; private Integer iteration;
@Value("${springbootwebfluxjjwt.password.encoder.keylength}") @Value("${springbootwebfluxjjwt.password.encoder.keylength}")
private Integer keylength; private Integer keylength;
/**
/** * More info (https://www.owasp.org/index.php/Hashing_Java) 404 :(
* More info (https://www.owasp.org/index.php/Hashing_Java) 404 :( * @param cs password
* @param cs password * @return encoded password
* @return encoded password */
*/ @Override
@Override public String encode(CharSequence cs) {
public String encode(CharSequence cs) { try {
try { byte[] result = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
byte[] result = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512") .generateSecret(new PBEKeySpec(cs.toString().toCharArray(), secret.getBytes(), iteration, keylength))
.generateSecret(new PBEKeySpec(cs.toString().toCharArray(), secret.getBytes(), iteration, keylength)) .getEncoded();
.getEncoded(); return Base64.getEncoder().encodeToString(result);
return Base64.getEncoder().encodeToString(result); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { throw new RuntimeException(ex);
throw new RuntimeException(ex); }
} }
}
@Override @Override
public boolean matches(CharSequence cs, String string) { public boolean matches(CharSequence cs, String string) {
return encode(cs).equals(string); return encode(cs).equals(string);
} }
} }

View File

@@ -18,29 +18,27 @@ import reactor.core.publisher.Mono;
*/ */
@Component @Component
public class SecurityContextRepository implements ServerSecurityContextRepository{ public class SecurityContextRepository implements ServerSecurityContextRepository{
@Autowired
@Autowired private AuthenticationManager authenticationManager;
private AuthenticationManager authenticationManager;
@Override @Override
public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) { public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) {
throw new UnsupportedOperationException("Not supported yet."); throw new UnsupportedOperationException("Not supported yet.");
} }
@Override @Override
public Mono<SecurityContext> load(ServerWebExchange swe) { public Mono<SecurityContext> load(ServerWebExchange swe) {
ServerHttpRequest request = swe.getRequest(); ServerHttpRequest request = swe.getRequest();
String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (authHeader != null && authHeader.startsWith("Bearer ")) { if (authHeader != null && authHeader.startsWith("Bearer ")) {
String authToken = authHeader.substring(7); String authToken = authHeader.substring(7);
Authentication auth = new UsernamePasswordAuthenticationToken(authToken, authToken); Authentication auth = new UsernamePasswordAuthenticationToken(authToken, authToken);
return this.authenticationManager.authenticate(auth).map((authentication) -> { return this.authenticationManager.authenticate(auth).map((authentication) -> {
return new SecurityContextImpl(authentication); return new SecurityContextImpl(authentication);
}); });
} else { } else {
return Mono.empty(); return Mono.empty();
} }
} }
} }

View File

@@ -19,34 +19,33 @@ import reactor.core.publisher.Mono;
@EnableReactiveMethodSecurity @EnableReactiveMethodSecurity
public class WebSecurityConfig { public class WebSecurityConfig {
@Autowired @Autowired
private AuthenticationManager authenticationManager; private AuthenticationManager authenticationManager;
@Autowired
@Autowired private SecurityContextRepository securityContextRepository;
private SecurityContextRepository securityContextRepository;
@Bean @Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http return http
.exceptionHandling() .exceptionHandling()
.authenticationEntryPoint((swe, e) -> { .authenticationEntryPoint((swe, e) -> {
return Mono.fromRunnable(() -> { return Mono.fromRunnable(() -> {
swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
}); });
}).accessDeniedHandler((swe, e) -> { }).accessDeniedHandler((swe, e) -> {
return Mono.fromRunnable(() -> { return Mono.fromRunnable(() -> {
swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN); swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
}); });
}).and() }).and()
.csrf().disable() .csrf().disable()
.formLogin().disable() .formLogin().disable()
.httpBasic().disable() .httpBasic().disable()
.authenticationManager(authenticationManager) .authenticationManager(authenticationManager)
.securityContextRepository(securityContextRepository) .securityContextRepository(securityContextRepository)
.authorizeExchange() .authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS).permitAll() .pathMatchers(HttpMethod.OPTIONS).permitAll()
.pathMatchers("/login").permitAll() .pathMatchers("/login").permitAll()
.anyExchange().authenticated() .anyExchange().authenticated()
.and().build(); .and().build();
} }
} }

View File

@@ -11,9 +11,7 @@ import lombok.ToString;
*/ */
@Data @NoArgsConstructor @AllArgsConstructor @ToString @Data @NoArgsConstructor @AllArgsConstructor @ToString
public class AuthRequest { public class AuthRequest {
private String username;
private String username; private String password;
private String password;
} }

View File

@@ -11,7 +11,6 @@ import lombok.ToString;
*/ */
@Data @NoArgsConstructor @AllArgsConstructor @ToString @Data @NoArgsConstructor @AllArgsConstructor @ToString
public class AuthResponse { public class AuthResponse {
private String token;
private String token;
} }

View File

@@ -5,5 +5,5 @@ package com.ard333.springbootwebfluxjjwt.security.model;
* @author ard333 * @author ard333
*/ */
public enum Role { public enum Role {
ROLE_USER, ROLE_ADMIN ROLE_USER, ROLE_ADMIN
} }

View File

@@ -17,28 +17,23 @@ import reactor.core.publisher.Mono;
*/ */
@Service @Service
public class UserService { public class UserService {
// this is just an example, you can load the user from the database from the repository
// this is just an example, you can load the user from the database from the repository
private Map<String, User> data; private Map<String, User> data;
@PostConstruct
@PostConstruct public void init(){
public void init(){ data = new HashMap<>();
data = new HashMap<>(); //username:passwowrd -> user:user
data.put("user", new User("user", "cBrlgyL2GI2GINuLUUwgojITuIufFycpLG4490dhGtY=", true, Arrays.asList(Role.ROLE_USER)));
//username:passwowrd -> user:user
data.put("user", new User("user", "cBrlgyL2GI2GINuLUUwgojITuIufFycpLG4490dhGtY=", true, Arrays.asList(Role.ROLE_USER)));
//username:passwowrd -> admin:admin //username:passwowrd -> admin:admin
data.put("admin", new User("admin", "dQNjUIMorJb8Ubj2+wVGYp6eAeYkdekqAcnYp+aRq5w=", true, Arrays.asList(Role.ROLE_ADMIN))); data.put("admin", new User("admin", "dQNjUIMorJb8Ubj2+wVGYp6eAeYkdekqAcnYp+aRq5w=", true, Arrays.asList(Role.ROLE_ADMIN)));
} }
public Mono<User> findByUsername(String username) {
public Mono<User> findByUsername(String username) { if (data.containsKey(username)) {
if (data.containsKey(username)) { return Mono.just(data.get(username));
return Mono.just(data.get(username)); } else {
} else { return Mono.empty();
return Mono.empty(); }
} }
}
} }

View File

@@ -1,16 +1,13 @@
package id.web.ard.springbootwebfluxjjwt; package id.web.ard.springbootwebfluxjjwt;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
public class SpringBootWebfluxJjwtApplicationTests { class DemoApplicationTests {
@Test @Test
public void contextLoads() { void contextLoads() {
} }
} }