Update version and change formating
This commit is contained in:
10
pom.xml
10
pom.xml
@@ -14,7 +14,7 @@
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.2.6.RELEASE</version>
|
||||
<version>2.5.0</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>11</java.version>
|
||||
<io.jsonwebtoken.version>0.11.2</io.jsonwebtoken.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -40,18 +41,18 @@
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>0.11.1</version>
|
||||
<version>${io.jsonwebtoken.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>0.11.1</version>
|
||||
<version>${io.jsonwebtoken.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>0.11.1</version>
|
||||
<version>${io.jsonwebtoken.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
@@ -87,5 +88,4 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
||||
|
||||
@@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@SpringBootApplication
|
||||
public class SpringBootWebfluxJjwtApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringBootWebfluxJjwtApplication.class, args);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringBootWebfluxJjwtApplication.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,5 @@ import lombok.ToString;
|
||||
*/
|
||||
@Data @NoArgsConstructor @AllArgsConstructor @ToString
|
||||
public class Message {
|
||||
|
||||
private String content;
|
||||
|
||||
private String content;
|
||||
}
|
||||
|
||||
@@ -21,62 +21,55 @@ import lombok.ToString;
|
||||
*/
|
||||
@ToString @AllArgsConstructor @NoArgsConstructor
|
||||
public class User implements UserDetails {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
|
||||
@Getter @Setter
|
||||
private Boolean enabled;
|
||||
|
||||
@Getter @Setter
|
||||
private List<Role> roles;
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
private String username;
|
||||
private String password;
|
||||
@Getter @Setter
|
||||
private Boolean enabled;
|
||||
@Getter @Setter
|
||||
private List<Role> roles;
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return this.roles.stream().map(authority -> new SimpleGrantedAuthority(authority.name())).collect(Collectors.toList());
|
||||
}
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return this.roles.stream().map(authority -> new SimpleGrantedAuthority(authority.name())).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@JsonProperty
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
@JsonIgnore
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
@JsonProperty
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -21,24 +21,23 @@ import reactor.core.publisher.Mono;
|
||||
@RestController
|
||||
public class AuthenticationREST {
|
||||
|
||||
@Autowired
|
||||
private JWTUtil jwtUtil;
|
||||
|
||||
@Autowired
|
||||
private PBKDF2Encoder passwordEncoder;
|
||||
@Autowired
|
||||
private JWTUtil jwtUtil;
|
||||
@Autowired
|
||||
private PBKDF2Encoder passwordEncoder;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@RequestMapping(value = "/login", method = RequestMethod.POST)
|
||||
public Mono<ResponseEntity<?>> login(@RequestBody AuthRequest ar) {
|
||||
return userService.findByUsername(ar.getUsername()).map((userDetails) -> {
|
||||
if (passwordEncoder.encode(ar.getPassword()).equals(userDetails.getPassword())) {
|
||||
return ResponseEntity.ok(new AuthResponse(jwtUtil.generateToken(userDetails)));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
}).defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build());
|
||||
}
|
||||
@RequestMapping(value = "/login", method = RequestMethod.POST)
|
||||
public Mono<ResponseEntity<?>> login(@RequestBody AuthRequest ar) {
|
||||
return userService.findByUsername(ar.getUsername()).map((userDetails) -> {
|
||||
if (passwordEncoder.encode(ar.getPassword()).equals(userDetails.getPassword())) {
|
||||
return ResponseEntity.ok(new AuthResponse(jwtUtil.generateToken(userDetails)));
|
||||
} else {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
}).defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -14,22 +14,19 @@ import reactor.core.publisher.Mono;
|
||||
*/
|
||||
@RestController
|
||||
public class ResourceREST {
|
||||
|
||||
@RequestMapping(value = "/resource/user", method = RequestMethod.GET)
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
public Mono<ResponseEntity<?>> user() {
|
||||
return Mono.just(ResponseEntity.ok(new Message("Content for user")));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/resource/admin", method = RequestMethod.GET)
|
||||
@PreAuthorize("hasRole('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() {
|
||||
return Mono.just(ResponseEntity.ok(new Message("Content for user or admin")));
|
||||
}
|
||||
@RequestMapping(value = "/resource/user", method = RequestMethod.GET)
|
||||
@PreAuthorize("hasRole('USER')")
|
||||
public Mono<ResponseEntity<?>> user() {
|
||||
return Mono.just(ResponseEntity.ok(new Message("Content for user")));
|
||||
}
|
||||
@RequestMapping(value = "/resource/admin", method = RequestMethod.GET)
|
||||
@PreAuthorize("hasRole('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() {
|
||||
return Mono.just(ResponseEntity.ok(new Message("Content for user or admin")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,28 +19,26 @@ import java.util.List;
|
||||
@Component
|
||||
public class AuthenticationManager implements ReactiveAuthenticationManager {
|
||||
|
||||
@Autowired
|
||||
private JWTUtil jwtUtil;
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Mono<Authentication> authenticate(Authentication authentication) {
|
||||
String authToken = authentication.getCredentials().toString();
|
||||
|
||||
try {
|
||||
String username = jwtUtil.getUsernameFromToken(authToken);
|
||||
if (!jwtUtil.validateToken(authToken)) {
|
||||
return Mono.empty();
|
||||
}
|
||||
Claims claims = jwtUtil.getAllClaimsFromToken(authToken);
|
||||
List<String> rolesMap = claims.get("role", List.class);
|
||||
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||
for (String rolemap : rolesMap) {
|
||||
authorities.add(new SimpleGrantedAuthority(rolemap));
|
||||
}
|
||||
return Mono.just(new UsernamePasswordAuthenticationToken(username, null, authorities));
|
||||
} catch (Exception e) {
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
@Autowired
|
||||
private JWTUtil jwtUtil;
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Mono<Authentication> authenticate(Authentication authentication) {
|
||||
String authToken = authentication.getCredentials().toString();
|
||||
try {
|
||||
String username = jwtUtil.getUsernameFromToken(authToken);
|
||||
if (!jwtUtil.validateToken(authToken)) {
|
||||
return Mono.empty();
|
||||
}
|
||||
Claims claims = jwtUtil.getAllClaimsFromToken(authToken);
|
||||
List<String> rolesMap = claims.get("role", List.class);
|
||||
List<GrantedAuthority> authorities = new ArrayList<>();
|
||||
for (String rolemap : rolesMap) {
|
||||
authorities.add(new SimpleGrantedAuthority(rolemap));
|
||||
}
|
||||
return Mono.just(new UsernamePasswordAuthenticationToken(username, null, authorities));
|
||||
} catch (Exception e) {
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ import org.springframework.web.reactive.config.WebFluxConfigurer;
|
||||
@EnableWebFlux
|
||||
public class CORSFilter implements WebFluxConfigurer {
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
|
||||
}
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
|
||||
}
|
||||
}
|
||||
@@ -21,60 +21,52 @@ import org.springframework.stereotype.Component;
|
||||
*/
|
||||
@Component
|
||||
public class JWTUtil {
|
||||
|
||||
@Value("${springbootwebfluxjjwt.jjwt.secret}")
|
||||
private String secret;
|
||||
|
||||
@Value("${springbootwebfluxjjwt.jjwt.expiration}")
|
||||
private String expirationTime;
|
||||
@Value("${springbootwebfluxjjwt.jjwt.secret}")
|
||||
private String secret;
|
||||
@Value("${springbootwebfluxjjwt.jjwt.expiration}")
|
||||
private String expirationTime;
|
||||
|
||||
private Key key;
|
||||
private Key key;
|
||||
|
||||
@PostConstruct
|
||||
public void init(){
|
||||
this.key = Keys.hmacShaKeyFor(secret.getBytes());
|
||||
}
|
||||
@PostConstruct
|
||||
public void init(){
|
||||
this.key = Keys.hmacShaKeyFor(secret.getBytes());
|
||||
}
|
||||
|
||||
public Claims getAllClaimsFromToken(String token) {
|
||||
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
|
||||
}
|
||||
|
||||
public String getUsernameFromToken(String token) {
|
||||
return getAllClaimsFromToken(token).getSubject();
|
||||
}
|
||||
|
||||
public Date getExpirationDateFromToken(String token) {
|
||||
return getAllClaimsFromToken(token).getExpiration();
|
||||
}
|
||||
|
||||
private Boolean isTokenExpired(String token) {
|
||||
final Date expiration = getExpirationDateFromToken(token);
|
||||
return expiration.before(new Date());
|
||||
}
|
||||
|
||||
public String generateToken(User user) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put("role", user.getRoles());
|
||||
return doGenerateToken(claims, user.getUsername());
|
||||
}
|
||||
public Claims getAllClaimsFromToken(String token) {
|
||||
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
|
||||
}
|
||||
public String getUsernameFromToken(String token) {
|
||||
return getAllClaimsFromToken(token).getSubject();
|
||||
}
|
||||
public Date getExpirationDateFromToken(String token) {
|
||||
return getAllClaimsFromToken(token).getExpiration();
|
||||
}
|
||||
private Boolean isTokenExpired(String token) {
|
||||
final Date expiration = getExpirationDateFromToken(token);
|
||||
return expiration.before(new Date());
|
||||
}
|
||||
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) {
|
||||
Long expirationTimeLong = Long.parseLong(expirationTime); //in second
|
||||
|
||||
final Date createdDate = new Date();
|
||||
final Date expirationDate = new Date(createdDate.getTime() + expirationTimeLong * 1000);
|
||||
private String doGenerateToken(Map<String, Object> claims, String username) {
|
||||
Long expirationTimeLong = Long.parseLong(expirationTime); //in second
|
||||
final Date createdDate = new Date();
|
||||
final Date expirationDate = new Date(createdDate.getTime() + expirationTimeLong * 1000);
|
||||
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setSubject(username)
|
||||
.setIssuedAt(createdDate)
|
||||
.setExpiration(expirationDate)
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Boolean validateToken(String token) {
|
||||
return !isTokenExpired(token);
|
||||
}
|
||||
return Jwts.builder()
|
||||
.setClaims(claims)
|
||||
.setSubject(username)
|
||||
.setIssuedAt(createdDate)
|
||||
.setExpiration(expirationDate)
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
public Boolean validateToken(String token) {
|
||||
return !isTokenExpired(token);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,36 +15,33 @@ import org.springframework.stereotype.Component;
|
||||
*/
|
||||
@Component
|
||||
public class PBKDF2Encoder implements PasswordEncoder{
|
||||
|
||||
@Value("${springbootwebfluxjjwt.password.encoder.secret}")
|
||||
private String secret;
|
||||
@Value("${springbootwebfluxjjwt.password.encoder.secret}")
|
||||
private String secret;
|
||||
|
||||
@Value("${springbootwebfluxjjwt.password.encoder.iteration}")
|
||||
private Integer iteration;
|
||||
@Value("${springbootwebfluxjjwt.password.encoder.iteration}")
|
||||
private Integer iteration;
|
||||
|
||||
@Value("${springbootwebfluxjjwt.password.encoder.keylength}")
|
||||
private Integer keylength;
|
||||
|
||||
/**
|
||||
* More info (https://www.owasp.org/index.php/Hashing_Java) 404 :(
|
||||
* @param cs password
|
||||
* @return encoded password
|
||||
*/
|
||||
@Override
|
||||
public String encode(CharSequence cs) {
|
||||
try {
|
||||
byte[] result = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
|
||||
.generateSecret(new PBEKeySpec(cs.toString().toCharArray(), secret.getBytes(), iteration, keylength))
|
||||
.getEncoded();
|
||||
return Base64.getEncoder().encodeToString(result);
|
||||
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
@Value("${springbootwebfluxjjwt.password.encoder.keylength}")
|
||||
private Integer keylength;
|
||||
/**
|
||||
* More info (https://www.owasp.org/index.php/Hashing_Java) 404 :(
|
||||
* @param cs password
|
||||
* @return encoded password
|
||||
*/
|
||||
@Override
|
||||
public String encode(CharSequence cs) {
|
||||
try {
|
||||
byte[] result = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
|
||||
.generateSecret(new PBEKeySpec(cs.toString().toCharArray(), secret.getBytes(), iteration, keylength))
|
||||
.getEncoded();
|
||||
return Base64.getEncoder().encodeToString(result);
|
||||
} catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(CharSequence cs, String string) {
|
||||
return encode(cs).equals(string);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(CharSequence cs, String string) {
|
||||
return encode(cs).equals(string);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,29 +18,27 @@ import reactor.core.publisher.Mono;
|
||||
*/
|
||||
@Component
|
||||
public class SecurityContextRepository implements ServerSecurityContextRepository{
|
||||
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Override
|
||||
public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) {
|
||||
throw new UnsupportedOperationException("Not supported yet.");
|
||||
}
|
||||
@Override
|
||||
public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) {
|
||||
throw new UnsupportedOperationException("Not supported yet.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<SecurityContext> load(ServerWebExchange swe) {
|
||||
ServerHttpRequest request = swe.getRequest();
|
||||
String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
|
||||
@Override
|
||||
public Mono<SecurityContext> load(ServerWebExchange swe) {
|
||||
ServerHttpRequest request = swe.getRequest();
|
||||
String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String authToken = authHeader.substring(7);
|
||||
Authentication auth = new UsernamePasswordAuthenticationToken(authToken, authToken);
|
||||
return this.authenticationManager.authenticate(auth).map((authentication) -> {
|
||||
return new SecurityContextImpl(authentication);
|
||||
});
|
||||
} else {
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String authToken = authHeader.substring(7);
|
||||
Authentication auth = new UsernamePasswordAuthenticationToken(authToken, authToken);
|
||||
return this.authenticationManager.authenticate(auth).map((authentication) -> {
|
||||
return new SecurityContextImpl(authentication);
|
||||
});
|
||||
} else {
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,34 +19,33 @@ import reactor.core.publisher.Mono;
|
||||
@EnableReactiveMethodSecurity
|
||||
public class WebSecurityConfig {
|
||||
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Autowired
|
||||
private SecurityContextRepository securityContextRepository;
|
||||
@Autowired
|
||||
private AuthenticationManager authenticationManager;
|
||||
@Autowired
|
||||
private SecurityContextRepository securityContextRepository;
|
||||
|
||||
@Bean
|
||||
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
|
||||
return http
|
||||
.exceptionHandling()
|
||||
.authenticationEntryPoint((swe, e) -> {
|
||||
return Mono.fromRunnable(() -> {
|
||||
swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
|
||||
});
|
||||
}).accessDeniedHandler((swe, e) -> {
|
||||
return Mono.fromRunnable(() -> {
|
||||
swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
|
||||
});
|
||||
}).and()
|
||||
.csrf().disable()
|
||||
.formLogin().disable()
|
||||
.httpBasic().disable()
|
||||
.authenticationManager(authenticationManager)
|
||||
.securityContextRepository(securityContextRepository)
|
||||
.authorizeExchange()
|
||||
.pathMatchers(HttpMethod.OPTIONS).permitAll()
|
||||
.pathMatchers("/login").permitAll()
|
||||
.anyExchange().authenticated()
|
||||
.and().build();
|
||||
}
|
||||
@Bean
|
||||
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
|
||||
return http
|
||||
.exceptionHandling()
|
||||
.authenticationEntryPoint((swe, e) -> {
|
||||
return Mono.fromRunnable(() -> {
|
||||
swe.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
|
||||
});
|
||||
}).accessDeniedHandler((swe, e) -> {
|
||||
return Mono.fromRunnable(() -> {
|
||||
swe.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
|
||||
});
|
||||
}).and()
|
||||
.csrf().disable()
|
||||
.formLogin().disable()
|
||||
.httpBasic().disable()
|
||||
.authenticationManager(authenticationManager)
|
||||
.securityContextRepository(securityContextRepository)
|
||||
.authorizeExchange()
|
||||
.pathMatchers(HttpMethod.OPTIONS).permitAll()
|
||||
.pathMatchers("/login").permitAll()
|
||||
.anyExchange().authenticated()
|
||||
.and().build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,7 @@ import lombok.ToString;
|
||||
*/
|
||||
@Data @NoArgsConstructor @AllArgsConstructor @ToString
|
||||
public class AuthRequest {
|
||||
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import lombok.ToString;
|
||||
*/
|
||||
@Data @NoArgsConstructor @AllArgsConstructor @ToString
|
||||
public class AuthResponse {
|
||||
|
||||
private String token;
|
||||
private String token;
|
||||
|
||||
}
|
||||
|
||||
@@ -5,5 +5,5 @@ package com.ard333.springbootwebfluxjjwt.security.model;
|
||||
* @author ard333
|
||||
*/
|
||||
public enum Role {
|
||||
ROLE_USER, ROLE_ADMIN
|
||||
ROLE_USER, ROLE_ADMIN
|
||||
}
|
||||
@@ -17,28 +17,23 @@ import reactor.core.publisher.Mono;
|
||||
*/
|
||||
@Service
|
||||
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;
|
||||
|
||||
@PostConstruct
|
||||
public void init(){
|
||||
data = new HashMap<>();
|
||||
|
||||
//username:passwowrd -> user:user
|
||||
data.put("user", new User("user", "cBrlgyL2GI2GINuLUUwgojITuIufFycpLG4490dhGtY=", true, Arrays.asList(Role.ROLE_USER)));
|
||||
private Map<String, User> data;
|
||||
@PostConstruct
|
||||
public void init(){
|
||||
data = new HashMap<>();
|
||||
//username:passwowrd -> user:user
|
||||
data.put("user", new User("user", "cBrlgyL2GI2GINuLUUwgojITuIufFycpLG4490dhGtY=", true, Arrays.asList(Role.ROLE_USER)));
|
||||
|
||||
//username:passwowrd -> admin:admin
|
||||
data.put("admin", new User("admin", "dQNjUIMorJb8Ubj2+wVGYp6eAeYkdekqAcnYp+aRq5w=", true, Arrays.asList(Role.ROLE_ADMIN)));
|
||||
}
|
||||
|
||||
public Mono<User> findByUsername(String username) {
|
||||
if (data.containsKey(username)) {
|
||||
return Mono.just(data.get(username));
|
||||
} else {
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
|
||||
//username:passwowrd -> admin:admin
|
||||
data.put("admin", new User("admin", "dQNjUIMorJb8Ubj2+wVGYp6eAeYkdekqAcnYp+aRq5w=", true, Arrays.asList(Role.ROLE_ADMIN)));
|
||||
}
|
||||
public Mono<User> findByUsername(String username) {
|
||||
if (data.containsKey(username)) {
|
||||
return Mono.just(data.get(username));
|
||||
} else {
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
package id.web.ard.springbootwebfluxjjwt;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
public class SpringBootWebfluxJjwtApplicationTests {
|
||||
class DemoApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() {
|
||||
}
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user