xxxxxxxxxx
<!-- JWT Library -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version> <!-- Use the latest version available -->
</dependency>
xxxxxxxxxx
@Override
public String createToken(UserDto user) {
return Jwts.builder()
.signWith(SignatureAlgorithm.HS512, secret)
.setClaims(buildUserClaims(user))
.setExpiration(getTokenExpirationDate())
.setIssuedAt(new Date())
.compact();
}
@Override
public Jws<Claims> validateJwtToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
}
xxxxxxxxxx
@PostMapping(value = {"/auth"}, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> authenticate(@RequestBody AuthenticationRequest authenticationRequest, HttpServletResponse response) {
Authentication authentication = authenticationService.authenticate(authenticationRequest);
if(authentication != null && authentication.isAuthenticated()) {
JwtTokens tokens = jwtTokenService.createTokens(authentication);
return ResponseEntity.ok().body(tokens);
}
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Authentication failed");
}
xxxxxxxxxx
DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(sa, secretKeySpec);
if (!validator.isValid(tokenWithoutSignature, signature)) {
throw new Exception("Could not verify JWT token integrity!");
}
xxxxxxxxxx
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}