Skip to content

Commit

Permalink
security - init jwt
Browse files Browse the repository at this point in the history
  • Loading branch information
chinnawatsut committed Mar 22, 2024
1 parent 3855241 commit 7896e6b
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 1 deletion.
1 change: 1 addition & 0 deletions kbazaar/.env.template
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export SONAR_TOKEN=${SONAR_TOKEN}
export SPRING_DATASOURCE_URL=jdbc:postgresql://${DB_URL}/${DB_NAME}
export SPRING_DATASOURCE_USERNAME=${DB_USERNAME}
export SPRING_DATASOURCE_PASSWORD=${DB_PASSWORD}
export SECURITY_JWT_SECRET=1ukPr@a1M@1T@1D3rN@NgJoNMaHenKubT@
6 changes: 5 additions & 1 deletion kbazaar/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,15 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok:1.18.30'

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
// implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.projectlombok:lombok:1.18.22'
implementation 'org.postgresql:postgresql:42.7.3'

implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'

implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.4.0'

testImplementation 'org.springframework.boot:spring-boot-starter-test'
Expand Down
Empty file added kbazaar/docker-compose.yml
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.kampus.kbazaar.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

@Component
public class JwtAuthFilter extends OncePerRequestFilter {

private final JwtService jwtService;

public JwtAuthFilter(JwtService jwtService) {
this.jwtService = jwtService;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
final String authHeader = request.getHeader(AUTHORIZATION);
final String jwtToken;

if (authHeader == null || !authHeader.startsWith("Bearer")) {
filterChain.doFilter(request,response);
return;
}
jwtToken = authHeader.substring(7);

if (SecurityContextHolder.getContext().getAuthentication() == null) {
if (!jwtService.isTokenExpired(jwtToken)) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken("mockUser", null, new ArrayList<>());
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}

filterChain.doFilter(request,response);
}

}
32 changes: 32 additions & 0 deletions kbazaar/src/main/java/com/kampus/kbazaar/security/JwtService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.kampus.kbazaar.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.function.Function;

@Component
public class JwtService {

@Value("${security.jwt.secret}")
private String SECRET_KEY = "";

public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}

public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return (Claims) Jwts.parserBuilder().setSigningKey(SECRET_KEY.getBytes()).build().parse(token).getBody();
}

public Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.kampus.kbazaar.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

private final JwtAuthFilter jwtAuthFilter;
public SecurityConfig(JwtAuthFilter jwtAuthFilter) {
this.jwtAuthFilter = jwtAuthFilter;
}

@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.disable())
.authorizeHttpRequests((requests) ->
requests
.requestMatchers("/swagger-ui/**","/v3/api-docs/**").permitAll()
.anyRequest()
.authenticated())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtAuthFilter, BasicAuthenticationFilter.class)
.build();
}
}
1 change: 1 addition & 0 deletions kbazaar/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ spring.datasource.maximumPoolSize=1
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:sql/schema/*.sql
spring.sql.init.data-locations=classpath:sql/data/*.sql
security.jwt.secret=

# swagger
springdoc.swagger-ui.enabled=true

0 comments on commit 7896e6b

Please sign in to comment.