Kunan pacha, aswan aswan llakikuyniyuq kayku ruwaymanta, chaymanta kikin pacha, yachayta munayku imayna sistemakuna utqaylla chaymanta atiyniyuq willayta atinku. Achka kutim willakuykunata apachiyta munanchik hinaspa atisqanchikman hina pakasqa hinaspa mana imamanta manchakuspa waqaychayta munanchik. Sensible datokuna wakin kuti web kaqpipas llapa runap qayllanpi purinanku tiyan chaymanta ruwaykunata wak puntapi alambre kaqpi qallarinanku tiyan. Aswantaqa, ruwaykunata paqarichiyta munayku, chaykunam datos mutacionkunata ruwanqa. Kay casokunapi, mana datoyku waqaychayllatachu qhawachkayku. Willayta kachaspa ruwasqa ruwaykuna atisqa kananpaq qhawayta munayku. Datosniykuta achka ruwaykunawan waqaychayta atiyku. Aswan riqsisqa, willayta huk TLS
(Transport Layer Security) waqaychasqa tinkiywan apachiyku. Chayqa datosniyku Chifrasqa kananpaq alambre kaqnintakama qhawanqa. Certificadokuna llamk'achiyku iskay partikunapura hapipakuq tinkiykuna ruwanapaq chaymanta kayta aypanapaq.Kay qillqasqapi, JWT
kamachiymanta rimayta munani chaymanta aswanta qhawayta munani imayna JWT
huk común Enterprise
ruwanaman tinkiyta atiykuman. Kaypiqa KumuluzEE
nisqamanta qhawarisunchis .Wakin qallariy hamut’aykunata qhawarisunchis. JWT
icha JSON Web Token, icha aswan allin, JavaScript Objeto Notación Web Token, huk kamachiymi RFC7519 kaqpi riqsichisqa. Kay kamachiyqa, llapa RFC
(Comentariokuna mañakuy) kamachiykuna hina, IETF
(Internet Ingeniería Task Force) kaqwan riqsichisqa, qillqasqa chaymanta lluqsichisqa karqa. Achka imaymanakunawanmi sut’inchakunman. Generalmente, nisunman JWT
huk compacto, mana imamanta manchachikuq forma iskay partikunapura reclamacionkunata apachinapaq. Huk ñan imachus huk reclamación kaqta pisiyachinapaq, básicamente huk suti/chani paris hina willayta mayqinchus willayta hap'in. Kay willayta necesitayku huk pisi importante aspectokuna internet willakuyniykumanta garantizanaykupaq. Asegurananchikmi chay willakuy chaskisqayku allinchasqa kananpaq hinaspa punta kaqpi hapipakunanpaq. Chaymantataq chayta validananchis. Kayqa aswanta chay.Kay kamachiyta ruwanapaq, achka marcokuna llamk'achiyta atiykuman mayqinkunachus Java empresa ruwana ruwayta yanapawasunman. Spring Boot nisqaqa anchatam llamk'achisqa kachkan. Achka kutipas huk sutiyuqwan p'istuykusqa kachkan propiedad software kaqpi wakin organizacionkunamanta qullqi wasikuna hina chaymanta wak qullqi organizacionkunamanta. Ejemploykupaqmi tantearurqani huknirayta ruwanaypaq. Spring Boot nisqamantaqa, KumuluzEE
nisqawan huk ejemplota qhawarisunchis. Puntoqa, JWT
imachus kasqanmanta, imaynachus kasqanmanta ima allinta riqsiymi. Java Enterprise Yanapakuykuna aswanta ruwanakuna kanku mayqinkunachus huk ruwana sirwiqpi mast'arisqa kankuman utaq sapallankumanta purichiyta atinku huk churasqa sirwiqpa llamk'ayninwan. Huk rikch'ana hina, Spring Boot ruwanakuna huk churasqa Tomcat sirwiqpi purin. Kay qillqasqapiqa, KumuluzEE
nisqamanta rimarisunchik. Imaynachus Spring Boot kaqpipas huk churasqa servidorta hap'in. Salvo kay casopiqa Jetty sutiyuq. Kayqa Soldadurawan kuskachasqa llamk'achisqa CDI(Inyección de Dependencia de Contexto) nisqa qunapaq. Llapan Java EE
chaymanta Jakarta EE
tecnologia kamachiykuna kay framework
kaqwan tupan .
JWT
imayna llamkasqanmanta ejemplota qawachinaypaqqa, imayna qawachinaypaqmi yuyaymananay karqa. Ejemplokuna clásico maypichus seguridad huk llakikuy kan chaypi kanku bancokuna. Ichaqa, huk tukuy banco mañakuyta ruway imayna JWT
llamk'asqanmanta rikuchinapaq huk pacha usuchiy kanman chaymanta ichapas ancha achka hamut'aykuna chaypi kanman. Aswanpas ruwasqayqa ancha sasan sistema bancario nisqa. Hatun llakikuyniyku imayna willakuy alambre kaqninta purin chaymanta imayna ruwaqkuna wakin áreas ruwanaykuman yaykuyta tarinku chayta rikuchiymi. Hinallataq mana rimasaqchu TLS kaqmanta utaq imayna chifrasqa willayta alambre kaqninta apachiyta atiykuman. JWT
nisqapi yuyayniykutaqa aswan ch'uya formapi waqaychasaqku.Casoykuqa sistema bancario nisqa, huk huñu naturalezata, pachamamatapas defiendeqpa llamk'achisqanmi. Kayqa kusikuyllam qawachinapaq imayna JWT
llamkasqanmanta. Kay Liga de Naturaleza nisqapi aswan hatun runaqa Lucymi, payqa llapa qillqasqaykunapim común runaman tikrakuchkan.
Manaraq qallarichkaspa, purichkaq aplicacionninchikta bosquejasunchik. Ancha sasallawan ruwanapaqmi, ichaqa allinraqmi siq'inapaq:
Razón imaraykuchus kayqa ancha sasan kachkan chaymanta JWT
sapa mañakuypi qhawasqa chaymanta sapa mañakuy llave pública kaqwan chiqaqchasqa, chaymanta yachayku sapa mañakuypi chiqan tokenta apachisqaykukama chaymanta pasayta atisaqku. JWT
OAuth2, Okta SSO utaq mayqin wak kamachiy mecanismo kaqwan tinkisqa kanman. Kayhina kaqtinqa, ruwasqaykuqa chiqaqchayta chaymanta kamachiyta takyachiymi. Aplicacionniykupi, JWT
llamk'achisaqku chaymanta chaywan, willakuyniyku chiqaqchay huk firmawan. Ichaqa manan chay aplicacionman haykusaqkuchu. Aswanpas, ruwaqkunata kamachiyniyku llamk'achinankupaq kamachiyku allin chiqaqchaymanta. Kaypi, JWT
ukhunpi chiqamanta huk hunt'asqa ruwanamanta ancha huch'uy parte kasqanmanta qhawayqa sasam. Chaywanpas wakin ruwanakuna yapasqa kanan tiyan. Kaykunaqa Recursos nisqakunan necesitanchis:
Nisunmanmi sistema básico nisqanchis qolqeta, crédito nisqa mañakuyllata registranqa nispa. Esencialmente valores nisqakunata huñunqalla. Yuyaymanasuntaqmi wakin runakunaqa crédito chaskiyta atinqaku wakintaq mana. Wakin runakunaqa qolqeta waqaychayta atinqaku, wakintaq manukuyta chaskinqaku.
Riqsichikuypi nisqa hina, KumuluzEE
empresa ruwanaykupa marcon hina llamk'achisaqku, chaymanta huk ultra-básica ruwanata ruwasaqku huk ruwaypi chaymanta JWT
terminología básica chaymanta hamut'aykunata qhawayta atiyku.Aseguray allin Java layayuq kayta. Kay etapapi, aswan pisi Java 17 SDK churasqa necesitasaqku. Maven, git, huk Java-wan tupaq IDE IntelliJ hina, chaymanta huk shell imahinapas necesitasaqku.
Yanapakuyniyku qallarinapaq, huk pisi KumuluzEE
dependenciakunayuq kayku. Kayqa aswanta imaraykuchus KumuluzEE
, imaynachus Spring Boot huk iskay dependenciakuna necesitan. POM willañiqita pisillapi qhawarisunchik:
<dependencies> <dependency> <groupId>com.kumuluz.ee.openapi</groupId> <artifactId>kumuluzee-openapi-mp</artifactId> </dependency> <dependency> <groupId>com.kumuluz.ee.openapi</groupId> <artifactId>kumuluzee-openapi-mp-ui</artifactId> </dependency> <dependency> <groupId>com.kumuluz.ee</groupId> <artifactId>kumuluzee-microProfile-3.3</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.mockk</groupId> <artifactId>mockk-jvm</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.ninja-squad</groupId> <artifactId>springmockk</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.kotest</groupId> <artifactId>kotest-assertions-core-jvm</artifactId> <scope>test</scope> </dependency> </dependencies>
Iskay kimsa dependenciakunamanta pisillapi rimarisunchik. Kayta ñawinchaspaykiqa, ama hina kaspa, pom.xml
willañiqiykuta patamanta urayman qatipay. Kayqa ancha allinmi kay qatiq sut'inchayta hamut'anapaq.Huk paquete dependenciakuna necesitayku ruwanayku llamk'ananpaq. , Ancha kusisqa, KumuluzEE
, Microperfil bibliotecakuna quwanchik mayqinkunachus kay ruwana qallariypaq básicos estándar paquetes kaqwan kanku. Kayqa llapanmi KumuluzEE
-Microprofile biblioteca nisqapi kachkan. Appniykuta llapa JWT
parámetros necesitasqaykuwan ruwayta atinaykupaq, chayman huk MicroProfile bibliotecata yapanayku tiyan. Chaypachallapitaq, JSON ruwana bibliotecata necesitayku. Kaymi Johnson Corepa ruwasqan kanqa. Necesitayku claro KumuluzEE
núcleonta llamkanaykupaq. Jetty nisqaqa KumuluzEE
marcota purichiq ukhu sirwiqmi. Kayraykum necesitanchik dependencianchikkunapi. CDI
necesitasqaykumanta qhawarispa, chayta yanapaq bibliotecatapas necesitayku. REST tukukuyniyku atichinaykupaq, KumuluzEE
kaqpa puchuqnin bibliotecata necesitayku. APIykuta chaskinaykupaq, chaymanta huk Geronimo bibliotecata necesitayku. Chaywanmi JSR-374
nisqapa implementacionnin kananpaq. Hinallataq JWT
nisqaykutapas JSON-formatted
kaqninkunatapas interpretanayku.Lombokqa manam chiqaptachu necesitakun per se. ¡Tukuy imatapas sumaqllata, llimp’iyuqllata ruwan! Logback nisqapas ancha allinmi kanan, chaynapi registrokunata aswan allinta interpretanapaq hinaspa ruwasqanchikta entiendenapaq.Kunanqa qawarisun resources
carpetanchikta.Qallarinapaq puntata entiendesun imakunatam kay carpetapi tariyta suyanchik. Yanapakuyniykuta JWT
kaqwan tupaqwan ruwanayku tiyan , Logback kaqwan chaymanta tukukuypaq, imallatapas ninayku tiyan chay habas ruwasqaykumanta.Chaypi aswan sasan archivota qhawasunchik. Chay beans.xml nisqataqa META-INF nisqapi tarinki:
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" xmlns:weld="http://jboss.org/schema/weld/beans" bean-discovery-mode="all"> <weld:scan> <weld:exclude name="org.jesperancinha.fintech.model.Accounts"/> </weld:scan> </beans>
Kayqa huk típicolla chaymanta kunan yuyaykusqaykiman hina, huk chhika mawk'a archivo. Kaypiqa, yuyayqa KumuluzEE
purichinapaqlla. Ñuqaykuqa kanmi huk acción excluir nisqa. Kayqa Weldman nin ama Cuentas de clase nisqakunata qhawarinanpaq, habas ruwayninpaq escaneo ruwasqanpi. Kayqa ancha allinmi imaraykuchus implementacionwan llamk'achkanchik, Weld
básicamente sapa claseta huk ch'usaq ruwaqwan haba hina qhawarinqa. Qhepamanmi qhawarisunchis imaraykun mana munanchischu Cuentas nisqakuna habas hina qhawarisqa kananta. Kunankamaqa yuyaypi hap'isun mañakuykunata ruwachkayku Mañakuy alcance nisqapi. Kayqa lógico imaraykuchus sapa mañakuy hukniray userniyuq kayta atin.Kunanqa qhawasun imaynatachus " logback
" ruwasqa kachkan. Hinallataqmi META-INF
nisqapi tarikun :
<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> <root level="INFO"> <appender-ref ref="STDOUT"/> </root> </configuration>
Kayqa ancha chiqan ruwaylla logs
.Tukuyninpaq, ichapas aswan chaniyuq willañiqi ruwanaykumanta. Kayqa config-plantilla nisqa. Kaypiqa, ancha allinmi kay proyectopi ruwasqay wakin archivokuna huk plantilla estructurapa parten kasqanmanta. Chaymanta astawan sut’inchasaq qhepaman. Kay plantilla willañiqiqa config.yml willañiqiman tikrasqa kanan tiyan mayqinchus MicroProfile kaqwan ñawirinqa. Kay willañiqiqa kapuqpa saphinpim kachkan:
kumuluzee: name: your-financeje-banking version: 1.0.0 jwt-auth: public-key: {{ publicKey }} issuer: {{ issuer }} healthy: true
Qhepamanmi qhawarisunchis imapunichus cheqaqtapuni llapan kay propiedades nisqakuna niyta munan. Llapallankum kikinkumanta sut’inchakunku. publicKey chaymanta emisor llapa parámetros kanku mayqinkunachus tikrasqa kanqa. Chaytaqa qhepamanmi t’aqwirisunchis. Bash scriptniykuqa tikrasqa kasqankuta qhawanqa.Yaqa listoña kayku codificacionman rinaykupaq, ichaqa ñawpaqta, JWT
token estructuraykuta qhawarisunchik.
Ancha uchuylla aplicacionninchikta ruwasun. Kay t'aqapin sut'inchasun imaynatas solicitudninchis JWT
nisqawan llank'achisunman chayta. Imatachus qhawayta munasqaykuqa sichus wakin REST
ñanniykuman yaykunapaq ruwaqkunata niyta atiyku manataq wakkunamanchu.Huk ñan kay codigo qhawayta qallariypaq ñawpaqta huk qhawayta ruway JWT
llañu tokenniykuman. Kaypi kachkan admin ejemplonchik:
{ "iss": "joaofilipesabinoesperancinha", "jti": "01MASTERFINANCE", "sub": "admin", "aud": "nature", "upn": "admin", "groups": [ "user", "admin", "client", "credit" ], "user_id": 1, "access": "TOP", "name": "Admin" }
Sapa huk kay sutikuna JSON
reclamacionkuna hina riqsisqa. Ejemploykupiqa rikunchikmi huk iskay kimsa Reservado nisqa reclamacionkunata:
iss
" — Kayqa tokenpa quqninmi. Chaypaqqa munasqanchikman hinam huk chaninchayta akllachwan. Kay parámetro chaninqa ñawpaq rikusqayku config.yml kaqpi tikranapaq quq tikraqwan tupanan tiyan.jti
" — Kayqa tokenpa sapalla riqsichiqninmi. Ejemplopaq kay reclamacionta llamk'achiy atiykuman huk token iskay kuti utaq aswan kuti llamk'achiyta hark'anapaq.sub
" — Kayqa tokenpa sujetonmi. Chayqa kanmanmi usuario utaq imapas munasqanchik. Importantemi yuyaypi hap'iy kayta huk riqsichiq hina, llave hina, sutichay hina utaq ima munasqayku hina llamk'achiy atikunman.upn
" — Ruraqpa umalliq sutin. Kayqa llamk'achiqpa llamk'achisqan umalliqta riqsichinapaqmi.groups
" — Kayqa kunan llamk'achiqpa huñunkunap matrizninmi. Esencialmente kayqa determinanqa imatachus huk mañakuy kay tokenwan ruwayta atin. Tokenniykupi, chaymanta rikuyku huk iskay kimsa Custom reclamacionkunata. Kaytaqa Reservado nisqa reclamacionkuna hina allintam servichikuchwanuser_id
" — Kayta llamk'achisaqku user id nisqa churanapaq.access
" — Ruwaqpa yaykuy patantam kamachisaqku.name
" — Ruraqpa sutin. Kunankama yachasqanchikmanta huk recapitularta ruwasun. Yachanchikmi huk estructura determinasqanchikwan tokenkunawan rimanakunanchikta. Astawan, ruwanaykupa ruwayninta churarqayku, logback ruwayta chaymanta tukukuypaq, huk ruwasqa ruwayta empresa habas maskanapaq churarqayku.Paquete modelota qhawasunchik. Kaypiqa 3 clasekunatam tarisunchik. Kay clasekuna básicamente huk agregación cuentakuna chaymanta representación client
chaymanta account
chawpipi kaqlla representan . Kayhinata qallariyta atiykuman kotlin archivo Model.kt maypi Client
tarikun:
data class Client constructor( @JsonProperty var name: String ?= null )
Kay ñawpaq modelo claseqa clienteykupa representacionninmi. Casoykupaq client
sutiyuqllam. Kayqa " jwt
" atributo sutiwan rikuchisqa username.Astawan, Account
:
data class Account( @JsonProperty val accountNumber: String?, @JsonProperty val client: Client? = null, @JsonProperty var currentValue: BigDecimal = BigDecimal.ZERO, @JsonProperty var creditValue: BigDecimal = BigDecimal.ZERO ) { fun addCurrentValue(value: Long) = Account( accountNumber, client, currentValue .add(BigDecimal.valueOf(value)), creditValue ) fun addCreditValue(value: Long): Account = Account( accountNumber, client, currentValue, currentValue .add(BigDecimal.valueOf(value)) ) }
Kay clasepi, básicamente huk accountNumber, huk cliente, huk currentValue chaymanta tukukuypi huk creditValue kaqmanta churayku. Reparay llapa chanikunata 0 kaqman ñawpaqmanta churasqayku.BigDecimal kaqtapas llamk'achkayku, qullqiwan ruwasqaykuraykulla. Qullqiqa chiqan kanan tiyan, manataq sistema muyurichiykunata utaq muyurichiykunata ñak’ariyta atinchu. Kayqa huk rimaypi niyta munan chaymanta huk ejemplo hina huk yupay 0. 0000000000000000000000000000000000000000000000000001
Euros chay yupayta tukuy pacha qhipakunan tiyan. Hinallataq, yupayniykuman chanikunata yapayta munayku. Kaypim addCurrentValue nisqa ruwayqa hamun. Kikin razonkunarayku, creditoykutapas addCreditValue
kaqwan yapasaqku .Tukuyninpaq, qhipa kaq t'aqapi willayniyku churasqaykupi clase Accounts
kaqwan tupayku :
open class Accounts constructor( open val accountMap: MutableMap<String, Account> = mutableMapOf() )
Kayqa aswantaqa llapa yupayniykupa huñuqninllam. Mapa kaqninta llamk'achisunchik huk willay tantanapa ruwayninta qatipanapaq.Kunanqa kamachiq paqueteta qhawasunchik. Kaypi ruwasqayku ruwanayku purichkaqta modelo de datosniykuwan. Ñawpaqta, huk qhawayta ruwasun clase BankApplication
:
@LoginConfig(authMethod = "MP-JWT") @ApplicationPath("/") @DeclareRoles("admin", "creditor", "client", "user") class BankApplication : Application()
Kaywanmi 3 importante kaqkunata rimashanchis. LoginConfig anotacionwan, MicroProfile kaqmanhina JWT
tokenkuna llamk'achinapaq chaymanta hamut'anapaq riqsichiyku. ApplicationPath nisqa ruwana saphita riqsichin. Kaypim ruwanapa URL qallarinqa. Ejemploykupi, HTTP://localhost:8080 kanqa. Tukuyninpaq, DeclareRoles ruwanakuna llamk'achinapaq chaymanta ruwasqaykuwan chaskisqa kananta riqsichin. Ruwaykuna chaymanta Huñukuna kay situacionpi términokuna intercambiable kanku.Inyección allin llamk'ananpaq, huk anotación específica ruwayku yupay mapa riqsichinapaq:
annotation class AccountsProduct
Tukuy pantalla modoman yaykuy Tukuy pantalla modomanta lluqsiy
Chaymanta, huk caché objeto fabrica AccountsFactory ruwayku:
class AccountsFactory : Serializable { @Produces @AccountsProduct @ApplicationScoped fun accounts(): Accounts = Accounts(mutableMapOf()) companion object { @Throws(JsonProcessingException::class) fun createResponse( currentAccount: Account, name: JsonString, accounts: Accounts, log: Logger, objectMapper: ObjectMapper, principal: Principal?, jsonWebToken: JsonWebToken? ): Response { val jsonObject = Json.createObjectBuilder() .add("balance", currentAccount.currentValue) .add("client", name) .build() accounts.accountMap[name.string] = currentAccount log.info("Principal: {}", objectMapper.writeValueAsString(principal)) log.info("JSonWebToken: {}", objectMapper.writeValueAsString(jsonWebToken)) return Response.ok(jsonObject) .build() } } }
Kay fabricaqa imaraykuchus maskanata mana llamk'achirqayku específicamente Accounts
kaqpaq . Maskana ruwayta huk habas ruwayta saqinamantaqa, huñuq instanciata ñuqayku kikiyku ruwayku. Produces anotacionta llamk'achispa, habas ruwayta atiyku. Sapanchasqa anotacionniykuwan, AccountsProduct kaqwan, kay haba llamk'achiyta aswan específico ruwayku. Tukuyninpaq, ApplicationScoped
llamk'achispa, alcancenta Application
alcance kaqhina riqsichiyku. Huk rimaypi, yupay huñuna haba huk sapalla objeto hina tukuy ruwanapi purinqa." createResponse
" huk genérico ñanlla JSON kutichiykunata ruwanapaq.Kunan necesitasqayku iskay "Recursokuna" kanku. Kayqa aswanta " Controllers
" kaqwan Primavera kaqpi kaqlla. Huk sutim, ichaqa kaqlla llamk'achiyniyuqmi.CuentasResource AccountsResource
claseta qhawasunchik:
@Path("accounts") @RequestScoped @Produces(MediaType.APPLICATION_JSON) open class AccountResource { @Inject @AccountsProduct open var accounts: Accounts? = null @Inject open var principal: Principal? = null @Inject open var jsonWebToken: JsonWebToken? = null @Inject @Claim("access") open var access: JsonString? = null @Claim("iat") @Inject open var iat: JsonNumber? = null @Inject @Claim("name") open var name: JsonString? = null @Inject @Claim("user_id") open var userId: JsonNumber? = null @POST @RolesAllowed("admin", "client", "credit") @Throws(JsonProcessingException::class) open fun createAccount(): Response = createResponse( requireNotNull(accounts).accountMap[requireNotNull(name).string] ?: Account( client = Client(name = requireNotNull(name).string), accountNumber = UUID.randomUUID().toString() ) ) @POST @RolesAllowed("admin", "user") @Path("user") @Throws(JsonProcessingException::class) open fun createUser(): Response { return createResponse( requireNotNull(accounts).accountMap[requireNotNull(name).string] ?: Account( client = Client(name = requireNotNull(name).string), accountNumber = UUID.randomUUID().toString() ) ) } @GET @RolesAllowed("admin", "client") @Throws(JsonProcessingException::class) open fun getAccount(): Response? { return createResponse( requireNotNull(accounts).accountMap[requireNotNull(name).string] ?: return Response.serverError() .build() ) } @PUT @RolesAllowed("admin", "client") @Consumes(MediaType.APPLICATION_JSON) @Throws( JsonProcessingException::class ) open fun cashIn(transactionBody: TransactionBody): Response? { val userAccount = requireNotNull(accounts).accountMap[requireNotNull(name).string] ?: return Response.serverError() .build() val currentAccount = userAccount.addCurrentValue(transactionBody.saldo?: 0) requireNotNull(accounts).accountMap[requireNotNull(name).string] = currentAccount return createResponse(currentAccount) } @GET @Path("all") @Produces(MediaType.APPLICATION_JSON) @Throws( JsonProcessingException::class ) open fun getAll(): Response? { val allAccounts = ArrayList( requireNotNull(accounts).accountMap .values ) logger.info("Principal: {}", objectMapper.writeValueAsString(principal)) logger.info("JSonWebToken: {}", objectMapper.writeValueAsString(jsonWebToken)) return Response.ok(allAccounts) .build() } @GET @Path("summary") @Throws(JsonProcessingException::class) open fun getSummary(): Response? { val totalCredit = requireNotNull(accounts).accountMap .values .map(Account::currentValue) .stream() .reduce { result, u -> result.add(u) } .orElse(BigDecimal.ZERO) val jsonObject = Json.createObjectBuilder() .add("totalCurrent", totalCredit) .add("client", "Mother Nature Dream Team") .build() logger.info("Summary") logger.info("Principal: {}", objectMapper.writeValueAsString(principal)) logger.info("JSonWebToken: {}", objectMapper.writeValueAsString(jsonWebToken)) return Response.ok(jsonObject) .build() } @GET @RolesAllowed("admin", "client") @Path("jwt") open fun getJWT(): Response? { val jsonObject = Json.createObjectBuilder() .add("jwt", requireNotNull(jsonWebToken).rawToken) .add("userId", requireNotNull(userId).doubleValue()) .add("access", requireNotNull(access).string) .add("iat", requireNotNull(iat).doubleValue()) .build() return Response.ok(jsonObject) .build() } @Throws(JsonProcessingException::class) private fun createResponse(currentAccount: Account): Response = AccountsFactory.createResponse( currentAccount, requireNotNull(name), requireNotNull(accounts), logger, objectMapper, principal, jsonWebToken ) companion object { val objectMapper: ObjectMapper = ObjectMapper() val logger: Logger = LoggerFactory.getLogger(AccountResource::class.java) } }
Huk ratuta hap’iy kay claseta aswan sut’ita qhawarinaykipaq. Path
anotacionqa imayna kay yanapakuyman saphimanta chayayta riqsichin. Yuyariy "/" saphi hina llamk'achisqanchikta. Kayhina kaqpi, "yupaykuna" kay yanapakuypaq sapsi yaykuyniyku. Llapan recursoyku, ñuqaykupi iskaylla alcance RequestResource kaqwan purichkanku. Anotación kaqwan Produces determinan llapa kutichiykuna aggregator
mañakuykunaman mana ima laya kaqtinpas JSON formatoyuq willakuypa rikch'ayninta hap'inqa.Huñuqniyku inyectanapaqqa Inject anotación chaymanta AccountsProduct
anotacionpa tinkiyninllata llamk'achiyku:
@Inject @AccountsProduct open var accounts: Accounts? = null
Kayqa tupanmi fabricapi definisqaykuwan.Astawan, iskay importante elementokuna seguridadmanta inyectachkaykutaqmi. Huk principal
chaymanta jsonWebToken
:
@Inject open var principal: Principal? = null @Inject open var jsonWebToken: JsonWebToken? = null
JsonWebToken
chaymanta Principal
iskayninku kaqlla kanqa, chaymanta chayta registroykupi rikusaqku.Recursoykupi, sapa kuti huk mañakuymanta reclamacionkunata inyectar atiykuman huk token kaqwan:
@Inject @Claim("name") open var name: JsonString? = null @Inject @Claim("user_id") open var userId: JsonNumber? = null
Kayqa ruwakun Inject
chaymanta Claim
anotacionkuna huñusqawan. Claim
anotacionpa urayninpi churasqa sutiqa mayqin reclamacionta inyectayta munasqanchikta riqsichin. Cuidakunanchikmi ima tipowanchus parámetrosninchikta defininchik. Ejemploykupi,r JsonString
chaymanta JsonNumber
layakunallata necesitayku.Ñawpaqta, qhawasunchik imayna yupaykunata chaymanta ruwaqkunata ruwachkayku:
@POST @RolesAllowed("admin", "client", "credit") @Throws(JsonProcessingException::class) open fun createAccount(): Response = createResponse( requireNotNull(accounts).accountMap[requireNotNull(name).string] ?: Account( client = Client(name = requireNotNull(name).string), accountNumber = UUID.randomUUID().toString() ) ) @POST @RolesAllowed("admin", "user") @Path("user") @Throws(JsonProcessingException::class) open fun createUser(): Response { return createResponse( requireNotNull(accounts).accountMap[requireNotNull(name).string] ?: Account( client = Client(name = requireNotNull(name).string), accountNumber = UUID.randomUUID().toString() ) ) }
Yupaykunata, llamk'achiqkunata ima paqarichiy
Kaypi propósitoqa métodokunata t'aqayta atiymi, hukniray permisokunata quy. Ejemploykupi, iskayninku huk yupayta ruwankulla, ichaqa importante kanku reparay chaymanta ruwaqkunalla ruwanakunayuq user createUser métodota llamk'achiyta atinku. Chaynallataq, cliente chaymanta crédito ruwanakunayuq ruwaqkunalla createAccount ruwayman yaykuyta atinku.Kunanqa kay yanapakuypa PUT mañakuy ñanninta sut'imanta qhawasunchik:
@PUT @RolesAllowed("admin", "client") @Consumes(MediaType.APPLICATION_JSON) @Throws( JsonProcessingException::class ) open fun cashIn(transactionBody: TransactionBody): Response? { val userAccount = requireNotNull(accounts).accountMap[requireNotNull(name).string] ?: return Response.serverError() .build() val currentAccount = userAccount.addCurrentValue(transactionBody.saldo?: 0) requireNotNull(accounts).accountMap[requireNotNull(name).string] = currentAccount return createResponse(currentAccount) }
Cashing In
Yachanchikmi anotacion PUT
nisqa kay método PUT
nisqa laya mañakuykunawanlla yaykuy atikuq kasqanmanta. Chaymanta Anotacion Ñan Jettyman willan kay ñanman ñanqa huk chaniyuq kasqanmanta. Kayqa PathParam
nisqapas riqsisqam. Tukuyninpaq, kay métodota definiyta atiykuman sapalla ruwaqkuna llamk'achinankupaq ruwanakunayuq admin utaq cliente kaqwan. Chaymanta yaykusqa chanin PathParam llamk'achispa Unay chanin tikraqniykuman pasasqa.Mana ima ruwanakunatapas CreditResource
, chaymanta mayqin ruwaqpas allin token kaqwan kay ruwanakunaman yaykuyta atinqa.CreditResource kaqllapi ruwasqa ñan:
@Path("credit") @RequestScoped @Produces(MediaType.APPLICATION_JSON) open class CreditResource { @Inject @AccountsProduct open var accounts: Accounts? = null @Inject open var principal: Principal? = null @Inject open var jsonWebToken: JsonWebToken? = null @Inject @Claim("access") open var access: JsonString? = null @Inject @Claim("iat") open var iat: JsonNumber? = null @Inject @Claim("name") open var name: JsonString? = null @Inject @Claim("user_id") open var userId: JsonNumber? = null @GET @RolesAllowed("admin", "credit") @Throws(JsonProcessingException::class) open fun getAccount(): Response = requireNotNull(accounts).let { accounts -> createResponse( accounts.accountMap[requireNotNull(name).string] ?: return Response.serverError().build() ) } @PUT @RolesAllowed("admin", "credit") @Consumes(MediaType.APPLICATION_JSON) @Throws( JsonProcessingException::class ) open fun cashIn(transactionBody: TransactionBody) = requireNotNull(accounts).let { accounts -> requireNotNull(name).let { name -> accounts.accountMap[name.string] = (accounts.accountMap[name.string] ?: return Response.serverError() .build()).addCreditValue(transactionBody.saldo?: 0L) createResponse( (accounts.accountMap[name.string] ?: return Response.serverError() .build()).addCreditValue(transactionBody.saldo?: 0L) ) } } @GET @Path("all") @Produces(MediaType.APPLICATION_JSON) @Throws( JsonProcessingException::class ) open fun getAll(): Response? { val allAccounts = ArrayList( requireNotNull(accounts).accountMap .values ) logger.info("Principal: {}", objectMapper.writeValueAsString(principal)) logger.info("JSonWebToken: {}", objectMapper.writeValueAsString(jsonWebToken)) return Response.ok(allAccounts) .build() } @GET @Path("summary") @Produces(MediaType.APPLICATION_JSON) @Throws( JsonProcessingException::class ) open fun getSummary(): Response? { val totalCredit = requireNotNull(accounts).accountMap .values .map(Account::creditValue) .stream() .reduce { total, v -> total.add(v) } .orElse(BigDecimal.ZERO) val jsonObject = Json.createObjectBuilder() .add("totalCredit", totalCredit) .add("client", "Mother Nature Dream Team") .build() logger.info("Summary") logger.info("Principal: {}", objectMapper.writeValueAsString(principal)) logger.info("JSonWebToken: {}", objectMapper.writeValueAsString(jsonWebToken)) return Response.ok(jsonObject) .build() } @GET @RolesAllowed("admin", "client") @Path("jwt") open fun getJWT(): Response? { val jsonObject = Json.createObjectBuilder() .add("jwt", requireNotNull(jsonWebToken).rawToken) .add("userId", requireNotNull(userId).doubleValue()) .add("access", requireNotNull(access).string) .add("iat", requireNotNull(iat).doubleValue()) .build() return Response.ok(jsonObject) .build() } @Throws(JsonProcessingException::class) private fun createResponse(currentAccount: Account): Response { return AccountsFactory.createResponse( currentAccount, requireNotNull(name), requireNotNull(accounts), logger, objectMapper, principal, jsonWebToken ) } companion object { val objectMapper: ObjectMapper = ObjectMapper() val logger: Logger = LoggerFactory.getLogger(CreditResource::class.java) } }
Huklla chiqan kayqa, ruwanakuna admin
chaymanta client
llamk'achiyta rantipi kunan admin
chaymanta credit
ruwaykunata llamk'achkayku. Hinallataq, qhaway, ruwaqkunapaq yupaykuna mana hayk'aqpas kay resource
ruwasqachu kanqa . Chayqa yupaypa resource
atikun .Kunanqa imayna codigo ruwasqa kasqanmanta yachaspayku ñawpaqta recap mayqin métodokunata ruwasqayku REST
servicioykupi.
Llamk'achisqa yanapakuykunap listanta qhawasunchik:
Tipo,URL,Carga de pago,Resultado,Roles Permitisqa
APACHIY,
APACHIY,
TARIY,
CHURAY,
TARIY,
TARIY,
TARIY,
CHURAY,
TARIY,
TARIY,
Sapsi qillqana mayt'upi bash
willañiqita ruwarqani. Kay willañiqiqa "setupCertificates.sh" sutiyuq. Chayta qhawarisun ima ruwasqanmanta yuyayta tarinapaq:
#!/bin/bash mkdir -p your-finance-files cd your-finance-files || exit openssl genrsa -out baseKey.pem openssl pkcs8 -topk8 -inform PEM -in baseKey.pem -out privateKey.pem -nocrypt openssl rsa -in baseKey.pem -pubout -outform PEM -out publicKey.pem echo -e '\033[1;32mFirst test\033[0m' java -jar ../your-finance-jwt-generator/target/your-finance-jwt-generator.jar \ -p ../jwt-plain-tokens/jwt-token-admin.json \ -key ../your-finance-files/privateKey.pem >> token.jwt CERT_PUBLIC_KEY=$(cat ../your-finance-files/publicKey.pem) CERT_ISSUER="joaofilipesabinoesperancinha" echo -e "\e[96mGenerated public key: \e[0m $CERT_PUBLIC_KEY" echo -e "\e[96mIssued by: \e[0m $CERT_ISSUER" echo -e "\e[96mYour token is: \e[0m $(cat token.jwt)" cp ../your-financeje-banking/src/main/resources/config-template ../your-financeje-banking/src/main/resources/config_copy.yml CERT_CLEAN0=${CERT_PUBLIC_KEY//"/"/"\/"} CERT_CLEAN1=${CERT_CLEAN0//$'\r\n'/} CERT_CLEAN2=${CERT_CLEAN1//$'\n'/} CERT_CLEAN3=$(echo "$CERT_CLEAN2" | awk '{gsub("-----BEGIN PUBLIC KEY-----",""); print}') CERT_CLEAN4=$(echo "$CERT_CLEAN3" | awk '{gsub("-----END PUBLIC KEY-----",""); print}') CERT_CLEAN=${CERT_CLEAN4//$' '/} echo -e "\e[96mCertificate cleanup: \e[0m ${CERT_CLEAN/$'\n'/}" sed "s/{{ publicKey }}/$CERT_CLEAN/g" ../your-financeje-banking/src/main/resources/config_copy.yml > ../your-financeje-banking/src/main/resources/config_cert.yml sed "s/{{ issuer }}/$CERT_ISSUER/g" ../your-financeje-banking/src/main/resources/config_cert.yml > ../your-financeje-banking/src/main/resources/config.yml rm ../your-financeje-banking/src/main/resources/config_cert.yml rm ../your-financeje-banking/src/main/resources/config_copy.yml echo -e "\e[93mSecurity elements completely generated!\e[0m" echo -e "\e[93mGenerating tokens...\e[0m" TOKEN_FOLDER=jwt-tokens mkdir -p ${TOKEN_FOLDER} # CREATE_ACCOUNT_FILE=createAccount.sh CREATE_USER_FILE=createUser.sh SEND_MONEY_FILE=sendMoney.sh ASK_CREDIT_FILE=askCredit.sh TOKEN_NAME_VALUE=tokenNameValue.csv echo "#!/usr/bin/env bash" > ${CREATE_ACCOUNT_FILE} chmod +x ${CREATE_ACCOUNT_FILE} echo "#!/usr/bin/env bash" > ${CREATE_USER_FILE} chmod +x ${CREATE_USER_FILE} echo "#!/usr/bin/env bash" > ${SEND_MONEY_FILE} chmod +x ${SEND_MONEY_FILE} echo "#!/usr/bin/env bash" > ${ASK_CREDIT_FILE} chmod +x ${ASK_CREDIT_FILE} for item in ../jwt-plain-tokens/jwt-token*.json; do if [[ -f "$item" ]]; then filename=${item##*/} per_token=${filename/jwt-token-/} token_name=${per_token/.json/} cp "${item}" jwt-token.json java -jar ../your-finance-jwt-generator/target/your-finance-jwt-generator.jar \ -p jwt-token.json \ -key ../your-finance-files/privateKey.pem > token.jwt cp token.jwt ${TOKEN_FOLDER}/token-"${token_name}".jwt token=$(cat token.jwt) echo "# Create account: ""${token_name}" >> ${CREATE_ACCOUNT_FILE} echo "echo -e \"\e[93mCreating account \e[96m${token_name}\e[0m\"" >> ${CREATE_ACCOUNT_FILE} echo curl -i -H"'Authorization: Bearer ""${token}""'" http://localhost:8080/accounts -X POST >> ${CREATE_ACCOUNT_FILE} echo "echo -e \"\e[93m\n---\e[0m\"" >> ${CREATE_ACCOUNT_FILE} echo "# Create user: ""${token_name}" >> ${CREATE_USER_FILE} echo "echo -e \"\e[93mCreating user \e[96m${token_name}\e[0m\"" >> ${CREATE_USER_FILE} echo curl -i -H"'Authorization: Bearer ""${token}""'" http://localhost:8080/accounts/user -X POST >> ${CREATE_USER_FILE} echo "echo -e \"\e[93m\n---\e[0m\"" >> ${CREATE_USER_FILE} echo "# Send money to: "${token_name} >> ${SEND_MONEY_FILE} echo "echo -e \"\e[93mSending money to \e[96m${token_name}\e[0m\"" >> ${SEND_MONEY_FILE} echo curl -i -H"'Content-Type: application/json'" -H"'Authorization: Bearer ""${token}""'" http://localhost:8080/accounts -X PUT -d "'{ \"saldo\": "$((1 + RANDOM % 500))"}'" >> ${SEND_MONEY_FILE} echo "echo -e \"\e[93m\n---\e[0m\"" >> ${SEND_MONEY_FILE} echo "# Asking money credit to: "${token_name} >> ${ASK_CREDIT_FILE} echo "echo -e \"\e[93mAsking credit from \e[96m${token_name}\e[0m\"" >> ${ASK_CREDIT_FILE} echo curl -i -H"'Content-Type: application/json'" -H"'Authorization: Bearer ""${token}""'" http://localhost:8080/credit -X PUT -d "'{ \"saldo\": "$((1 + RANDOM % 500))"}'">> ${ASK_CREDIT_FILE} echo "echo -e \"\e[93m\n---\e[0m\"" >> ${ASK_CREDIT_FILE} echo "${token_name},${token}" >> ${TOKEN_NAME_VALUE} fi done
Pachamama miray
Ama hina kaspa, archivota qatipay ima ruwasqanmanta sut'inchasqayman hina. Kayqa ancha allinmi, chaynapi ima ruwasqanmanta allinta entiendenanchikpaq. Ñawpaqta sapalla chaymanta llapapaq llavekunata ruwayku huk PEM
formato kaqpi. Chaymanta sapalla llaveta "your-finance-jwt-generator.jar" purichiy atiyniykuwan llamk'achiyku. Kayqa purichiy atikuq jarranchikmi chaymi tokenkuna utqaylla ruwayta saqin. Chay quqtaqa manam qhipaman tikrayta atikunmanchu. Tukuchanapaqtaq, juk tokenta paqarichimun. Qhepamanmi qhawarisunchis imaynatas kay tokenta leesunman chayta. Kay tokenqa 3 yapasqa Umalla mañakuykunata hap'in. Kaykunaqa "kid", "typ", "alg" nisqakunam. Kay formato nisqatam qatipan:
{ "kid": "jwt.key", "typ": "JWT", "alg": "RS256" }
JWT
nisqapa umalliqnin
Aswan allinta qhawarisun kay nisqankuta:
IANA
willay mast'ariq layakunata willanapaq llamk'achkan. Kimsa akllanakuna kan JWT
(JSON Web token), JWE
(JSON Web Chifray), chaymanta JWA
(JSON Web Algoritmos). Kay layakunaqa manam experimentoykupaqqa tupanchu. Rikusaqkulla tokenniyku mana chiqamanta allin chifrasqa kaqta chaymanta chiqamanta mana sasachu descifrar kaqta. Qawasuntaqmi tokenkunata descifrayta atispapas, manam chayna faciltachu huk ruwaykunata ruwanapaqqa mana allintachu ruwayta atichwan.Llave pública nisqaykuwanqa, plantillaykuta tikranaykupaqmi tukupaypiqa servichikuchwan. Musuq config.yml willañiqiqa kayhinam kanan:
kumuluzee: name: your-financeje-banking version: 1.0.0 jwt-auth: public-key: FAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKE.FAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETO.FAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKEN issuer: joaofilipesabinoesperancinha healthy: true
config.yml nisqa
Iskay kaq ruwayqa tawa willañiqikunata ruwaymi. Sapa sapalla llañu tokenpaq " jwt-plain-tokens
" sutiyuq qillqana mayt'upi, tawa kamachiykunata ruwasaqku. Ñawpaq kamachiyqa ruwaqkuna ruwaymi, paykunaqa allinta ruwayta atinku yupayninkuwan. Kaykunaqa " admin
", " client
", chaymanta " credit
" nisqa perfilniyuq llamk'aqkuna kanku." createAccount.sh
" willañiqita purichisunchik, chaykunata ruwanapaq. Iskay kaq kamachiyqa puchuq ruwaqkunata ruwanqa mayqinkunachus manaraq ima derechoyuqchu kanku. Kayqa "createUser.sh" nisqa willañiqim. Chayta phawarisunchik. Kunanqa llapa llamk'aqkuna tukukuypi kamasqa kasqankuta qhawasunchik. Kunanqa ruwaykunamanta sut’inchaykunata qhawarisunchis, puchuq iskay kamachikuykunatataq qhawarisunchis. Hukninmi "cashin" nisqaman, huknintaq aswan crédito nisqa mañakunanpaq. Ñawpaq kaq paqarichisqa willañiqiqa "sendMoney.sh" bash qillqam. Kaypiqa " cashin
" nisqaman llapa mañakuykunata tarisunman. Kay willañiqipi huk curl mañakuyta tarinki, sapa llamk'aqman qullqi yupaykunata random kaqta apachinapaq. Admin casota qhawarisun:
#!/usr/bin/env bash # Send money to: admin echo -e "\e[93mSending money to \e[96madmin\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer= FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 125}' echo -e "\e[93m\n---\e[0m" # Send money to: cindy echo -e "\e[93mSending money to \e[96mcindy\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 360}' echo -e "\e[93m\n---\e[0m" # Send money to: faustina echo -e "\e[93mSending money to \e[96mfaustina\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 50}' echo -e "\e[93m\n---\e[0m" # Send money to: jack echo -e "\e[93mSending money to \e[96mjack\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 205}' echo -e "\e[93m\n---\e[0m" # Send money to: jitska echo -e "\e[93mSending money to \e[96mjitska\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 332}' echo -e "\e[93m\n---\e[0m" # Send money to: judy echo -e "\e[93mSending money to \e[96mjudy\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 295}' echo -e "\e[93m\n---\e[0m" # Send money to: lucy echo -e "\e[93mSending money to \e[96mlucy\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 160}' echo -e "\e[93m\n---\e[0m" # Send money to: malory echo -e "\e[93mSending money to \e[96mmalory\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 413}' echo -e "\e[93m\n---\e[0m" # Send money to: mara echo -e "\e[93mSending money to \e[96mmara\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 464}' echo -e "\e[93m\n---\e[0m" # Send money to: namita echo -e "\e[93mSending money to \e[96mnamita\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 51}' echo -e "\e[93m\n---\e[0m" # Send money to: pietro echo -e "\e[93mSending money to \e[96mpietro\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 491}' echo -e "\e[93m\n---\e[0m" # Send money to: rachelle echo -e "\e[93mSending money to \e[96mrachelle\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 474}' echo -e "\e[93m\n---\e[0m" # Send money to: sandra echo -e "\e[93mSending money to \e[96msandra\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 417}' echo -e "\e[93m\n---\e[0m" # Send money to: shikka echo -e "\e[93mSending money to \e[96mshikka\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/accounts -X PUT -d '{ "saldo": 64}' echo -e "\e[93m\n---\e[0m"
sendMoney.sh nisqamanta hurqusqa
Chay kikin usuariokuna qullqi mañakuyninkutapas paykunaman qusqa kanku:
#!/usr/bin/env bash # Asking money credit to: admin echo -e "\e[93mAsking credit from \e[96madmin\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 137}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: cindy echo -e "\e[93mAsking credit from \e[96mcindy\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 117}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: faustina echo -e "\e[93mAsking credit from \e[96mfaustina\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 217}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: jack echo -e "\e[93mAsking credit from \e[96mjack\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 291}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: jitska echo -e "\e[93mAsking credit from \e[96mjitska\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 184}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: judy echo -e "\e[93mAsking credit from \e[96mjudy\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 388}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: lucy echo -e "\e[93mAsking credit from \e[96mlucy\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 219}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: malory echo -e "\e[93mAsking credit from \e[96mmalory\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 66}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: mara echo -e "\e[93mAsking credit from \e[96mmara\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 441}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: namita echo -e "\e[93mAsking credit from \e[96mnamita\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 358}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: pietro echo -e "\e[93mAsking credit from \e[96mpietro\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 432}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: rachelle echo -e "\e[93mAsking credit from \e[96mrachelle\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 485}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: sandra echo -e "\e[93mAsking credit from \e[96msandra\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 500}' echo -e "\e[93m\n---\e[0m" # Asking money credit to: shikka echo -e "\e[93mAsking credit from \e[96mshikka\e[0m" curl -i -H'Content-Type: application/json' -H'Authorization: Bearer FAKE.FAKE.FAKE' http://localhost:8080/credit -X PUT -d '{ "saldo": 89}' echo -e "\e[93m\n---\e[0m"
askCredit.sh nisqamanta hurqusqa
Llapan characters
Liga de Nature
nisqap hukninmi . Esencialmente wakin qutu runakunalla kay sistema bancario nisqapi kanankupaq. Kaypiqa pachamamatam amachachkanku. Manan cheqaqtachu relevante chay qelqapaq imatachus kay t’aqa runakuna ruwanku otaq maypi willakuypi tupanku, ichaqa contextopaq, paykunaqa participanku ruwaykunapi pachamama defiendenankupaq hinallataq pisiyachinankupaq cambio climático nisqapa efectonkunata . Wakin characters
tukuy imata ruwayta atinku, wakintaq mana imatapas ruwayta atinkuchu wakintaq "cashin" nisqallata otaq "crédito mañakuy" nisqallata. Reparaytaq sensitivo willakuykunata pantachisqayta. Kay tokenkuna normalmente mana rakinasqachu kananku tiyan utaq rikusqa kananku tiyan kay URL particular kaqpi. Paykunaqa arí sapa kuti kanku chay navegador ruwaq consola kaqnintakama ichaqa imayna kaqtinpas wakin mañakuykuna ruwasqa kaqta protect
. Kayqa huk hamut'ay riqsisqa "seguridad-por-oscuidad" kaqwan and
mana técnicamente hark'anchu chaypas, usuariota consciente kananpaq chay token llamk'achisqanmanta, llamk'an huk disuasorio hina.Iskaynin métodokunapi, mayk'aq huk qullqi churay ruwasqayku utaq mayk'aq ñuqayku mañakuy crédito, reparay sapa mañakuypaq, huk yupay random kaqta 1manta 500kama apachichkayku.Kunanqa yaqa listoña kayku mañakuyniyku qallarinaykupaq, ichaqa ñawpaqta, huk buceo ruwasun a aswan pisilla teoría.
JWT
token ruwakun
Kunanqa tokenniyku paqarichisqaykuña, hukninta qhawarisun. Huk mana sut'i rikusqa tokenta rikuchisqayki, chaywantaq kayta entiendesaqku.Kaypim tokenniyku kachkan: FAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKE
. FAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETO
. FAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKENFAKETOKEN
Kaypi importante reparanapaqqa, tokenninchis kinsa t’aqapi t’aqasqa kasqan:
Header
kaqwan Payload
kaqwan cifrasqa huñusqa . Decidiyku algoritmo llamk'achiyta munasqayku chaymanta kay bit token kaqmanta básicamente determinanqa sichus willayta apachisqayku confiable kanan tiyan. Chay huñusqapaq sapallan chaymanta sirwiqniyku "llave-llave" ruwasqayku llamk'achinqa sichus huk tupachiyniyuq kayku chayta yachanapaq. Sichus yuyarinki kay patamanta RS256
ejemploykupi llamk'achkayku.
Manaraq hinalla purichkaptiyku, ama hina kaspa, iskaynin Header
chaymanta Payload
Util nisqapas ejemploykupi decyphered
kanman. Chaylla "manan" carga útil nisqawan utaq umalliqwan manipulayta atiykuchu chaymanta hinallataqmi ruwayku confiable. Huk mana allin tokenpa atikuq efectonkunamanta harkayqa akllasqayku algoritmowanlla harkasqa kanman. Chaymi allin yuyaywan akllay.Sichus huk organizacionpi llank’ashanki maypichus pakasqa willakuykuna llakikuypaq kashan, ahinataq bancopi, ama hina kaspa AMA ruwaychu imatachus ruwanaykuta. Kayqa huk ñanlla ñuqaykupaq internetpi qhawanaykupaq chay tokenkuna ruwasqaykumanta.Ñawpaqta, https://jwt.io/ kaqman risun chaymanta JWT
tokenniykuta hunt'achisun. Chayraq paqarichisqayki tokenta llamk'achiy:
https://jwt.io/ nisqawan tokenniykupa kaqninkunata qawanapaqKaypi imakuna kasqanmanta qawasun. Kayqa kamachiqniykupa tokenninmi. Chay runaqa "Admin" nisqa ejemplonchispi. Rikusunmanmi parámetros nisqanchis llapanku kasqanmanta. Listaykupi rikuyku "sub", "aud", "upn", "access", "user_id", "iss", "suti", "grupos" chaymanta tukukuypi "jti". Hinallataqmi wakin extra reclamacionkunatapas kapuwanchik. Chaykunata qhawarisunchis:
" auth_time " — Kayqa chiqapchay ruwakuptin. Tokenniyku chiqapchasqa hina domingo, 17 ñiqin inti raymi killapi 2022 p'unchawpi 16:15:47 GMT+02:00 DST" iat " — Kayqa token kamasqa kaptin. Ñoqaykupaq, kayqa auth_time." exp " — Kayqa tokenpa tukukuy p'unchawninmi. Domingo 17 ñiqin inti raymi killapi 2022 watapi 16:32:27 GMT+02:00 DST p'unchawpi tukukun. Tokenniykupiqa manam ima p'unchaw tukukuytapas nirqaykuchu. Kayqa niyta munan JWT
~15 minutukuna ñawpaqmanta churasqa chaninninta llamk'achin.
Kunanqa wakin pruebakunata ruwasun.
Chay codigoqa GitHub nisqapi llamk'anapaq wakichisqañam kachkan. Sichus codigota qhawayku chaymanta Intellij kaqwan kichayku chaymanta yachanayku tiyan mana kay ruwayta Spring Boot ruwana hina purichiyta atiykuchu. Mana "psvm" nisqa kanchu purichinapaq. Aswanpas, ruwasqa jarrata chiqalla purichiyta atiykuman chaymanta huk "mvn ruway" ruwasqaykumanta ñawpaqllaraq qhawayta atiykuman. Kaypi imaynatas kunan pacha llamk'achkani:
[1] . ] https://github.com/jesperancinha/your-finance-je "Aplicación purichinapaq pachamama churay")
Kunanqa " setupCertificates.sh
" qillqa mayt'uta wakmanta purichisunchik. Mana yachanichu hayka tiempota kayman chayanaykipaq ichaqa ancha probablem chay 15 minutokunaña kaypi tukusqa. Just in case, just run them again.App nisqaykutaqa qallarisun!Kayhinatam qallarichwan:
mvn clean install java -jar your-financeje-banking/target/your-financeje-banking.jar
Utaq chaylla purichiyta atiykuman listo purinapaq ruwasqaykuwan. Repo chaymanta Makefile ñawpaqmanta qhaway sichus tukuy ruwasqanmanta hamut'ayta munanki:
make dcup-full-action
Kay qillqa mayt'u 2 yanapakuykunata purichinqa. Hukninmi 8080
puertopi huknintaq 8081
puertopi. 8080
puerto kaqpi huk laya kay software kaqmanta purichisaqku kikin códigoyku purichispa JWT
tokenkuna ruwanapaq. 8081 puertopi, huk laya purichisunchik jwtknizr
generadorta Adam Bien
ruwasqanwan. Kay qillqasqata astawan qhawarisunchik, ichaqa 8080
puertopi purichkaq yanapakuymanta. Munaspaqa, cypress
nisqatapas kaykunawanmi purichiyta atinki:
make cypress-open
Kayqa cypress
consolata open
, chaymanta pruebakunata akllasqayki maskaqwan purichiyta atikunki. Ichaqa, maskaq akllanakuna kay etapapi pisillaraq kachkan. Yaqa llapan mañakuykuna chiqapmanta kamachiy chiru mañakuykuna kanqa cypress
.Kunankama, ama " cypress
" nisqaman yaykusunchu. Ama hina kaspa, maskaqniykiman riy hinaspa kay kitiman riy:
http://localhost:8080/cuentakuna/llapa
Kay hinatan huk resultadota chaskinanchis:
Rikusqanchis hina, " Malory
", " Jack Fallout
", " Jitska
" nisqakunapas manan ima crédito nisqatapas qolqetapas chaskinkuchu. Kayqa, paykunaman llamk'aq qutullata qusqa kasqankuraykum. Reparaytaq Shikka
mana ima crédito nisqatapas qosqankuta. " Shikka
", sapalla clienteyku mana qutu créditoyuqchu.Sichus registrokunata qhawaspa, rikusunman allin ruwaykuna kay formatota hap'isqankuta:
Sending money to admin HTTP/1.1 200 OK Date: Sun, 17 Jul 2022 15:01:13 GMT X-Powered-By: KumuluzEE/4.1.0 Content-Type: application/json Content-Length: 32 Server: Jetty(10.0.9) {"balance":212,"client":"Admin"}
Huk 200 willawanchik llamk'ay allin risqanmanta."Malory", "Jack Fallout", "Jitska" kaqpi, iskaynin llamk'ay mana allinchu chaymanta kayhina willayta chaskisunchik:
Sending money to jitska HTTP/1.1 403 Forbidden X-Powered-By: KumuluzEE/4.1.0 Content-Length: 0 Server: Jetty(10.0.9)
Huk 403 willawanchik JWT
tokenniyku validasqa kasqanmanta chaymanta confiable kasqanmanta. Ichaqa, chay llamk'ayta ruwayta hark'asqa. Huk rimaypiqa, manan chay método designado nisqaman haykuyta atinkuchu.
Fichasninchikta huk chikanta manipulasunchik. Sichus wakin tokenkunata sendMoney.sh willañiqimanta tikranchik. Kayta chaskinanchik tiyan:
Sending money to admin HTTP/1.1 401 Unauthorized X-Powered-By: KumuluzEE/4.1.0 WWW-Authenticate: Bearer realm="MP-JWT" Content-Length: 0 Server: Jetty(10.0.9)
Tukuy pantalla modoman yaykuy Tukuy pantalla modomanta lluqsiy
Kay 401
niyta munan, tokenniyku mana validasqachu karqan. Niyta munan, llave pública mayqinchus servidor llamk'achkan qhawanapaq sichus tokenniyku atisqa kanan tiyan, mana tupachiyta tarisqachu. Sichus llave pública mana JWT tokenpa firmanta chaninchayta chaymanta chiqaqchayta atinchu, chaymanta mana chaskinqachu.
Huk kutichiy hina, Uma kaq chaymanta "Payload" mana chifrasqachu. Paykunaqa base 64 "codificado" nisqalla kanku. Kayqa niyta munan "Decodificación" sapa kuti huk qhawayta ukhupi imachus carga útil chiqamanta kasqanmanta saqiwanchik. Sichus maskachkayku carga útilniyku waqaychayta mana uyariymanta, mana "Carga útil" nisqa tokenpa huk imapaqpas llamk'achinaykuchu aswanpas riqsichiy parámetros akllay. Sasachakuyqa chiqamanta kachkan mayk'aq huk runa makinkuta JWT
token kaqpi tarin, huk rikch'anapaq, mayk'aq TLS tunel pantasqa kaptin chaymanta pipas chay t'inkisqa willakuypa contenidonta ñawiriyta atin. Chayna kaptinqa huk harkakuypas kanraqmi. Hinaspa kaymi firma. Huklla willayta yaykuchkaqta chiqaqchayta atiq, llapapaq llaveyuq sirwiq. Kay llapapaq llave, llapapaq kaptinpas, yaykuq willayta chiqaqchaylla saqillan firmawan chaymanta "Uma + Carga útil" kaqwan purispa.
Sesión nisqayku tukukunanpaqña chayaykuña. Gracias kayta qatisqaykimanta.Qhawayta atiyku imaynatachus JWT
tokenkuna compacto kanku chaymanta ancha aswan pisi verboso kanku XML kaqninkumanta, SAML
tokenkunamanta. Rikuyku imayna facil kaqta tokenkuna ruway chaymanta llamk'achiyta wakin autorizacionkunata wakin métodokuna necesitasqankuta tarinaykupaq chaymanta imayna chayman chayayku huk firmasqa token kaqnintakama.I tarini ichaqa ancha importante huk yuyayta imayna JWT
llamk'asqanmanta. Munaymanmi, kaywan, allin riqsichiyta quykichik imayna JWT
tokenkuna llamkasqankumanta.Aswan allin yuyayta tarinaykipaq imayna tukuy kay llamkasqanmanta, yuyaychaykichik pukllanaykipaq chay implementasqa pruebakuna cypress
nisqawan. Kayqa huk sumaq ñanmi imayna mañakuykuna ruwasqa kaqta chaymanta ima pruebasqayku chaymanta ima suyasqa kaqta qhawanapaq. Chaymantataq aswan allin yuyayta tarinki imarayku wakin llamk'aqkuna wakin ruwaykunata ruwanankupaq chayanku wakintaq mana.Kay ruwanamanta llapa pukyuta GitHub kaqpi churarqani Suyachkani kay qillqasqawan kusisqa kasqaykita imaynachus ñuqa qillqaypi kusisqa karqani it.Gracias leesqaykimanta!