Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discriminating users without authentication in Spring

I am currently writing a comment system for websites with Spring Boot that will be based on a simple REST API.

In order to let people delete or update comments they posted earlier, I'd like to store a unique token in a Cookie to remember/identify them. Users are not required to register in order to post comments. When a user deletes the cookie or when it expires, there will be no way to get back permissions to delete/modify a comment.

Of course it is possible to implement such a functionality by myself using filters, but I wanted to know if there is a standard way for doing this in Spring (probably using Spring Security)? I thought this would be a common scenario, but all examples I could find include authentication information like username/password.

like image 736
pvorb Avatar asked Dec 13 '15 23:12

pvorb


2 Answers

This can be achieved by creating a custom implementation of SecurityContextRepository.

  1. Create an implementation of SecurityContextRepository that loads authentication information from a cookie.
  2. Create an implementation of AuthenticationProvider to check if the cookie contains a valid value. A prefix and/or a suffix may be added to the cookie value and the value may be encrypted to ensure authenticity and prevent impersonation.

I have a sample app that demonstrates the components to be implemented. The sample stores authentication information in an in-memory cache but it can be stored in HttpSession or any other data store as required. The code is in Scala but should be readable for Java programmers.

like image 112
manish Avatar answered Nov 07 '22 06:11

manish


With Spring Security you can write a custom Filter to achieve the functionality that you need. For example check RestTokenValidationFilter, this one reads the Authorization Header and validates whether the token is valid or not by looking the token in database.

You could use the similar pattern. Instead of reading the Authorization Header, you could read the cookie and Authenticate the User.

like image 4
JChap Avatar answered Nov 07 '22 05:11

JChap