Working with data from custom Spring MVC controller

Our system is being integrated with another system that doesn’t support Oath2, so I had to make a custom spring MVC controller with our own authentication. Everything works as expected, but now I need to work with some data. The controller is located in the web module. When I try to use the DataManager I get “No security context bound to the thread”. I tried to create a bean in the global module but that doesn’t have access to the EntityManager either. Any idea how I can overcome these security restictions?

Okay so I have managed to set a security context with the following code and I can now access the DB as a admin.

@RequestMapping(path = PATH, method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<String> doSomething(HttpServletRequest request) {

        WebAuthConfig webAuthConfig = configuration.getConfig(WebAuthConfig.class);
        UserSession systemSession;
        try {
            systemSession = loginService.getSystemSession(webAuthConfig.getTrustedClientPassword());
        } catch (LoginException e) {
            throw new RuntimeException("Error during system auth");
        }
        AppContext.setSecurityContext(new SecurityContext(systemSession));

        // After this I authenticate this request, do business logic and work with data
        return new ResponseEntity<String>("{\"message\": \"success\"}", HttpStatus.OK);
    }

Is this a safe way of doing it? Should I set the securitycontext on each request or should it maybe only be done once, after construction of controller?

Hi,

You do it right, the security context must be set for each invocation. Just better use TrustedClientService because LoginService is deprecated in the latest versions of the framework and will be removed in 7.1.

@Inject
protected TrustedClientService trustedClientService;

@Inject
protected Configuration configuration;

public ResponseEntity<String> doSomething(HttpServletRequest request) {
    String trustedClientPassword = configuration.getConfig(WebAuthConfig.class).getTrustedClientPassword();
    UserSession systemSession = trustedClientService.getSystemSession(trustedClientPassword);
    SecurityContext securityContext = new SecurityContext(systemSession);
    SecurityContext previousSecurityContext = AppContext.getSecurityContext();
    AppContext.setSecurityContext(securityContext);
    try {
        // your business logic here
    } finally {
        AppContext.setSecurityContext(previousSecurityContext);
    }
}
1 Like