Custom Authentication tip from cuba does not work in jmix

Hi all.
On the page Security :: Jmix Documentation
I see the tip for a custom authentication, for us it works on cuba platform but there are no the same classes and beans in jmix to reproduce the tip.
Do you know how I can return an access token for custom endpoint (there is additional business logic before generation)?

Hi, if you need to do something before token generation, you may try adding an interceptor to the authorization server endpoints.

Create the interceptor:

public class MyTokenEndpointInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //your code
    }
}

and the AuthorizationServerConfigurer:

@Component
public class MyAuthorizationServerConfigurer implements AuthorizationServerConfigurer {
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.addInterceptor(new MyTokenEndpointInterceptor());
    }
}

In order to use the spring security oauth2 classes in your code, you need to explicitly add the dependency in the project build.gradle file, because jmix oauth2 module doesn’t transitively expose this dependency:

implementation 'org.springframework.security.oauth:spring-security-oauth2'

No, I don’t need add an action before or after authorization.

I need generate an access token programatically, for example, I want to generate an access token in a custom endpoint with some business logic.

I can do it in cuba (CUBA REST API) via the code:

// generate token for "promo-user"
OAuthTokenIssuer.OAuth2AccessTokenResult tokenResult = oAuthTokenIssuer.issueToken("promo-user", messageTools.getDefaultLocale(), Collections.emptyMap());
OAuth2AccessToken accessToken = tokenResult.getAccessToken();

But how can I reproduce the same logic it in Jmix?

I don’t see an easy way to obtain access tokens programmatically. It would be possible if some Spring security OAuth2 services were defined as Spring beans. Currently, services like TokenGranter or TokenServices are instantiated in the OAuth2AuthorizationServerConfigurer and can’t be reused elsewhere in the application.
I’ve created an issue for this. The issue description contains code samples explaining how obtaining access tokens might look after we fix the issue.

1 Like