How we can implement refresh token with /authorize and /token in grails

i want to generate refresh token with ouath2 api from server.but how we can implement it with grails?

I can’t speak for grails specifically, but as long is the application is configured to allow use of the Refresh token grant, you can get refresh tokens returned from the token endpoint (when using authorization code flow) if you request the “offline_access” scope in your authorize request.

More details about refresh tokens found in our guide here.

@mraible, have any ideas for how to do this with grails?

We do have a Grails tutorial on the developer blog: Build Server Side Authentication in Grails with OAuth 2.0 and Okta | Okta Developer

thanks…mraible !!
But to get a refresh token, i wanted to call following api
authorizeUrl: ‘https://{yourOktaDomain}/oauth2/default/v1/authorize’
which will return authorization_code in browser url like
yourApp:/callback?code=BdLDvZvO3ZfSwg-asLNk&state=state-8600b31f-52d1-4dca-987c-386e3d8967e9
so how can i captured this authorization_code from URL in grails??
is there any way to get auth_code from browser to server??

@andrea Already explained how to get a refresh token. It’s all about passing in the offline_access scope and configuring your Okta OIDC app to allow refresh tokens. From there, everything should work.

Have you tried the Grails tutorial I linked to? You might be making this harder than you need to. I think the Grails code in the tutorial will work and you don’t have to worry about the code returned or talking to another endpoint.

In our angular application we have implemented okta for user authentication for every request that hit our application.
Each request is authenticated using token generated by okta and it gets validated through introspect api and it works fine.
With these user interactions if the token gets expired we redirect user to home page so that new token gets generated. Now in this scenario, instead of redirecting user to home page, we need to refresh the token without intervention of the user and to achieve this need to generate refresh token from back end, so how the token can be refreshed offline without letting the user know about it

What is your use case that would make you/your users expect that the user would know about the refresh token being used to extend their session? Instead of having to redirect the user back to the home page to re-authenticate, you will instead have your application simply fetch a new token for them without them needing to re-authenticate or do anything else.

Also, the “offline” part of the offline_access scope is a little confusing. API calls still need to be made to Okta to get a new token (via the /token endpoint), but with an offline access token, the user does not need to be present/logged in to get new tokens, they just need a valid refresh token. See OpenID spec here for details about this scope

I have tried that tutorial, and it’s now outdated due to the Okta Grails plugin no longer being available. The bintray repository where the Okta Grails plugin was hosted, has been shut down. Trying that project, the build fails because of that Okta dependency, since the repository no longer exists.

Without it, another way has to be implemented to use Okta.
It will be nice to have that update, ideally for people like me working on legacy applications using Grails as the back-end. Most of the applications I work with are in Grails 2.x to Grails 3.x. I hope the Okta team will also think about us.

Can you share your logic for the validation of the REST API from the front-end, I am working on a Grails back-end with a react front-end, however I am not sure what’s the best process to deal with the implementation of the rest services to handle Okta.

A simple example will be nice to see.

Thank you.

I haven’t touched Grails since the pandemic started, but shouldn’t you really ought to be able to leverage the Java authentication SDK to do the auth-code-flow? I used to teach Grails all the time and linked a lot of Java to it.

1 Like

On your second post here, define “validation of the REST API from the front-end”, I’m not sure what you are trying to achieve. I’ll be happy to help you out with it though.

1 Like

I am using a simple Enterprise Grails 2.4.5 secured by Okta default generated /users API through the “url mappings” configuration.
I am able to see the REST JSON response on the browser going through Okta (probably because Okta is implemented throughout the enterprise) without any issue. however when I have an Okta secured React Front-End app that calls that API, a CORS error appears.

I also tried to test those default generated APIs on Postman and I am getting a 404 not found error.

I am using an access token inside the header in all scenarios.

The app is using a custom Enterprise Grails Okta OAuth plugin.

All APIs require authentication through the @Secured (IS_AUTHENTICATED_FULY) from the spring-security-core plugin that works with that custom Okta grails plugin through the Grails controller classes.

The React front-end also uses Okta for authentication.

I haven’t implemented any token decoder and verifier to check the validity of the token before returning the response, and even without that, it works in the browser.

I am just trying to understand why I can’t even see the response on Postman.

I followed one of the official examples from Okta (“Custom Okta Spring Boot Login Page”), and I also had a CORS issue. I had to add the custom endpoint “8080/custom-login” as a trusted origin inside my personal private okta admin console under “Security/API/Trusted Origin/Add Origin”.

I just wonder if that’s something I have to do for that Enterprise Grails application and add that endpoint inside the enterprise Okta Admin Console.

Thank you very much, I hope that helps clarify a bit.

The project I am working on is on Groovy, but since it’s based on Java, I am sure it’s possible to use Java since there are a lot of Okta dependencies on maven that work well with Spring/Spring Boot/Java.
Ideally don’t want to add another Okta dependency since I am using already a custom OAuth Plugin that secures the application with Okta.

Mostly looking for the logical steps to implement the most basic controller and secure it with Okta that can accept request from a React App.

If I am reading this correctly it seems that you are a) trying to use the Okta API from a grails (server-side) app, b) from a client-side React app, and c) from Postman to check things. Which can be confusing because there are three different ways to do things here. Sorry this is going to be a bit long, and let’s back away from any framework for the moment which just confuses the situation:

  1. On a server-side app we normally issue an API token to access the Okta API. This is a sensitive token, it is the only credential needed with administrative access to the API. The API URL is always https://[your tenant server]/api/v1/[something like users. See this page for details: Create an API token | Okta Developer, and here is the full API documentation: Core Okta API | Okta Developer. An API token can be used to access both groups of APIs, authentication and management.

  2. On a client-side app (browser or device native) we never use an API token because it’s too risky and we don’t trust the user. So once the user is authenticated the app that initiated authentication can get an ID token and access token for the API. The ID token describes the user, the access token is used to make API calls. Now there are some limitations here:

    a. The client-side app can only access the authentication API, Authentication | Okta Developer, or the OAuth API OpenID Connect & OAuth 2.0 API | Okta Developer.

    b. The client-side application URL (protocol, server, and port number only) has to be registered as a trusted origin in Okta. Specifically if this isn’t done then Okta doesn’t respond with the access-control-allow-origin header in the response and the browser sees the CORS error.

  3. Postman complicates things because there are two ways to use it. First off, if you are getting a 404 error your URL isn’t right (see above).

    a. Postman can be used with an API token to access all of the APIs. Here are all the postman collections to do it: Postman Collections | Okta Developer.

    b. Postman can be used to make API calls using an access token, but you have to jump through a couple of hoops to make it work.

    One way is to install the Postman Interceptor in your browser and then turn it on in both the browser and Postman. You need the browser to authenticate to the Okta tenant, and the interceptor traps the cookies and tokens and then they can be passed back to Okta in the Postman requests. So you don’t actually need the access token for most of these API calls, because the session cookie tells Okta who you are. But, there is a gotcha: you have to set the “origin” header in Postman to match the original application that authenticated for POST and PUT requests or Okta will reject them.

    The second way is to capture the access token from an authentication and then pass it in the header in Postman as you say you are doing. Again, 404 is probably a URL issue. But, the other gotcha here is that access tokens have a short lifetime. You can check it by pasting the token string into the form at https://token.dev.

    So if you want a confirmed example, you can set up the Interceptor and login to my demo dev server https://dev-77167726.okta.com as “annebonny” with “P!rates17”. This account cannot access the dashboard and has no privileges, and it’s just a demo tenant so no security risk for me :slight_smile: Then have Postman do a GET at https://dev-77167726.okta.com/api/v1/users/me and you’ll get the profile for Anne.

Back to the end of your question: do you have to enable CORS in Okta for the Grails app? Not if you are using an API token, but probably if you are using an access token (and set the “origin” in the header properly). I haven’t actually tested that :slight_smile:

Now for your last post, that looks like a whole different problem unless I’m reading it wrong. Do you want to build your own API (I assume in Grails) and secure it with an access token issued to the React app by Okta?

1 Like

I was able to access most of the Okta APIs using an access token from Postman as well as my default Grails APIs created in UrlMappings.groovy, using the client_credentials grant_type and the authorization_code grant_type:

 '/api/v1/users'(resources:'user')
        "/api/v1/user/$username"(controller:'user', action:"findByUsername", method: 'GET')
package com.xxx.xxx.controller
import grails.converters.JSON
import grails.rest.RestfulController
import grails.plugin.springsecurity.annotation.Secured

@Secured(['IS_AUTHENTICATED_FULLY'])
class UserController extends RestfulController
{
    static responseFormats = ['json']

    UserController(){
        super(User)
    }

    def index(){
        def users = User?.list(max:5, sort: "username", order:"asc")
        render(users as JSON)
    }

    def show(){
        def user = User.findById(params?.id)
        render(user as JSON)
    }

    def findByUsername(String username){
        def userWithUsername = User?.findByUsername(params?.username?.toString())
        render(userWithUsername as JSON)
    }
}

However, for the Grails 2.4.5 APIs server-side APIs, I couldn’t use the Access Token obtained from the client_credentials grant_type, as it triggered an “Unauthorized 401 response”, most likely because the Access Token obtained through that grant type doesn’t contain any information about the user and I put an @Securedred annotation on my controller, hence requiring authentication first, before accessing any API.
I had to use the cookie created when the application launched from IntelliJ ( It’s a Grails 2.4.5 Web App that I am trying to convert into a Web Service with a separate React Front-End.) and automatically authenticated the user through Okta, and add it inside the header of the request without any access token (no oauth) to access my created APIs and get a JSON response.

I am now good on getting an Access Token and use it to access Okta APIs and my custom Server Side APIs. :white_check_mark:

b. The client-side application URL (protocol, server, and port number only) has to be registered as a trusted origin in Okta. Specifically if this isn’t done then Okta doesn’t respond with the access-control-allow-origin header in the response and the browser sees the CORS error.
I will try your suggested solutions to deal with CORS as well as go through all the other suggested solutions to have a better understanding.

I still have a CORS issue when the React Front-End tries to access the server-side APIs even with the Access Token (obtained after the user logged in successfully) that works on Postman and despite adding inside the header “Origin: http://localhost:3000”. “http://localhost:3000/” is a trusted origin inside Okta, whi is that?

I tried to do a POST Request on the Okta API “v1/trustedOrigins” to add the server-side APIs as Trusted Origins, however I got this error below:

{

    "errorCode": "E0000022",

    "errorSummary": "The endpoint does not support the provided HTTP method",

    "errorLink": "E0000022",

    "errorId": "oaeUwwz9JQ8ROeIkfvqSoYOHQ",

    "errorCauses": []

}:

Can you also check if my logic is correct when it comes to implementing the server side APIs? I want to make sure I am on the right track in terms of logic and flow.

Thank you very much for your time.

I ended up using the Grails CORS 1.1.0 plugin to deal with the CORS issue. I see that the server returns some headers, based on my configuration in the config.groovy file when the React makes an api call in the Response Headers.

cors.enable.logging = true // enable logging of failed requests
cors.url.pattern = '/api/v1/*'
cors.headers = ['Access-Control-Allow-Origin': 'http://localhost:3000', // Only allow access to that origin
				'Access-Control-Allow-Headers': '*',
				'Access-Control-Allow-Methods': 'GET, HEAD, TRACE, OPTIONS',
               ]

However there’s still a CORS issue because the browser doesn’t seem to get the status code 200 sent by the server.

How do you make sure that the browser sees that status? I can see the status in the browser when launching the back-end app as well as from the command line “curl”, however the React front-end is having that issue that’s preventing the front end from accessing the server services, because the back-end doesn’t return status code 200, despite that I wrote some code to return that status.

def index(){
        def users = User?.list(max:5, sort: "username", order:"asc")
        response.status = 200
        render(users as JSON)
    }

Is there something wrong with the code? Why isn’t the status returned back when the browser does it’s preflight check with “OPTIONS” header?
Am I supposed to add the “OPTIONS” header as an additional “method” in my urlMappins.groovy file? I will read more about the documentation and see if that’s an option. I thought the Cors Plugin would have handled that.

static mappings = {
        '/api/v1/users'(resources:'user')
        "/api/v1/user/$username"(controller:'user', action:"findByUsername", method: 'GET')

Thank you very much for your time.

I was able to fix the issue using the Grails Cors 1.3.0 plugin. Thank you very much for your help.