Question

I am designing a RESTful web services that needs to be accessed by user after proper authentication. I have already developed Security for my application using Spring Security 3.0. Now I want to integrate TokenBasedAuthentication. But I stuck here for how do i do this.

My ApplicationContextSecurity.xml:

<global-method-security pre-post-annotations="enabled">
    </global-method-security>
    <beans:bean id="myAccessDecisionManager"
        class="com.app.security.MyAccessDecisionManager">
    </beans:bean>
    <http auto-config="true" once-per-request="true"
        access-decision-manager-ref="myAccessDecisionManager"       
        access-denied-page="/jsp/errorPage.jsp">
        <intercept-url pattern="/*.app" access="ROLE_ANONYMOUS" />
        <form-login login-page="/login.app"
            login-processing-url="/j_spring_security_check" default-target-url="/login/checking.app"
            authentication-failure-url="/login.app?login_error=1" />
        <logout logout-url="/j_spring_security_logout"
            logout-success-url="/login.app" invalidate-session="true" />
        <session-management invalid-session-url="/login.app"
            session-fixation-protection="newSession">
            <concurrency-control max-sessions="100"
                error-if-maximum-exceeded="false" />
        </session-management>
    </http>

    <authentication-manager alias="authenticationManager">
        <authentication-provider ref="customAuthenticationProvider"></authentication-provider>
    </authentication-manager>

    <beans:bean id="customAuthenticationProvider"
        class="com.app.security.CustomAuthenticationProvider">
    </beans:bean>

My CustomAuthenticationProvider :

public class CustomAuthenticationProvider implements AuthenticationProvider {

@Autowired
private ILoginService loginService;

protected final transient Log log = LogFactory.getLog(getClass());

public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {

    UsernamePasswordAuthenticationToken usernamePassswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials());

    // Doing authentication process here and returning authentication token
    return usernamePassswordAuthenticationToken;
}

public boolean supports(Class<? extends Object> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}

My requirement is,

  • When user want to access rest web service at first time he should provide userName/password to the server from header.
  • Server will accept the request, check the authentication and generate token for future requests for specific period. Also I need client side code for how to access secured web services. Thanks.
Was it helpful?

Solution

When user want to access rest web service at first time he should provide userName/password to the server from header.

Server will accept the request, check the authentication and generate token for future requests for specific period

You can do this either using HTTP headers or a normal HTTP POST request mapped to a Spring MVC controller (this is how we do it in our apps):

@Controller
public class AuthenticationController {
    @Autowired
    @Qualifier("authenticationManager")
    AuthenticationManager     authenticationManager;

    @Autowired
    SecurityContextRepository securityContextRepository;

    @RequestMapping(method = RequestMethod.POST, value = "/authenticate")
    public @ResponseBody String authenticate(@RequestParam final String username, @RequestParam final String password, final HttpServletRequest request, final HttpServletResponse response) {
        final UsernamePasswordAuthenticationToken authenticationRequest = new UsernamePasswordAuthenticationToken(username, password);
        final Authentication authenticationResult = this.authenticationManager.authenticate(authenticationRequest);

        final String token = <some randomly generated secure token>;

        final Authentication authentication = new MyAuthenticationToken(authenticationResult, token);

        SecurityContextHolder.getContext().setAuthentication(authentication);

        this.securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);

        return token;
    }
}

Once this is done, the client should send the token in an HTTP header with every subsequent request.

Also I need client side code for how to access secured web services

Not sure what exactly you are looking for here. If your client is a JavaScript library running in a web browser, setting the authentication token as an HTTP header with every request should be straightforward. If your client is a device, the device could store the token in memory and include it as an HTTP header with every request using whatever HTTP client library you are using to invoke the services.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top