Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Spring Security:RESTful Authentication via Spring

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 1.16k
    Comment on it

    AuthenticationTokenProcessingFilter

    First we need to make security context where we define our Authentication Entry point and a filter for processing the token. Configuration xml will look something like this:

    <security:http realm="Authentication API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="SimpleAuthenticationEntryPoint">
        <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM&#95;LOGIN&#95;FILTER" />
        <security:intercept-url pattern="/authenticate" access="permitAll"/>
        <security:intercept-url pattern="/**" access="isAuthenticated()" />
    </security:http>
    
    <bean id="simpleAuthenticationEntryPoint"
        class="com.evon.spring.SimpleAuthenticationEntryPoint" />
    
    <bean id="authenticationTokenProcessingFilter"
        class="com.evon.spring.AuthenticationTokenProcessingFilter" >
        <constructor-arg ref="authenticationManager" />
    </bean>
    

    SimpleAuthenticationEntryPoint

    Now we need to create a simpleAuthenticationEntryPoint, which basically just returns a 401 Unauthorized code if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter.

    public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
            response.sendError( HttpServletResponse.SC&#95;UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
        }
    }
    

    AuthenticationTokenProcessingFilter

    Here we have created a filter to process authentication token.

    public class AuthenticationTokenProcessingFilter extends GenericFilterBean {
    
        @Autowired UserService userService;
        @Autowired TokenUtils tokenUtils;
        AuthenticationManager authManager;
    
        public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
            this.authManager = authManager;
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            @SuppressWarnings("unchecked")
            Map<String, String[]> parms = request.getParameterMap();
    
            if(parms.containsKey("token")) {
                String token = parms.get("token")[0]; // get the first parameter: "token" 
    
                // validating token
                if (tokenUtils.validate(token)) {
                    // fetching user detail based on the token we got as parameter
                    UserDetails userDetails = tokenUtils.getUserFromToken(token);
                    // create an Authentication object with the user information
                    UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
                    // set the authentication object into the SecurityContext
                    SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));         
                }
            }
            // continue through the filter chain
            chain.doFilter(request, response);
        }
    }
    

    Now the last one is TokenUtils interface, which list down the available methods.

    public interface TokenUtils {
        String getToken(UserDetails userDetails);
        String getToken(UserDetails userDetails, Long expiration);
        boolean validate(String token);
        UserDetails getUserFromToken(String token);
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: