Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:REST spring security - Manually authenticating a new user and getting access token

I am writing a RESTful webservice on grails, using rest spring security api. All good... now I want to login a user on registration, there is a registration action, and up on registration completion, i would like to login that user. I found:

springSecurityService.reauthenticate(username) method 

but that only login the user, but doesnt create access token in authentication_token table.

Is there other possible way to login and get the access token for that user?

like image 619
sufyan.shoaib Avatar asked Aug 28 '14 07:08

sufyan.shoaib


People also ask

How do I authenticate REST API in Spring Security?

The following Spring security setup works as following: The user logs in with a POST request containing his username and password, The server returns a temporary / permanent authentication token, The user sends the token within each HTTP request via an HTTP header Authorization: Bearer TOKEN .


1 Answers

The plugin is designed for applications where the frontend (a pure HTML/JS client using, for example, AngularJS) is separated from the backend (your Grails app). In such scenario, the backend has to send back the frontend the access token, and the frontend has to store it somehow (usually using local storage or cookies), to pass it as an HTTP on every subsequent request.

You can do something like this in your controller:

class RegisterController {

    def springSecurityService
    def tokenGenerator
    def tokenStorageService

    def register() {
         //do stuff
         springSecurityService.reauthenticate(username)
         String tokenValue = tokenGenerator.generateToken()
         tokenStorageService.storeToken(tokenValue, springSecurityService.principal)

         redirect url: "http://example.org/?access_token=${tokenValue}"
    } 
}

Then, the frontend can grab the token from the URL and pass it on every subsequent API request.

like image 181
Álvaro Sánchez-Mariscal Avatar answered Sep 28 '22 10:09

Álvaro Sánchez-Mariscal