Skip to content

Commit

Permalink
create new file src/main/java/ndt/java/spring/controller/PermitAllCon…
Browse files Browse the repository at this point in the history
…troller.java

modified:
	+ src/main/java/ndt/java/spring/config/WebSecurityConfig.java:
	  add white list url or uri
	+ src/main/java/ndt/java/spring/controller/AuthenAPI.java: add
	  comment to note and explain code
	+ src/main/java/ndt/java/spring/utils/JwtTokenUtil.java: add
	  methods validateAccessToken, getSubject, parseClaims
  • Loading branch information
dinhthien2000 committed Oct 31, 2023
1 parent 6ff9415 commit a033d27
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 19 deletions.
7 changes: 5 additions & 2 deletions src/main/java/ndt/java/spring/config/WebSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,18 @@
@RequiredArgsConstructor
public class WebSecurityConfig {

static String[] LIST_MATCHER ={"/*","/auth/signup","/auth/login"};
static String[] LIST_MATCHER ={"/","/auth/signup","/auth/login","/hello","/index"};

final UserRepository repository;

@Bean
/*Because we don’t use classic web so disable CSRF and no session management needed*/
public SecurityFilterChain securityFilterChain (HttpSecurity http) throws Exception {
return http.csrf(c->c.disable())
.authorizeHttpRequests(auth->auth.requestMatchers(LIST_MATCHER).permitAll())
.authorizeHttpRequests(
auth->auth.requestMatchers(LIST_MATCHER).permitAll()
.anyRequest().authenticated()
)
.sessionManagement(t -> t.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/ndt/java/spring/controller/AuthenAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,11 @@ public class AuthenAPI {
@PostMapping("/auth/login")
public ResponseEntity<?> login(@RequestBody @Valid AuthenRequest request) {
try {
// Create Authentication object ( gồm Object principal (username), Object credentials (passwrord))
// from request and with username and password
Authentication authencation = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
User user = (User) authencation.getPrincipal();
User user = (User) authencation.getPrincipal(); // authentication request with username and password
System.out.println(ColorSysoutUtil.GREEN_BOLD + user.toString() + ColorSysoutUtil.RESET);
String accessToken = jwtUtil.generateAccessToken(user);
System.out.println(accessToken);
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/ndt/java/spring/controller/PermitAllController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ndt.java.spring.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = {"/","/hello","/index"})
public class PermitAllController {

@GetMapping
public String index() {
return " Welcome to website ahihi ^^ ";
}
}
73 changes: 57 additions & 16 deletions src/main/java/ndt/java/spring/utils/JwtTokenUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

Expand All @@ -16,26 +18,65 @@

@Component
public class JwtTokenUtil {
private final static long EXPIRE_DURATION = 24*60*60*1000; // The token should expire after 24 hours

private final static long EXPIRE_DURATION = 24 * 60 * 60 * 1000; // The token should expire after 24 hours

@Value("${app.jwt.secret}") // specify in the application.properties file
private String SECRET_KEY;

private Key key() {
return Keys.hmacShaKeyFor(this.SECRET_KEY.getBytes(StandardCharsets.UTF_8));
}



private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

private Key key() {
return Keys.hmacShaKeyFor(this.SECRET_KEY.getBytes(StandardCharsets.UTF_8));
}

// JJwt need Key object to set signWith method
public String generateAccessToken(User user) {
Map<String, Object> claims = new HashMap<>();
return Jwts.builder()
.setClaims(claims)
.setSubject(String.format("%s,%s", user.getId(), user.getEmail()))
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE_DURATION))
.signWith(key(),SignatureAlgorithm.HS512)
.compact();
return Jwts.builder().setClaims(claims).setSubject(String.format("%s,%s", user.getId(), user.getEmail()))
.setIssuer("NdtJava").setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRE_DURATION))
.signWith(key(), SignatureAlgorithm.HS512).compact();
}

/*
* validateAccessToken(): used to verify a given JWT. It returns true if the JWT is verified, or false otherwise.
* getSubject(): gets the value of the subject field of a given token. The subject contains User ID and email, which will be used to recreate a User object
*
* */

public boolean validateAccessToken(String token) {
try {
// validate jwt with secret key and build and confident (tin tưởng)jwt content
// compact has been cryptographically signed.
Jwts.parserBuilder().setSigningKey(key()).build().parseClaimsJws(token);
return true;
} catch (ExpiredJwtException ex) {
LOGGER.error("JWT expired", ex.getMessage());
} catch (IllegalArgumentException ex) {
LOGGER.error("Token is null, empty or only whitespace", ex.getMessage());
} catch (MalformedJwtException ex) {
LOGGER.error("JWT is invalid", ex);
} catch (UnsupportedJwtException ex) {
LOGGER.error("JWT is not supported", ex);
} catch (SignatureException ex) {
LOGGER.error("Signature validation failed");
}
return false;
}

public String getSubject(String token) {
return parseClaims(token).getSubject();
}

public Claims parseClaims(String token) {
// Jwt set singinKey để chuyển đổi từ mã token sang dạng token json (header, payload, signing), sau khi đã chuyển sang json ta có thể get header, body (payload), singing
// string token -> json jwt -> getHeader, getBody (payload), getSigningKey
return Jwts.parserBuilder()
.setSigningKey(key())
.build()
.parseClaimsJws(token)
.getBody();
}

}

0 comments on commit a033d27

Please sign in to comment.