-
Notifications
You must be signed in to change notification settings - Fork 0
/
JwtApplication.kt
248 lines (217 loc) · 10.7 KB
/
JwtApplication.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package com.example.jwt
import com.nimbusds.jose.jwk.JWKSelector
import com.nimbusds.jose.jwk.JWKSet
import com.nimbusds.jose.jwk.RSAKey
import com.nimbusds.jose.jwk.source.JWKSource
import com.nimbusds.jose.proc.SecurityContext
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.support.beans
import org.springframework.http.HttpStatus
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
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.oauth2.core.AuthorizationGrantType
import org.springframework.security.oauth2.core.ClientAuthenticationMethod
import org.springframework.security.oauth2.core.OAuth2TokenType
import org.springframework.security.oauth2.server.authorization.*
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationToken
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.config.ClientSettings
import org.springframework.security.oauth2.server.authorization.config.ProviderSettings
import org.springframework.security.oauth2.server.authorization.config.TokenSettings
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter
import org.springframework.web.servlet.function.ServerResponse
import org.springframework.web.servlet.function.router
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.time.Duration
import java.util.*
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletResponse
@SpringBootApplication
class JwtApplication
fun main(args: Array<String>) {
runApplication<JwtApplication>(*args){
addInitializers(beans {
bean {
router {
GET("/secured/test") {
val name = it.principal()
.map { it.name }
.orElse("no one")
ServerResponse.ok().body("test ok $name")
}
}
}
bean {
val http: HttpSecurity = ref()
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http)
http.build()
}
bean {
val userAndPasswordFilter: (ServletRequest, ServletResponse, FilterChain) -> Unit =
{ req, resp, chain ->
try {
val username: String? = req.getParameter("username")
val password: String? = req.getParameter("password")
val passwordEncoder: PasswordEncoder = ref()
val userDetailsService: UserDetailsService = ref()
if (username != null && password != null) {
val user = userDetailsService.loadUserByUsername(username)
if (!passwordEncoder.matches(password, user.password)) {
throw BadCredentialsException("wrong credentials")
}
} else throw BadCredentialsException("missing username or password")
chain.doFilter(req, resp)
} catch (ex: AuthenticationException) {
resp as HttpServletResponse
resp.status = HttpStatus.UNAUTHORIZED.value()
ex.message?.let { resp.writer.write(it) }
}
}
val http: HttpSecurity = ref()
http
.antMatcher("/oauth2/token")
.addFilterAfter(userAndPasswordFilter, BasicAuthenticationFilter::class.java)
http.build()
}
bean {
InMemoryOAuth2AuthorizationService() // This must be a JdbcOAuth2AuthorizationService if you want a stateless backend
}
bean {
val http: HttpSecurity = ref()
http
.authorizeHttpRequests { authz ->
authz
.antMatchers("/secured/*")
.hasAuthority("SCOPE_efc")
.antMatchers("/secured/*")
.hasRole("USER")
.and()
.oauth2ResourceServer { oauth2 ->
oauth2.jwt { jwtConfigurer ->
jwtConfigurer.jwtAuthenticationConverter { jwt ->
val service: OAuth2AuthorizationService = ref()
val token: OAuth2Authorization? = service.findByToken(jwt.tokenValue, OAuth2TokenType.ACCESS_TOKEN)
if(token?.accessToken?.isActive == false){
throw BadCredentialsException("token revoked")
}
val roles: List<String> = jwt.getClaimAsStringList("roles") ?: emptyList()
val scope: List<String> = jwt.getClaimAsStringList("scope") ?: emptyList()
JwtAuthenticationToken(
jwt,
roles.map(::SimpleGrantedAuthority) +
scope.map { SimpleGrantedAuthority("SCOPE_$it") })
}
}
}
}
.build()
}
bean {
ProviderSettings
.builder()
.issuer("http://auth-server:8080")
.build();
}
bean { BCryptPasswordEncoder() }
bean {
val encoder: PasswordEncoder = ref()
val registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("messaging-client")
.clientSecret(encoder.encode("secret"))
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://auth-server:8080/athorization_code")
.scope("efc")
.clientSettings(
ClientSettings.builder()
.requireProofKey(true)
.build())
.tokenSettings(
TokenSettings.builder()
.accessTokenTimeToLive(Duration.ofMinutes(60))
.build()
)
.build()
InMemoryRegisteredClientRepository(registeredClient)
}
bean {
val rsaKey: RSAKey = JwKUtils.generateRsa()
val jwkSet = JWKSet(rsaKey)
JWKSource { jwkSelector: JWKSelector, _: SecurityContext? ->
jwkSelector.select(jwkSet)
}
}
bean {
val encoder: PasswordEncoder = ref()
val user = User.builder()
.passwordEncoder(encoder::encode)
.username("user1")
.password("password")
.roles("USER")
.build()
InMemoryUserDetailsManager(user)
}
})
}
}
@Configuration(proxyBeanMethods = false)
class MyConfiguration{
@Bean
fun jwtCustomizer(userDetailsService: UserDetailsService) =
OAuth2TokenCustomizer<JwtEncodingContext>{ context ->
if (OAuth2TokenType.ACCESS_TOKEN == context.tokenType) {
context.headers.type("JWT").build()
val username = context
.getAuthorizationGrant<OAuth2ClientCredentialsAuthenticationToken>()
.additionalParameters["username"]
?.toString()
val user: UserDetails = userDetailsService.loadUserByUsername(username)
context.claims
.subject(username)
.id(UUID.randomUUID().toString())
.claim("roles", user.authorities.map { it.authority })
}
}
}
object JwKUtils {
private fun generateRsaKey(): KeyPair {
val keyPair: KeyPair = try {
val keyPairGenerator = KeyPairGenerator.getInstance("RSA")
keyPairGenerator.initialize(2048)
keyPairGenerator.generateKeyPair() // The key must receive a seed from the configuration if you want a stateless backend
} catch (ex: Exception) {
throw IllegalStateException(ex)
}
return keyPair
}
fun generateRsa(): RSAKey {
val keyPair: KeyPair = generateRsaKey()
val publicKey = keyPair.public as RSAPublicKey
val privateKey = keyPair.private as RSAPrivateKey
return RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID(UUID.randomUUID().toString())
.build()
}
}