Skip to content

Refactoring to avoid deprecated methods #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ out/

### VS Code ###
.vscode/


.DS_Store
24 changes: 18 additions & 6 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
id("org.springframework.boot") version "3.0.6"
id("io.spring.dependency-management") version "1.1.0"
kotlin("jvm") version "1.7.22"
kotlin("plugin.spring") version "1.7.22"
kotlin("plugin.jpa") version "1.7.22"
val kotlinVersion = "2.0.0"


id("org.springframework.boot") version "3.3.1"
id("io.spring.dependency-management") version "1.1.5"
kotlin("plugin.spring") version kotlinVersion
kotlin("plugin.allopen") version kotlinVersion
kotlin("plugin.jpa") version kotlinVersion
kotlin("jvm") version kotlinVersion


}

group = "com.hadiyarajesh"
Expand All @@ -26,7 +32,7 @@ dependencies {

developmentOnly("org.springframework.boot:spring-boot-devtools")

runtimeOnly("com.h2database:h2")
runtimeOnly("com.h2database:h2:2.1.214")
runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.5")
runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.5")

Expand All @@ -44,3 +50,9 @@ tasks.withType<KotlinCompile> {
tasks.withType<Test> {
useJUnitPlatform()
}

allOpen {
annotation("javax.persistence.Entity")
annotation("javax.persistence.Embeddable")
annotation("javax.persistence.MappedSuperclass")
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import org.springframework.security.core.GrantedAuthority

@Entity
@Table(name = "roles")
class Role(
data class Role(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,5 @@ data class User(

@JsonIgnore
override fun isEnabled() = true

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,23 @@ class SecurityConfiguration(
fun filterChain(http: HttpSecurity): SecurityFilterChain? {
http
// .csrf { csrf -> csrf.ignoringRequestMatchers(AntPathRequestMatcher.antMatcher("/h2-console/**")).disable() }
.csrf()
.disable() // Why to disable CSRF? Read here -> https://docs.spring.io/spring-security/reference/features/exploits/csrf.html#csrf-when
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers(PathRequest.toH2Console()).permitAll()
.requestMatchers(EndPoint.AUTH_ROOT_PATH + EndPoint.SIGN_UP, EndPoint.AUTH_ROOT_PATH + EndPoint.SIGN_IN)
.permitAll()
.requestMatchers("${EndPoint.ADMIN_ROOT_PATH}/**").hasAuthority(RoleName.ADMIN.name)
.anyRequest().authenticated()
.csrf {
csrf -> csrf.ignoringRequestMatchers(PathRequest.toH2Console())
csrf.disable()
}
// Why to disable CSRF? Read here -> https://docs.spring.io/spring-security/reference/features/exploits/csrf.html#csrf-when
.sessionManagement {
it.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}
.authorizeHttpRequests {
it
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.requestMatchers(PathRequest.toH2Console()).permitAll()
.requestMatchers(EndPoint.AUTH_ROOT_PATH + EndPoint.SIGN_UP, EndPoint.AUTH_ROOT_PATH + EndPoint.SIGN_IN)
.permitAll()
.requestMatchers("${EndPoint.ADMIN_ROOT_PATH}/**").hasAuthority(RoleName.ADMIN.name)
.anyRequest().authenticated()
}

http
.addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter::class.java)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.hadiyarajesh.spring_security_demo.security

import com.hadiyarajesh.spring_security_demo.app.exception.InvalidJwtException
import io.jsonwebtoken.*
import io.jsonwebtoken.security.Keys
import jakarta.servlet.http.HttpServletRequest
import org.springframework.stereotype.Component
import org.springframework.util.StringUtils
Expand All @@ -12,8 +13,10 @@ class TokenProvider(
private val securityProperties: SecurityProperties
) {
private fun extractAllClaims(token: String): Claims {
return Jwts.parser()
.setSigningKey(securityProperties.secret)

return Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(securityProperties.secret.toByteArray()))
.build()
.parseClaimsJws(token)
.body
}
Expand All @@ -38,7 +41,7 @@ class TokenProvider(
.setIssuer("SpringSecurityKotlinDemoApplication")
.setIssuedAt(now)
.setExpiration(Date(now.time + tokenValidity))
.signWith(SignatureAlgorithm.HS256, securityProperties.secret)
.signWith(Keys.hmacShaKeyFor(securityProperties.secret.toByteArray()))
.compact()
}

Expand All @@ -59,8 +62,9 @@ class TokenProvider(

fun validateToken(token: String): Boolean {
try {
Jwts.parser()
.setSigningKey(securityProperties.secret)
Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(securityProperties.secret.toByteArray()))
.build()
.parseClaimsJws(token)
return true
} catch (e: MalformedJwtException) {
Expand All @@ -83,9 +87,14 @@ class TokenProvider(
}

fun getClaimsFromToken(token: String): Claims? {
return Jwts.parser()
.setSigningKey(securityProperties.secret)
.parseClaimsJws(token)
?.body
return try {
Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(securityProperties.secret.toByteArray()))
.build()
.parseClaimsJws(token)
.body
} catch (e: Exception) {
null
}
}
}
2 changes: 1 addition & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
spring:
datasource:
url: "jdbc:h2:file:~/security_database;DB_CLOSE_ON_EXIT=FALSE"
url: jdbc:h2:file:~/security_database;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE
driver-class-name: org.h2.Driver
username: sa
password: secret-password
Expand Down