Creating a Spring Security Key for Signing a JWT Token

This commit is contained in:
michaelin007 2024-03-11 17:52:07 +00:00
parent 5eca855e37
commit 1fea1bf611
13 changed files with 218 additions and 137 deletions

View File

@ -1,4 +1,14 @@
package com.baeldung.jwtsignkey; package com.baeldung.jwtsignkey;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@EnableWebMvc
public class SpringJwtApplication { public class SpringJwtApplication {
public static void main(String[] args) {
SpringApplication.run(com.baeldung.jwtsignkey.SpringJwtApplication.class);
}
} }

View File

@ -3,23 +3,25 @@ package com.baeldung.jwtsignkey.controller;
import com.baeldung.jwtsignkey.jwtconfig.JwtUtils; import com.baeldung.jwtsignkey.jwtconfig.JwtUtils;
import com.baeldung.jwtsignkey.model.User; import com.baeldung.jwtsignkey.model.User;
import com.baeldung.jwtsignkey.repository.UserRepository; import com.baeldung.jwtsignkey.repository.UserRepository;
import com.baeldung.jwtsignkey.response.JwtResponse;
import com.baeldung.jwtsignkey.userservice.UserDetailsImpl; import com.baeldung.jwtsignkey.userservice.UserDetailsImpl;
import com.baeldung.request.LoginRequest;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController @RestController
public class JwtAuthController { public class JwtAuthController {
@ -38,8 +40,10 @@ public class JwtAuthController {
@PostMapping("/signup") @PostMapping("/signup")
public ResponseEntity<?> registerUser(@RequestBody User signUpRequest, HttpServletRequest request) throws UnsupportedEncodingException { public ResponseEntity<?> registerUser(@RequestBody User signUpRequest, HttpServletRequest request) throws UnsupportedEncodingException {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
// Create new user's account return ResponseEntity.badRequest()
.body("Error: Username is already taken!");
}
User user = new User(); User user = new User();
user.setUsername(signUpRequest.getUsername()); user.setUsername(signUpRequest.getUsername());
user.setPassword(encoder.encode(signUpRequest.getPassword())); user.setPassword(encoder.encode(signUpRequest.getPassword()));
@ -50,7 +54,7 @@ public class JwtAuthController {
} }
@PostMapping("/signin") @PostMapping("/signin")
public ResponseEntity<?> authenticateUser( @RequestBody LoginRequest loginRequest) { public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
@ -60,11 +64,14 @@ public class JwtAuthController {
String jwt = jwtUtils.generateJwtToken(authentication); String jwt = jwtUtils.generateJwtToken(authentication);
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername()));
return ResponseEntity.ok(
new JwtResponse(jwt, userDetails.getUsername()));
} }
@RequestMapping("/user-dashboard")
@PreAuthorize("isAuthenticated()")
public String dashboard() {
return "My Dashboard";
}
} }

View File

@ -27,22 +27,18 @@ public class AuthTokenFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class); private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
throws ServletException, IOException {
try { try {
String jwt = parseJwt(request); String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) { if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
String username = jwtUtils.getUserNameFromJwtToken(jwt); String username = jwtUtils.getUserNameFromJwtToken(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(username); UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext()
.setAuthentication(authentication);
} }
} catch (Exception e) { } catch (Exception e) {
logger.error("Cannot set user authentication: {}", e); logger.error("Cannot set user authentication: {}", e);

View File

@ -1,8 +1,13 @@
package com.baeldung.jwtsignkey.jwtconfig; package com.baeldung.jwtsignkey.jwtconfig;
import com.baeldung.jwtsignkey.userservice.UserDetailsImpl; import com.baeldung.jwtsignkey.userservice.UserDetailsImpl;
import io.jsonwebtoken.*;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.Keys; import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -28,9 +33,9 @@ public class JwtUtils {
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
return Jwts.builder() return Jwts.builder()
.setSubject((userPrincipal.getUsername())) .subject((userPrincipal.getUsername()))
.setIssuedAt(new Date()) .issuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)) .expiration(new Date((new Date()).getTime() + jwtExpirationMs))
.signWith(getSigningKey()) .signWith(getSigningKey())
.compact(); .compact();
@ -42,14 +47,21 @@ public class JwtUtils {
} }
public String getUserNameFromJwtToken(String token) { public String getUserNameFromJwtToken(String token) {
//return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject(); return Jwts.parser()
return Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody().getSubject(); .setSigningKey(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();
} }
public boolean validateJwtToken(String authToken) { public boolean validateJwtToken(String authToken) {
try { try {
Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(authToken); Jwts.parser()
.setSigningKey(getSigningKey())
.build()
.parseSignedClaims(authToken);
return true; return true;
} catch (SignatureException e) { } catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage()); logger.error("Invalid JWT signature: {}", e.getMessage());

View File

@ -7,6 +7,8 @@ import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> { public interface UserRepository extends JpaRepository<User, Long> {
Boolean existsByUsername(String username);
Optional<User> findByUsername(String username); Optional<User> findByUsername(String username);
} }

View File

@ -1,4 +1,4 @@
package com.baeldung.jwtsignkey; package com.baeldung.jwtsignkey.response;
public class JwtResponse { public class JwtResponse {
private String token; private String token;
@ -6,7 +6,6 @@ public class JwtResponse {
private String username; private String username;
public JwtResponse(String accessToken, String username) { public JwtResponse(String accessToken, String username) {
this.token = accessToken; this.token = accessToken;
this.username = username; this.username = username;

View File

@ -3,6 +3,7 @@ package com.baeldung.jwtsignkey.securityconfig;
import com.baeldung.jwtsignkey.jwtconfig.AuthEntryPointJwt; import com.baeldung.jwtsignkey.jwtconfig.AuthEntryPointJwt;
import com.baeldung.jwtsignkey.jwtconfig.AuthTokenFilter; import com.baeldung.jwtsignkey.jwtconfig.AuthTokenFilter;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
@ -17,6 +18,8 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS;
@ -30,16 +33,13 @@ public class SecurityConfiguration {
@Autowired @Autowired
private AuthEntryPointJwt unauthorizedHandler; private AuthEntryPointJwt unauthorizedHandler;
private static final String[] WHITE_LIST_URL = { "/signin", "/signup" private static final String[] WHITE_LIST_URL = { "/h2-console/**","/signin", "/signup", "/user-dashboard" };
};
@Bean @Bean
public AuthTokenFilter authenticationJwtTokenFilter() { public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter(); return new AuthTokenFilter();
} }
@Bean @Bean
public DaoAuthenticationProvider authenticationProvider() { public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
@ -61,14 +61,14 @@ public class SecurityConfiguration {
} }
@Bean @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
http.csrf(AbstractHttpConfigurer::disable) http.csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable) .cors(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL) .authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL)
.permitAll() .permitAll()
.anyRequest() .anyRequest()
.authenticated()) .authenticated())
.exceptionHandling( ex -> ex.authenticationEntryPoint(unauthorizedHandler)) .exceptionHandling(ex -> ex.authenticationEntryPoint(unauthorizedHandler))
.sessionManagement(session -> session.sessionCreationPolicy(STATELESS)) .sessionManagement(session -> session.sessionCreationPolicy(STATELESS))
.authenticationProvider(authenticationProvider()) .authenticationProvider(authenticationProvider())
.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); .addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
@ -77,4 +77,3 @@ public class SecurityConfiguration {
} }
} }

View File

@ -18,7 +18,6 @@ public class UserDetailsImpl implements UserDetails {
@JsonIgnore @JsonIgnore
private String password; private String password;
public UserDetailsImpl(Long id, String username, String password) { public UserDetailsImpl(Long id, String username, String password) {
this.id = id; this.id = id;
this.username = username; this.username = username;
@ -28,17 +27,13 @@ public class UserDetailsImpl implements UserDetails {
public static UserDetailsImpl build(User user) { public static UserDetailsImpl build(User user) {
return new UserDetailsImpl(user.getId(), user.getUsername(), user.getPassword()); return new UserDetailsImpl(user.getId(), user.getUsername(), user.getPassword());
} }
public Long getId() { public Long getId() {
return id; return id;
} }
public static long getSerialversionuid() { public static long getSerialversionuid() {
return serialVersionUID; return serialVersionUID;
} }
@ -78,8 +73,6 @@ public class UserDetailsImpl implements UserDetails {
return true; return true;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o)

View File

@ -0,0 +1,24 @@
package com.baeldung.request;
public class LoginRequest {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -1,3 +1,2 @@
spring.thymeleaf.prefix=classpath:/templates/
baeldung.app.jwtSecret= 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970 baeldung.app.jwtSecret= 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
baeldung.app.jwtExpirationMs= 8640000 baeldung.app.jwtExpirationMs= 8640000

View File

@ -0,0 +1,40 @@
package com.baeldung.jwtsecuritykey;
import com.baeldung.jwtsignkey.SpringJwtApplication;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest(classes = SpringJwtApplication.class)
public class JwtSignKeyIntegrationTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
private void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
@Test
public void givenAnonymous_whenAccessUserDashboard_thenForbidden() throws Exception {
mvc.perform(get("/user-dashboard"))
.andExpect(status().isUnauthorized());
}
}