Manikandaraj Srinivasan
Manikandaraj Srinivasan

Reputation: 3647

Spring Security - Authenticating with Authorization Header

I'm trying to setup Authorization for my HTTP Requests in Spring Boot with Sprint Security framework. I'm new to Spring Security and I couldn't find any documentation for my case.

I understand we have to override WebSecurityConfigurerAdapter methods - configure(AuthenticationManagerBuilder ) & configure(HttpSecurity). It works fine for some basic cases. However for the Project i'm working on, i'm looking for a specific use case.

This is the flow i'm trying to setup. My front-end and back-end are hosted in different domains, so i'm looking for Authorization with Cross Origin as well. Login by posting to the REST API, [ For this API alone, there should be no Authorization]

https://atlan.co/login - POST
{
'user_name': 'mani',
'password': 'mani'
}

/login REST Controller receives the username and password, does LDAP Auth, once Authentication Successful, creates a Token and stores in an in-memory DB [Redis Preferably], with the username, user_email mapped to the token. And sends a login success message, with Set Authorization Cookie - Token to the browser.

After that, each request from Browser will be accompanied with the Authorization header, with the token value.

The above part, i'm able to work it out. When the request comes in, I want to setup Spring Security so that it will read Authorization Header and get username, useremail from Redis in case if the token exists, pass the username, useremail to the Controller and the usual flow of the controller. In case, if the token didn't exists, should throw 401 UnAuthorized HTTP Error in JSON format, along with a custom message.

I've tried reading the questions in Stackoverflow, Spring documentation, but I couldn't work it out. Would be very helpful, if someone can shed light on this.

Upvotes: 2

Views: 12856

Answers (1)

Qwer Izuken
Qwer Izuken

Reputation: 639

You need to add a custom spring filter to process your Authorization header

public class YourAuthenticationFilter extends OncePerRequestFilter
{

  @Override
  protected void doFilterInternal(HttpServletRequest request,
    HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException
  {

    String xAuth = request.getHeader("Authorization");//here is your token value
    //Place here your redis checks, get Authentication and so on
    SecurityContextHolder.getContext().setAuthentication(auth);

    filterChain.doFilter(request, response);
  }

}

In your security config:

@Override
protected void configure(HttpSecurity http) throws Exception
{
  http
    //...
    .addFilterBefore(new YourAuthenticationFilter(), BasicAuthenticationFilter.class)
    //...
}

Upvotes: 4

Related Questions