Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

some server Refactorings and tests with reactive webclient for learning #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<version>3.1.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
<java.version>17</java.version>
<io.jsonwebtoken.version>0.11.2</io.jsonwebtoken.version>
</properties>

Expand Down Expand Up @@ -62,11 +62,21 @@
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
package com.ard333.springbootwebfluxjjwt.rest;

import com.ard333.springbootwebfluxjjwt.model.Message;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ard333.springbootwebfluxjjwt.model.Message;

import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/resource")
public class ResourceREST {

@GetMapping("/resource/user")
@GetMapping("/user")
@PreAuthorize("hasRole('USER')")
public Mono<ResponseEntity<Message>> user() {
return Mono.just(ResponseEntity.ok(new Message("Content for user")));
}

@GetMapping("/resource/admin")
@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public Mono<ResponseEntity<Message>> admin() {
return Mono.just(ResponseEntity.ok(new Message("Content for admin")));
}

@GetMapping("/resource/user-or-admin")
@GetMapping("/user-or-admin")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public Mono<ResponseEntity<Message>> userOrAdmin() {
return Mono.just(ResponseEntity.ok(new Message("Content for user or admin")));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
package com.ard333.springbootwebfluxjjwt.security;

import com.ard333.springbootwebfluxjjwt.model.User;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.ard333.springbootwebfluxjjwt.model.User;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;

@Component
public class JWTUtil {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.ard333.springbootwebfluxjjwt.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
Expand All @@ -14,6 +15,7 @@
@AllArgsConstructor
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
@Configuration
public class WebSecurityConfig {

private AuthenticationManager authenticationManager;
Expand All @@ -22,21 +24,20 @@ public class WebSecurityConfig {
@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
return http
.exceptionHandling()
.authenticationEntryPoint((swe, e) ->
Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED))
).accessDeniedHandler((swe, e) ->
Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN))
).and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.exceptionHandling(handling -> handling
.authenticationEntryPoint((swe, e) ->
Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED))
).accessDeniedHandler((swe, e) ->
Mono.fromRunnable(() -> swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN))
))
.csrf(csrf -> csrf.disable())
.formLogin(formLogin -> formLogin.disable())
.httpBasic(httpBasic -> httpBasic.disable())
.authenticationManager(authenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.pathMatchers("/login").permitAll()
.anyExchange().authenticated()
.and().build();
.authorizeExchange(exchange -> exchange
.pathMatchers(HttpMethod.OPTIONS).permitAll()
.pathMatchers("/login").permitAll()
.anyExchange().authenticated()).build();
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.ard333.springbootwebfluxjjwt.security.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
Expand All @@ -9,8 +10,12 @@
*
* @author ard333
*/
@Data @NoArgsConstructor @AllArgsConstructor @ToString
public class AuthRequest {
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder(toBuilder = true)
public class AuthRequest {
private String username;
private String password;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package com.ard333.springbootwebfluxjjwt.service;

import com.ard333.springbootwebfluxjjwt.model.User;
import com.ard333.springbootwebfluxjjwt.model.security.Role;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.ard333.springbootwebfluxjjwt.model.User;
import com.ard333.springbootwebfluxjjwt.model.security.Role;

import jakarta.annotation.PostConstruct;
import reactor.core.publisher.Mono;

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"properties": [
{
"name": "springbootwebfluxjjwt.password.encoder.secret",
"type": "java.lang.String",
"description": "Encoder secret"
},
{
"name": "springbootwebfluxjjwt.password.encoder.iteration",
"type": "java.lang.Integer",
"description": "Iteration numbers for generating the key"
},
{
"name": "springbootwebfluxjjwt.password.encoder.keylength",
"type": "java.lang.Integer",
"description": "The key length'"
},
{
"name": "springbootwebfluxjjwt.jjwt.secret",
"type": "java.lang.String",
"description": "This is secret for JWTHS512 signature algorithm that MUST have 64 byte length"
},
{
"name": "springbootwebfluxjjwt.jjwt.expiration",
"type": "java.lang.String",
"description": "Expiration time for token in seconds"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.ard333.springbootwebfluxjjwt;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.ard333.springbootwebfluxjjwt.rest.AuthenticationREST;
import com.ard333.springbootwebfluxjjwt.rest.ResourceREST;

@SpringBootTest
class SpringBootWebfluxJjwtApplicationTest {

@Autowired
AuthenticationREST authenticationREST;

@Autowired
ResourceREST resourceREST;

@Test
void contextLoads() {
Assertions.assertThat(authenticationREST).isNotNull();
Assertions.assertThat(resourceREST).isNotNull();
}

}
55 changes: 55 additions & 0 deletions src/test/java/com/ard333/springbootwebfluxjjwt/rest/LoginTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.ard333.springbootwebfluxjjwt.rest;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatusCode;

import com.ard333.springbootwebfluxjjwt.model.security.AuthResponse;
import com.ard333.springbootwebfluxjjwt.security.model.AuthRequest;
import com.ard333.springbootwebfluxjjwt.utils.BaseRestTest;

public class LoginTest extends BaseRestTest {

@Test
public void whenLoginWithBadPassword_shouldRespondWith4xx() {

webClient()
.post()
.uri("/login")
.bodyValue(AuthRequest.builder()
.username("user")
.password("wrong")
.build())
.exchangeToMono(res -> {
assertThat(res.statusCode()).isEqualTo(HttpStatusCode.valueOf(401));
return res.bodyToMono(AuthRequest.class);
})
.doOnError(e -> Assertions.fail("should not throw", e))
.block();

}

@Test
public void whenLoginWithUser_shouldRespondWith2xx() {
webClient()
.post()
.uri("/login")
.bodyValue(AuthRequest.builder()
.username("user")
.password("user")
.build())
.exchangeToMono(res -> {

assertThat(res.statusCode().is2xxSuccessful()).isTrue();
return res.bodyToMono(AuthResponse.class);

})
.doOnError(e -> Assertions.fail("should not throw", e))
.doOnSuccess(authRes -> {
assertThat(authRes.getToken()).isNotEmpty();
})
.block();
}
}
Loading