3

I am trying to get current user inside a controller in a Grails 3.0.3 application. I have used this repo as a base for my security setup - security is GORM based. I am using following line in build.gradle in order to include Spring Security Framework:

compile "org.springframework.boot:spring-boot-starter-security"

but when I try to inject springSecurityService like it was recommended in other SO threads (see for example: this one) in my controller, I get only a null object. It is not initiated like it should be.

class RestapiController {
    def springSecurityService

    def currentUser(){
        def user = springSecurityService.currentUser
        render user
    }
}

How can I inject springSecurityService into a controller in Grails 3.0.3?

UPDATE: In the end I used following line to get the current user:

SecurityContextHolder.context.authentication.name
Community
  • 1
  • 1
Piotr Zakrzewski
  • 3,591
  • 6
  • 26
  • 28

1 Answers1

4

springSecurityService isn't part of Spring Security, it's in the Grails spring-security-core plugin. Spring Security doesn't have the concept of the "current user". You can access the current Authentication and get the username, password, enabled, etc., but there's nothing in the framework that gets you back to the source object that was used to populate the authentication (in Grails + spring-security-core this is often a User domain class instance) - that would have to be done in your application code.

This weekend I released an initial version of the plugin that works with Grails 3, version 3.0.0.M1. The documentation is here. There's a short tutorial in the docs to help get you started, and you might also check out this sample app using the plugin in Grails 3.

Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • Also note that if you only need this in a controller, you can skip injecting `springSecurityService` and use the [getAuthenticatedUser() metaclass method](https://grails-plugins.github.io/grails-spring-security-core/guide/controllerMetaClassMethods.html) that's injected into all controllers (or the analagous `authenticatedUser` property). – Burt Beckwith Aug 17 '15 at 18:07
  • Thanks Burt! I also added an update with code I used in the end to get the name of the current user. – Piotr Zakrzewski Aug 18 '15 at 07:16
  • 1
    That's very different. `springSecurityService.currentUser` retrieves the domain class instance from the database, and should only be used when you need domain class data that isn't available from the `Authentication`. If you only need the username, then your code is fine, and a more compact option is `springSecurityService.principal.username`. If you can't dependency-inject `springSecurityService` then something is broken. Of course that's assuming that you're using the spring-security-core plugin - if you're using the Spring Boot starter, then yes, you have to do a lot more work in your app. – Burt Beckwith Aug 18 '15 at 07:18