{"id":18291962,"url":"https://github.com/xxlabaza/groovy-auth2-sample","last_synced_at":"2025-04-09T07:53:16.777Z","repository":{"id":94549536,"uuid":"51717773","full_name":"xxlabaza/groovy-auth2-sample","owner":"xxlabaza","description":"Groovy oAuth2 Sample","archived":false,"fork":false,"pushed_at":"2016-02-14T22:51:31.000Z","size":6,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-02-15T02:17:06.860Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Groovy","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/xxlabaza.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-02-14T22:43:41.000Z","updated_at":"2016-02-14T22:44:06.000Z","dependencies_parsed_at":"2023-05-02T01:36:32.808Z","dependency_job_id":null,"html_url":"https://github.com/xxlabaza/groovy-auth2-sample","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xxlabaza%2Fgroovy-auth2-sample","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xxlabaza%2Fgroovy-auth2-sample/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xxlabaza%2Fgroovy-auth2-sample/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xxlabaza%2Fgroovy-auth2-sample/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xxlabaza","download_url":"https://codeload.github.com/xxlabaza/groovy-auth2-sample/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247999850,"owners_count":21031044,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-05T14:15:49.469Z","updated_at":"2025-04-09T07:53:16.752Z","avatar_url":"https://github.com/xxlabaza.png","language":"Groovy","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n# Описание\n\n## Запуск\n\n```bash\n$\u003e spring run authorization.groovy -- --spring.profiles.active=authorization \u0026\n$\u003e spring run service.groovy -- --spring.profiles.active=service \u0026\n$\u003e spring run zuul.groovy -- --spring.profiles.active=zuul \u0026\n```\n\nПроверка работы, авторизация пользователем:\n\n```bash\n$\u003e curl \"http://localhost:9003/login?username=artem\u0026password=artem_password\" | jq .access_token\n$\u003e export TOKEN=\u003ctoken_value\u003e\n$\u003e curl localhost:9003/service/authorized -H \"Authorization: Bearer $TOKEN\"\nOnly authorized clients see this\n$\u003e curl localhost:9003/service/inner -H \"Authorization: Bearer $TOKEN\"\nOnly authorized clients with inner scope see this\n$\u003e curl localhost:9003/service/public -H \"Authorization: Bearer $TOKEN\"\nOnly authorized clients with public scope see this\n$\u003e curl localhost:9003/service/user -H \"Authorization: Bearer $TOKEN\"\nOnly clients with role USER see this\n$\u003e curl localhost:9003/service/admin -H \"Authorization: Bearer $TOKEN\"\n{\"error\":\"access_denied\",\"error_description\":\"Access is denied\"}\n```\n\nПроверка работы, авторизация приложением:\n\n```bash\n$\u003e curl -v artem:artem_password@localhost:9003/uaa/oauth/authorize \\\n     -d response_type=token \\\n     -d client_id=third_party_app \\\n     -d redirect_uri=http://example.com \\\n     -d scope=public_scope \\\n     -d state=3213\n$\u003e export TOKEN=\u003ctoken_value\u003e\n$\u003e curl localhost:9003/service/authorized -H \"Authorization: Bearer $TOKEN\"\nOnly authorized clients see this\n$\u003e curl localhost:9003/service/inner -H \"Authorization: Bearer $TOKEN\"\n{\"error\":\"access_denied\",\"error_description\":\"Access is denied\"}\n$\u003e curl localhost:9003/service/public -H \"Authorization: Bearer $TOKEN\"\nOnly authorized clients with public scope see this\n$\u003e curl localhost:9003/service/user -H \"Authorization: Bearer $TOKEN\"\nOnly clients with role USER see this\n$\u003e curl localhost:9003/service/admin -H \"Authorization: Bearer $TOKEN\"\n{\"error\":\"access_denied\",\"error_description\":\"Access is denied\"}\n```\n\n## [Сервис Авторизации](https://github.com/xxlabaza/groovy-auth2-sample/blob/master/authorization.groovy)\n\n### Пользователи\n\nСписок пользователей и их роли с паролями в сервисе захардкожены, в классе **GlobalAuthenticationConfiguration**:\n\n```java\nauthenticationManagerBuilder.inMemoryAuthentication()\n            .withUser('artem')\n            .password('artem_password')\n            .roles('USER')\n        .and()\n            .withUser('admin')\n            .password('admin')\n            .roles('ADMIN')\n```\n\nДля того, что бы загружать пользователей из стороннего сервиса, необходимо реализовать свою имплементацию абстрактного класса [AbstractUserDetailsAuthenticationProvider](http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/apidocs//org/springframework/security/authentication/dao/AbstractUserDetailsAuthenticationProvider.html) и использовать его так:\n\n```java\nauthenticationManagerBuilder\n        .authenticationProvider(\u003cmy_implementation\u003e)\n```\n\n### JWT\n\nПриватный и публичный **JWT**-ключи указаны в настройках [application.yml](https://github.com/xxlabaza/groovy-auth2-sample/blob/master/application.yml) в явном виде, но что бы хранить их болле надёжно - необходимо создать [keystore](http://docs.oracle.com/cd/E23943_01/core.1111/e10105/wallets.htm#ASADM2021).\n\nСоздаём **keystore**:\n\n```bash\nkeytool -genkeypair \\\n  -alias keystore_alias \\\n  -keyalg RSA \\\n  -dname \"CN=Artem Labazin,OU=jwt,O=ArtLab,L=SPb,S=SPb,C=RU\" \\\n  -keypass ArtLab90 \\\n  -keystore keystore.jks \\\n  -storepass ArtLab90\n```\n\nПолучаем публичный ключ:\n\n```bash\nkeytool -list -rfc --keystore keystore.jks | openssl x509 -inform pem -pubkey\n```\n\nТак же необходимо заменить настройки **jwtAccessTokenConverter**:\n\n```java\n@Bean\nJwtAccessTokenConverter jwtAccessTokenConverter () {\n    def converter = new JwtAccessTokenConverter()\n    def keyPair = new KeyStoreKeyFactory(\n            new ClassPathResource('keystore.jks'),\n            'ArtLab90'.toCharArray()\n    ).getKeyPair('keystore_alias')\n    converter.setKeyPair(keyPair)\n}\n```\n\n### Хранение токенов\n\nДля того, что бы не хранить информацию о генерируемых токенах и сервисах-клиентах в памяти, а хранить их в БД, необходимо произвести следующие настройки:\n\nЗаменить **tokenStore**:\n\n```java\n@Bean\nTokenStore tokenStore () {\n    new JdbcTokenStore(dataSource)\n}\n```\n\nСоздать **clientDetailsService**:\n\n```java\n@Bean\nClientDetailsService clientDetailsService () {\n    def clientDetailsService = new JdbcClientDetailsService(dataSource)\n    clientDetailsService.setPasswordEncoder(passwordEncoder())\n    return clientDetailsService\n}\n\n@Bean\nPasswordEncoder passwordEncoder () {\n    new BCryptPasswordEncoder(10)\n}\n```\n\nПеренастроить **clientDetailsService**:\n\n```java\n@Override\nvoid configure (ClientDetailsServiceConfigurer clients) throws Exception {\n    clients.withClientDetails(clientDetailsService())\n}\n```\n\n## [Ресурс сервис](https://github.com/xxlabaza/groovy-auth2-sample/blob/master/service.groovy)\n\n## [Шлюз](https://github.com/xxlabaza/groovy-auth2-sample/blob/master/zuul.groovy)\n\n## Полезные ссылки\n\n* [Как работает JWT](http://jwt.io/introduction/)\n\n* [Работа с social](https://spring.io/guides/tutorials/spring-boot-oauth2/)\n\n* [Описание работы с oAuth2](http://callistaenterprise.se/blogg/teknik/2015/04/27/building-microservices-part-3-secure-APIs-with-OAuth/)\n\n* [Пример проекта с oAuth2](https://github.com/dynamind/spring-boot-security-oauth2-minimal)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxxlabaza%2Fgroovy-auth2-sample","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxxlabaza%2Fgroovy-auth2-sample","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxxlabaza%2Fgroovy-auth2-sample/lists"}