Spring Security with Token Based Authentication

Posted By : Vishal Kumar | 20-Aug-2017

Spring Security is a lightweight security framework. With the help of Spring Security developers are able to perform role based authentication very easily. Here is how I was able to implement token based authentication and basic authentication. For implementing spring security with simplest way we have to create 1 security config file and 2 filters for authentication.

1. SecurityCofig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

    @Override
    public void configure(final AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(this.participantService).passwordEncoder(this.passwordEncoder());
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception
    {

        //Implementing Token based authentication in this filter
        final TokenAuthenticationFilter tokenFilter = new TokenAuthenticationFilter();
        http.addFilterBefore(tokenFilter, BasicAuthenticationFilter.class);

        //Creating token when basic authentication is successful and the same token can be used to authenticate for further requests
        final CustomBasicAuthenticationFilter customBasicAuthFilter = new CustomBasicAuthenticationFilter(this.authenticationManager() );
        http.addFilter(customBasicAuthFilter);

    }
}

2. TokenAuthenticationFilter.java

    public class TokenAuthenticationFilter extends GenericFilterBean
    {


        @Override
        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
                throws IOException, ServletException
        {
            final HttpServletRequest httpRequest = (HttpServletRequest)request;

             //extract token from header
            final String accessToken = httpRequest.getHeader("header-name");
            if (null != accessToken) {
           //get and check whether token is valid ( from DB or file wherever you are storing the token)

          //Populate SecurityContextHolder by fetching relevant information using token
               final User user = new User(
                            "username",
                            "password",
                            true,
                            true,
                            true,
                            true,
                            authorities);
                    final UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authentication);

            }

            chain.doFilter(request, response);
        }

      }

3. CustomBasicAuthenticationFilter.java

@Component
public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {


    @Autowired
    public CustomBasicAuthenticationFilter(final AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void onSuccessfulAuthentication(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response, final Authentication authResult) {
        //Generate Token
        //Save the token for the logged in user
        //send token in the response
        response.setHeader("header-name" , "token");


    }

}

Our CustomBasicAuthenticationFilter is used for username and password authentication we can remove this filter and create a normal service for generation token and authentication username and password.

After success of basic authentication request will be redirected to onSuccessfulAuthentication where we generate and send the token in response. Here we are sending token with response header.

If user hit any api that have a token in header, then the request will go through TokenAuthenticationFilter first before attempting to try Basic Authentication.

 

Conclusion: I think this is the simplest way for implementing spring security. We can secure our RestApis with @Secured annotation so that only the permitted Role can access that perticular api.

 

Note: Below dependancy is required for Spring Security.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

About Author

Author Image
Vishal Kumar

Vishal Kumar is Master in Computers Application. He has good technical skills in Java and always motivated to learn new things.

Request for Proposal

Name is required

Comment is required

Sending message..