Biểu trưng OpenStreetMap OpenStreetMap

Moving Python scripts to OAuth2

Do Zverik đăng vào 14 tháng 10 năm 2023 bằng English.

Spent today writing a new Python library. Super useful if you are making command-line OSM processing scripts:

https://github.com/Zverik/cli-oauth2

With it you add OAuth2 authentication in just one line of code (well, 3-4 after PEP8).

auth = OpenStreetMapAuth(
    client_id, client_secret, ['read_prefs', 'write_api']
).auth_server(token_test=lambda s: s.get('user/details'))

user_name = auth.get('user/details.json').json()['user']['display_name']

This line starts a local web server, opens OSM OAuth page, catches the redirect, stores the token on disk, and returns a requests session that also prepends the API endpoint to its parameter.

Not very secure — but it doesn’t need to be. One drawback is when publishing sources to github, you would need to publish your client credentials as well. Or just read then from a config file, idk.

Already updated my Simple Revert and OSM to Sandbox scripts to use it. Hope it helps!

Biểu tượng thư điện tử Biểu tượng Bluesky Biểu tượng Facebook Biểu tượng LinkedIn Biểu tượng Mastodon Biểu tượng Telegram Biểu tượng X

Thảo luận

Bình luận của kwiatek_123 vào 15 tháng 10 năm 2023 lúc 10:49

Is it a good idea to use this in a library that can be used in other python tools? Can you say more about saving credintials in the configuration file?

Bình luận của Zverik vào 15 tháng 10 năm 2023 lúc 11:42

Of course, should be fine. It stores a user token to $HOME/.config/PythonCliAuth/tokens.json on Linux, or an equivalent on other systems. Dictinary hashes are provider id (“openstreetmap”) + oauth client id for the app. So as long as you make library users provide you with a client id, you’ll be fine.

Bình luận của fititnt vào 20 tháng 10 năm 2023 lúc 06:34

Have things kind of thing already done is helpful, in special if the same programming language the dev like me would likely to do cli tools.

(All my tools still read-only and, if any, they export files to be used with OSM editors)

Bình luận của fititnt vào 20 tháng 10 năm 2023 lúc 06:38

By the way, looking at the https://github.com/Zverik/cli-oauth2/blob/main/src/oauthcli/providers.py is clear there’s some providers.

Did you know if OpenStreetMap Wiki (mediawiki) and Wikidata (the mediawiki/wikibase) have Oauth2? If yes, maybe consider implementing it.

Bình luận của Zverik vào 20 tháng 10 năm 2023 lúc 06:48

For the wiki, you should use tokens it provides: osm.wiki/Special:ApiSandbox#action=query&format=json&meta=tokens&type=login

I believe it’s the same for wikidata, since it also uses MediaWiki (I guess?)

Đăng nhập để nhận xét