Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

oauth 2.0 - OAuth2 flow for securing a REST API

I have Keycloak for authentication and authorization of multiple applications (a web page and a REST API). From my understanding the flow for the web page when using OAuth2 authentication_code grant type is as follows:

enter image description here

In this flow, in the second step (the one in red) the resource owner logs in because she/he were redirected to the login page of Keycloak. This flow is clear to me and is working well.

But, with the REST API I don't know what is the process to authenticate and authorize the user (resource owner), because there isn't a browser to redirect him to the login page of Keycloak. So, I tried with the password grant type and it worked, but then I realized that this grant type is deprecated. So I tried again with the authorization_code grant type but can't make it work. I am trying to get the token using the following request:

URL: http://localhost:8080/auth/realms/somerealm/protocol/openid-connect/token

Body:

username: someuser
passwoord: somepassword
grant_type: authorization_code
client_id: someclient
secret: somesecret

The problem is that I am receving the following response:

{
    "error": "invalid_request",
    "error_description": "Missing parameter: code"
}

I know I have something wrong in the request (and in my understanding of OAuth2), but I have read a lot and can't discover what it is.

question from:https://stackoverflow.com/questions/65867508/oauth2-flow-for-securing-a-rest-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

API (backend) doesn't need any login flow usually. It just needs to verify token and then it executes requested operation or it denies it (response code 401 - problem with authentication / 403 - problem with authorization). It doesn't redirect to auth server.

Client, which is using API must obtain token before API request. It can be done by the frontend (e.g. SPA with The Authorization Code Flow + PKCE) and then frontend maintains state (token refresh, error codes from the API, ...).

If you don't have any frontend, then procedure how to get token must be part of API specification. For example see swagger doc: https://swagger.io/docs/specification/authentication/oauth2/

The Client credentials flow should be used machine to machine authentication, so it's not a solution if you need to know user identity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...