Skip to content

Commit

Permalink
Merge pull request #5 from vinodbalakumar/feature/version-upgrade
Browse files Browse the repository at this point in the history
Feature/version upgrade
  • Loading branch information
vinodbalakumar authored Oct 7, 2024
2 parents 0799d5f + 142530a commit f56355e
Show file tree
Hide file tree
Showing 16 changed files with 252 additions and 85 deletions.
7 changes: 7 additions & 0 deletions Jenkins
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@Library('jenkins-shared-library') _

deployPipeline(
dockerRepo: 'your-docker-repo/spring-boot-app',
kubeconfigId: 'kubeconfig',
awsCredentialsId: 'aws-credentials'
)
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ This project demonstrates a simple JWT (JSON Web Token) authentication service b
- [Installation](#installation)
- [Configuration](#configuration)
- [Endpoints](#endpoints)
- [Testing the JWT Authentication](#testing-the-jwt-authentication)
- [Testing the JWT Authentication](#testing-the-jwt-authentication) stateless jwt token: means not managing session with server
- [License](#license)

## Technologies Used
Expand Down
10 changes: 7 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath />
<version>2.6.6</version> <!-- or later -->
</parent>

<properties>
Expand Down Expand Up @@ -65,7 +64,7 @@
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
<version>0.12.0</version>
</dependency>

<!-- MySQL Driver -->
Expand All @@ -74,6 +73,11 @@
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.26</version>
</dependency>



Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package com.java.vls.employee.portal.configuration;

import com.java.vls.employee.portal.jwt.JwtRequestFilter;
import com.java.vls.employee.portal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
Expand All @@ -11,39 +9,45 @@
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
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.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserService userService;
private final JwtRequestFilter jwtRequestFilter;
private final UserDetailsService userDetailsService;

@Autowired
private JwtRequestFilter jwtRequestFilter;

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
public SecurityConfig(JwtRequestFilter jwtRequestFilter, UserDetailsService userDetailsService) {
this.jwtRequestFilter = jwtRequestFilter;
this.userDetailsService = userDetailsService;
}


@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers("/auth/login","/auth/register","/h2-console/**").permitAll()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Override
@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
package com.java.vls.employee.portal.controller;

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

@RestController
@RequestMapping("/api")
public class SecuredController {
public class ApiController {

@GetMapping("/protected")
public ResponseEntity<String> getProtectedResource() {
return ResponseEntity.ok("This is a protected resource!");
}

// Accessible to authenticated users
@GetMapping("/hello")
public String hello() {
return "Hello, this is a secured endpoint!";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,24 @@
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

@Autowired
private AuthenticationManager authenticationManager;
private final AuthenticationManager authenticationManager;

@Autowired
private JwtUtil jwtUtil;

@Autowired
private UserService userService;
private final JwtUtil jwtUtil;

private final UserService userService;

public AuthController(AuthenticationManager authenticationManager, JwtUtil jwtUtil, UserService userService){
this.authenticationManager = authenticationManager;
this.jwtUtil = jwtUtil;
this.userService = userService;
}

@PostMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password) throws Exception {
Expand All @@ -30,7 +33,7 @@ public String login(@RequestParam("username") String username, @RequestParam("pa
} catch (Exception e) {
throw new Exception("Invalid credentials", e);
}
UserDetails userDetails = userService.loadUserByUsername(username);
User userDetails = userService.findByUsername(username);
return jwtUtil.generateToken(userDetails.getUsername());
}

Expand All @@ -40,4 +43,15 @@ public ResponseEntity<?> register(@RequestBody User user) {
User registeredUser = userService.registerUser(user);
return ResponseEntity.ok("User registered successfully with ID: " + registeredUser.getId());
}

@GetMapping("/users/{username}")
public ResponseEntity<User> getUser(@PathVariable String username) {
User user = userService.findByUsername(username);
if (user == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(user);
}


}
40 changes: 40 additions & 0 deletions src/main/java/com/java/vls/employee/portal/entity/Role.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.java.vls.employee.portal.entity;

import javax.persistence.*;

@Entity
@Table(name = "roles")
public class Role {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(unique = true, nullable = false)
private String name;

public Role() {
// Default constructor
}

public Role(String name) {
this.name = name;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;

}
}
30 changes: 29 additions & 1 deletion src/main/java/com/java/vls/employee/portal/entity/User.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
package com.java.vls.employee.portal.entity;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.CreatedDate;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "users")
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {

@Id
Expand All @@ -24,14 +33,33 @@ public class User {
@Column(nullable = false, unique = true)
private String email;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<>();

private transient String role;

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@CreationTimestamp
private LocalDateTime createdDate;

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@UpdateTimestamp
private LocalDateTime updatedDate;

// Constructors, Getters, and Setters

public User() {}

public User(String username, String password, String email) {
public User(String username, String password, String email,String role) {
this.username = username;
this.password = password;
this.email = email;
this.role = role;
}

// Getters and setters...
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.java.vls.employee.portal.jwt;

import com.java.vls.employee.portal.service.UserService;
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.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
Expand All @@ -18,16 +18,17 @@
@Component
public class JwtRequestFilter extends OncePerRequestFilter {

@Autowired
private JwtUtil jwtUtil;
private final JwtUtil jwtUtil; // Your JWT utility class

@Autowired
private UserService userService;
private final UserDetailsService userDetailsService; // Ensure this is your CustomUserDetailsService

public JwtRequestFilter(JwtUtil jwtUtil,UserDetailsService userDetailsService) {
this.jwtUtil = jwtUtil;
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {

final String authorizationHeader = request.getHeader("Authorization");

String username = null;
Expand All @@ -39,13 +40,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}

if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userService.loadUserByUsername(username);
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
chain.doFilter(request, response);
Expand Down
Loading

0 comments on commit f56355e

Please sign in to comment.