3

I've been looking for a way to authenticate a user via REST controller (URL params). The closest thing to do so is the following:

@Controller
@RequestMapping(value="/api/user")
public class UserController extends BaseJSONController{

    static Logger sLogger = Logger.getLogger(UserController.class);

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody String login(@RequestParam(value="username") String user, @RequestParam(value="password") String pass) throws JSONException {
        Authentication userAuth = new UsernamePasswordAuthenticationToken(user, pass);
        MyCellebriteAuthenticationProvider MCAP = new MyCellebriteAuthenticationProvider();

        if (MCAP.authenticate(userAuth) == null){
            response.put("isOk", false);
        }
        else{
            SecurityContextHolder.getContext().setAuthentication(userAuth);
            response.put("isOk", true);
            response.put("token", "1234");
        }
        return response.toString();
    }

}

However, this doesn't create a cookie. Any idea or a better way to implement what I want to achieve?

1
  • if your aim is to save the session's information to a cookie based token, you're probably looking for Remember-Me Authentication. Commented Nov 28, 2012 at 19:15

1 Answer 1

3

Firstly, you should not do this manually:

SecurityContextHolder.getContext().setAuthentication(userAuth)

It is better to employ special filter responsible for authentication, setting security context and clearing it after request is handled. By default Spring Security uses thread locals to store security context so if you don't remove it after client invocation, another client can be automatically logged in as someone else. Remember that server threads are often reused for different request by different clients.

Secondly, I would recommend using basic or digest authentication for your RESTful web service. Both are supported by Spring Security. More in docs http://static.springsource.org/spring-security/site/docs/3.1.x/reference/basic.html

And finally, remember that RESTful web service should be stateless.

Also remember that Spring Security documentation is your friend. :-)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I've moved the authentication to a token based stateless authentication

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.