Merge branch 'master' into bael-7667-update-readme
This commit is contained in:
@@ -23,7 +23,7 @@
|
||||
<module>spring-security-core-2</module>
|
||||
<!-- <module>spring-security-ldap</module>-->
|
||||
<module>spring-security-legacy-oidc</module> <!-- Ths module wasn't able to upgrade because is using Spring Security oauth2 which reached end of life. JAVA-29292-->
|
||||
<module>spring-security-oauth2</module>
|
||||
<module>spring-security-oauth2</module> <!-- This module wasn't updated to spring boot 3 because of spring-oauth2 not supporting Jakarta and reaching end of life. JAVA-29293 -->
|
||||
<module>spring-security-oauth2-sso</module> <!-- This module wasn't able to update because Spring Security Oauth reach end of life and not compatible with spring boot 3. JAVA-29294 -->
|
||||
<module>spring-security-oidc</module>
|
||||
<module>spring-security-okta</module>
|
||||
|
||||
@@ -69,7 +69,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<json.version>20190722</json.version>
|
||||
<json.version>20240303</json.version>
|
||||
<mvc-auth-commons.version>1.2.0</mvc-auth-commons.version>
|
||||
</properties>
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ This module contains articles about core Spring Security
|
||||
- [A Custom Spring SecurityConfigurer](https://www.baeldung.com/spring-security-custom-configurer)
|
||||
- [HttpSecurity vs. WebSecurity in Spring Security](https://www.baeldung.com/spring-security-httpsecurity-vs-websecurity)
|
||||
- [Spring Security AuthorizationManager](https://www.baeldung.com/spring-security-authorizationmanager)
|
||||
- [Migrate Application from Spring Security 5 to Spring Security 6/Spring Boot 3](https://www.baeldung.com/spring-security-migrate-5-to-6)
|
||||
- [Creating a Spring Security Key for Signing a JWT Token](https://www.baeldung.com/spring-security-sign-jwt-token)
|
||||
|
||||
### Build the Project
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
<properties>
|
||||
<start-class>com.baeldung.authresolver.AuthResolverApplication</start-class>
|
||||
<jjwt.version>0.12.5</jjwt.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -61,6 +62,21 @@
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-api</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-impl</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jsonwebtoken</groupId>
|
||||
<artifactId>jjwt-jackson</artifactId>
|
||||
<version>${jjwt.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
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 static void main(String[] args) {
|
||||
SpringApplication.run(com.baeldung.jwtsignkey.SpringJwtApplication.class);
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.jwtsignkey.controller;
|
||||
|
||||
import com.baeldung.jwtsignkey.jwtconfig.JwtUtils;
|
||||
import com.baeldung.jwtsignkey.model.User;
|
||||
import com.baeldung.jwtsignkey.repository.UserRepository;
|
||||
import com.baeldung.jwtsignkey.response.JwtResponse;
|
||||
import com.baeldung.jwtsignkey.userservice.UserDetailsImpl;
|
||||
import com.baeldung.request.LoginRequest;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
@RestController
|
||||
public class JwtAuthController {
|
||||
|
||||
@Autowired
|
||||
AuthenticationManager authenticationManager;
|
||||
|
||||
@Autowired
|
||||
PasswordEncoder encoder;
|
||||
|
||||
@Autowired
|
||||
JwtUtils jwtUtils;
|
||||
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
|
||||
@PostMapping("/signup")
|
||||
public ResponseEntity<?> registerUser(@RequestBody User signUpRequest, HttpServletRequest request) throws UnsupportedEncodingException {
|
||||
|
||||
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
|
||||
return ResponseEntity.badRequest()
|
||||
.body("Error: Username is already taken!");
|
||||
}
|
||||
User user = new User();
|
||||
user.setUsername(signUpRequest.getUsername());
|
||||
user.setPassword(encoder.encode(signUpRequest.getPassword()));
|
||||
|
||||
userRepository.save(user);
|
||||
|
||||
return ResponseEntity.ok(user);
|
||||
}
|
||||
|
||||
@PostMapping("/signin")
|
||||
public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
|
||||
|
||||
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
|
||||
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(authentication);
|
||||
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
|
||||
|
||||
String jwt = jwtUtils.generateJwtToken(authentication);
|
||||
|
||||
return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername()));
|
||||
|
||||
}
|
||||
|
||||
@RequestMapping("/user-dashboard")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public String dashboard() {
|
||||
return "My Dashboard";
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.jwtsignkey.jwtconfig;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
|
||||
logger.error("Unauthorized error: {}", authException.getMessage());
|
||||
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
|
||||
final Map<String, Object> body = new HashMap<>();
|
||||
body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
|
||||
body.put("error", "Unauthorized");
|
||||
body.put("message", authException.getMessage());
|
||||
body.put("path", request.getServletPath());
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.writeValue(response.getOutputStream(), body);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.jwtsignkey.jwtconfig;
|
||||
|
||||
import com.baeldung.jwtsignkey.userservice.UserDetailsServiceImpl;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class AuthTokenFilter extends OncePerRequestFilter {
|
||||
@Autowired
|
||||
private JwtUtils jwtUtils;
|
||||
|
||||
@Autowired
|
||||
private UserDetailsServiceImpl userDetailsService;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
try {
|
||||
String jwt = parseJwt(request);
|
||||
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
|
||||
String username = jwtUtils.getUserNameFromJwtToken(jwt);
|
||||
|
||||
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
|
||||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(authentication);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("Cannot set user authentication: {}", e);
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String parseJwt(HttpServletRequest request) {
|
||||
String headerAuth = request.getHeader("Authorization");
|
||||
|
||||
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
|
||||
return headerAuth.substring(7, headerAuth.length());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.baeldung.jwtsignkey.jwtconfig;
|
||||
|
||||
import com.baeldung.jwtsignkey.userservice.UserDetailsImpl;
|
||||
|
||||
import io.jsonwebtoken.ExpiredJwtException;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.MalformedJwtException;
|
||||
import io.jsonwebtoken.UnsupportedJwtException;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import io.jsonwebtoken.security.SignatureException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.util.Date;
|
||||
|
||||
@Component
|
||||
public class JwtUtils {
|
||||
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
|
||||
|
||||
@Value("${baeldung.app.jwtSecret}")
|
||||
private String jwtSecret;
|
||||
|
||||
@Value("${baeldung.app.jwtExpirationMs}")
|
||||
private int jwtExpirationMs;
|
||||
|
||||
public String generateJwtToken(Authentication authentication) {
|
||||
|
||||
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
|
||||
|
||||
return Jwts.builder()
|
||||
.subject((userPrincipal.getUsername()))
|
||||
.issuedAt(new Date())
|
||||
.expiration(new Date((new Date()).getTime() + jwtExpirationMs))
|
||||
.signWith(getSigningKey())
|
||||
.compact();
|
||||
|
||||
}
|
||||
|
||||
private SecretKey getSigningKey() {
|
||||
byte[] keyBytes = Decoders.BASE64.decode(jwtSecret);
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
|
||||
public String getUserNameFromJwtToken(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload()
|
||||
.getSubject();
|
||||
|
||||
}
|
||||
|
||||
public boolean validateJwtToken(String authToken) {
|
||||
try {
|
||||
Jwts.parser()
|
||||
.verifyWith(getSigningKey())
|
||||
.build()
|
||||
.parseSignedClaims(authToken);
|
||||
return true;
|
||||
} catch (SignatureException e) {
|
||||
logger.error("Invalid JWT signature: {}", e.getMessage());
|
||||
} catch (MalformedJwtException e) {
|
||||
logger.error("Invalid JWT token: {}", e.getMessage());
|
||||
} catch (ExpiredJwtException e) {
|
||||
logger.error("JWT token is expired: {}", e.getMessage());
|
||||
} catch (UnsupportedJwtException e) {
|
||||
logger.error("JWT token is unsupported: {}", e.getMessage());
|
||||
} catch (IllegalArgumentException e) {
|
||||
logger.error("JWT claims string is empty: {}", e.getMessage());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.jwtsignkey.model;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.jwtsignkey.repository;
|
||||
|
||||
import com.baeldung.jwtsignkey.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
Boolean existsByUsername(String username);
|
||||
|
||||
Optional<User> findByUsername(String username);
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.jwtsignkey.response;
|
||||
|
||||
public class JwtResponse {
|
||||
private String token;
|
||||
private String type = "Bearer";
|
||||
|
||||
private String username;
|
||||
|
||||
public JwtResponse(String accessToken, String username) {
|
||||
this.token = accessToken;
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getAccessToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setAccessToken(String accessToken) {
|
||||
this.token = accessToken;
|
||||
}
|
||||
|
||||
public String getTokenType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setTokenType(String tokenType) {
|
||||
this.type = tokenType;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.jwtsignkey.securityconfig;
|
||||
|
||||
import com.baeldung.jwtsignkey.jwtconfig.AuthEntryPointJwt;
|
||||
import com.baeldung.jwtsignkey.jwtconfig.AuthTokenFilter;
|
||||
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.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
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;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfiguration {
|
||||
|
||||
@Autowired
|
||||
UserDetailsService userDetailsService;
|
||||
@Autowired
|
||||
private AuthEntryPointJwt unauthorizedHandler;
|
||||
|
||||
private static final String[] WHITE_LIST_URL = { "/h2-console/**", "/signin", "/signup", "/user-dashboard" };
|
||||
|
||||
@Bean
|
||||
public AuthTokenFilter authenticationJwtTokenFilter() {
|
||||
return new AuthTokenFilter();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DaoAuthenticationProvider authenticationProvider() {
|
||||
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
|
||||
|
||||
authProvider.setUserDetailsService(userDetailsService);
|
||||
authProvider.setPasswordEncoder(passwordEncoder());
|
||||
|
||||
return authProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
|
||||
return authConfig.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
|
||||
http.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(AbstractHttpConfigurer::disable)
|
||||
.authorizeHttpRequests(req -> req.requestMatchers(WHITE_LIST_URL)
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated())
|
||||
.exceptionHandling(ex -> ex.authenticationEntryPoint(unauthorizedHandler))
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(STATELESS))
|
||||
.authenticationProvider(authenticationProvider())
|
||||
.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.jwtsignkey.userservice;
|
||||
|
||||
import com.baeldung.jwtsignkey.model.User;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Objects;
|
||||
|
||||
public class UserDetailsImpl implements UserDetails {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Long id;
|
||||
|
||||
private String username;
|
||||
|
||||
@JsonIgnore
|
||||
private String password;
|
||||
|
||||
public UserDetailsImpl(Long id, String username, String password) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
|
||||
}
|
||||
|
||||
public static UserDetailsImpl build(User user) {
|
||||
|
||||
return new UserDetailsImpl(user.getId(), user.getUsername(), user.getPassword());
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public static long getSerialversionuid() {
|
||||
return serialVersionUID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
UserDetailsImpl user = (UserDetailsImpl) o;
|
||||
return Objects.equals(id, user.id);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.jwtsignkey.userservice;
|
||||
|
||||
import com.baeldung.jwtsignkey.model.User;
|
||||
import com.baeldung.jwtsignkey.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
;
|
||||
|
||||
@Service
|
||||
public class UserDetailsServiceImpl implements UserDetailsService {
|
||||
|
||||
@Autowired
|
||||
UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
|
||||
|
||||
return UserDetailsImpl.build(user);
|
||||
}
|
||||
}
|
||||
+24
@@ -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;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
spring.thymeleaf.prefix=classpath:/templates/
|
||||
baeldung.app.jwtSecret= 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
|
||||
baeldung.app.jwtExpirationMs= 8640000
|
||||
|
||||
+40
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
This module contains articles about core Spring Security Oauth2 Backend-for-Frontend
|
||||
|
||||
### Relevant Articles:
|
||||
- [OAuth2 Backend for Frontend With Spring Cloud Gateway](https://www.baeldung.com/spring-backend-for-frontend-with-spring-cloud-gateway)
|
||||
- [OAuth2 Backend for Frontend With Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway-bff-oauth2)
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
<packaging>jar</packaging>
|
||||
<description>spring 5 security oauth sample project</description>
|
||||
|
||||
<!-- Unable to update this project to Boot 3 due to the lack of support for
|
||||
Spring-security-oauth2 dependencies in Spring Boot 3, which have reached their end of life. -->
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-security-modules</artifactId>
|
||||
|
||||
@@ -18,12 +18,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-oauth2-authorization-server</artifactId>
|
||||
<version>${spring-authorization-server.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<spring-authorization-server.version>0.3.1</spring-authorization-server.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+24
-34
@@ -5,24 +5,22 @@ import java.util.UUID;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
|
||||
import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
|
||||
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
||||
import org.springframework.security.oauth2.core.oidc.OidcScopes;
|
||||
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
|
||||
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
|
||||
import org.springframework.security.oauth2.server.authorization.config.ClientSettings;
|
||||
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings;
|
||||
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
|
||||
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
|
||||
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
|
||||
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
|
||||
|
||||
@Configuration
|
||||
public class AuthServerConfiguration {
|
||||
@@ -30,38 +28,30 @@ public class AuthServerConfiguration {
|
||||
@Bean
|
||||
@Order(1)
|
||||
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
|
||||
OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer<>();
|
||||
|
||||
// @formatter:off
|
||||
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
|
||||
http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
|
||||
.oidc(Customizer.withDefaults());
|
||||
http
|
||||
.requestMatcher(authorizationServerConfigurer.getEndpointsMatcher())
|
||||
.authorizeRequests(authorize ->
|
||||
authorize
|
||||
.anyRequest()
|
||||
.authenticated());
|
||||
http
|
||||
.exceptionHandling(exceptions ->
|
||||
exceptions.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")))
|
||||
.csrf( csrf ->
|
||||
csrf
|
||||
.ignoringRequestMatchers(authorizationServerConfigurer.getEndpointsMatcher()))
|
||||
.apply(authorizationServerConfigurer);
|
||||
|
||||
// Required by /userinfo endpoint
|
||||
http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
|
||||
// Redirect to the login page when not authenticated from the
|
||||
// authorization endpoint
|
||||
.exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login"),
|
||||
new MediaTypeRequestMatcher(MediaType.TEXT_HTML)))
|
||||
// Accept access tokens for User Info and/or Client Registration
|
||||
.oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()));
|
||||
|
||||
return http.build();
|
||||
// @formatter:on
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(2)
|
||||
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
// @formatter:off
|
||||
return http
|
||||
.formLogin(Customizer.withDefaults())
|
||||
.build();
|
||||
// @formatter:on
|
||||
http
|
||||
.authorizeHttpRequests((authorize) -> authorize
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.formLogin(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -89,8 +79,8 @@ public class AuthServerConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ProviderSettings providerSettings() {
|
||||
return ProviderSettings
|
||||
public AuthorizationServerSettings authorizationServerSettings() {
|
||||
return AuthorizationServerSettings
|
||||
.builder()
|
||||
.build();
|
||||
}
|
||||
|
||||
+1
-1
@@ -8,8 +8,8 @@ import java.util.UUID;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
|
||||
import org.springframework.security.oauth2.jwt.JwtDecoder;
|
||||
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
|
||||
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-security-modules</artifactId>
|
||||
<artifactId>parent-boot-3</artifactId>
|
||||
<relativePath>../../parent-boot-3</relativePath>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
|
||||
+2
@@ -5,6 +5,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ImportResource;
|
||||
|
||||
@SpringBootApplication
|
||||
//Comment this line when you want to use the class definition for defining Spring security rules, LoginRedirectSecurityConfig.
|
||||
// Uncomment the annotations from LoginRedirectSecurityConfig.
|
||||
@ImportResource({"classpath*:spring-security-login-redirect.xml"})
|
||||
class LoginRedirectApplication {
|
||||
public static void main(String[] args) {
|
||||
|
||||
+3
-2
@@ -13,8 +13,9 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
//if you use xsd configuration (spring-security-login-redirect.xml) please comment the annotations from this class, because it will overlap with configuration from this class
|
||||
/*@Configuration
|
||||
@EnableWebSecurity*/
|
||||
class LoginRedirectSecurityConfig {
|
||||
|
||||
private static final String LOGIN_USER = "/loginUser";
|
||||
|
||||
+6
-6
@@ -6,11 +6,11 @@
|
||||
xmlns:security="http://www.springframework.org/schema/security"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/mvc
|
||||
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
|
||||
http://www.springframework.org/schema/security
|
||||
http://www.springframework.org/schema/security/spring-security-5.2.xsd
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
https://www.springframework.org/schema/mvc/spring-mvc.xsd
|
||||
http://www.springframework.org/schema/security
|
||||
https://www.springframework.org/schema/security/spring-security.xsd
|
||||
http://www.springframework.org/schema/beans
|
||||
https://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<security:authentication-manager>
|
||||
<security:authentication-provider>
|
||||
@@ -40,7 +40,7 @@
|
||||
<mvc:interceptors>
|
||||
<mvc:interceptor>
|
||||
<mvc:mapping path="/loginUser"/>
|
||||
<bean class="com.baeldung.loginredirect.LoginPageInterceptor"/>
|
||||
<beans:bean class="com.baeldung.loginredirect.LoginPageInterceptor"/>
|
||||
</mvc:interceptor>
|
||||
</mvc:interceptors>
|
||||
</beans>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework.security.web" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
||||
@@ -82,7 +82,7 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-oxm</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<version>${spring-oxm.version}</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
@@ -172,6 +172,7 @@
|
||||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.security.version>6.1.5</org.springframework.security.version>
|
||||
<spring-oxm.version>6.1.4</spring-oxm.version>
|
||||
<!-- util -->
|
||||
<httpcore5.version>5.2.4</httpcore5.version>
|
||||
<httpclient5.version>5.3</httpclient5.version>
|
||||
|
||||
@@ -10,9 +10,9 @@
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-spring-5</artifactId>
|
||||
<artifactId>parent-spring-6</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-spring-5</relativePath>
|
||||
<relativePath>../../parent-spring-6</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@@ -86,15 +86,15 @@
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>${javax.servlet-api.version}</version>
|
||||
<groupId>jakarta.servlet</groupId>
|
||||
<artifactId>jakarta.servlet-api</artifactId>
|
||||
<version>${jakarta.servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>jstl</artifactId>
|
||||
<version>${jstl.version}</version>
|
||||
<groupId>jakarta.servlet.jsp.jstl</groupId>
|
||||
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
|
||||
<version>${jakarta.jstl-api.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- util -->
|
||||
@@ -127,9 +127,9 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.annotation</groupId>
|
||||
<artifactId>javax.annotation-api</artifactId>
|
||||
<version>${javax.annotation-api.version}</version>
|
||||
<groupId>jakarta.annotation</groupId>
|
||||
<artifactId>jakarta.annotation-api</artifactId>
|
||||
<version>${jakarta.annotation-api.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -173,7 +173,10 @@
|
||||
<properties>
|
||||
<!-- Maven plugins -->
|
||||
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
|
||||
<javax.annotation-api.version>1.3.2</javax.annotation-api.version>
|
||||
<jakarta.annotation-api.version>3.0.0-M1</jakarta.annotation-api.version>
|
||||
<jakarta.servlet-api.version>6.1.0-M1</jakarta.servlet-api.version>
|
||||
<jakarta.jstl-api.version>3.0.0</jakarta.jstl-api.version>
|
||||
<spring-security.version>6.2.1</spring-security.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user