user2524908
user2524908

Reputation: 871

Java Spring authenticate user based on token

Looking to protect pages in a basic java spring application based on a token. After the token is consumed I would need the application to know the token was valid at some point and then put some time to live on that session. Below is the controller I have to consume the token.

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(ModelMap model, @RequestParam(value = "token", required = false) String token) {
    if(token==null) {
        return "redirect:403";
    } else if(token.isEmpty()) {
        return "redirect:403";
    } else {
        //perform token WS call to validate the token


        return "redirect:home";
    }
}


@RequestMapping(value = "/403", method = RequestMethod.GET)
public ModelAndView accesssDenied(Principal user) {

    ModelAndView model = new ModelAndView();
        model.addObject("msg",
                "You do not have permission to access this page!");
    model.setViewName("403");
    return model;

}

After performing some check on the token how can I protect all of the subsequent pages? Id also like to be able to secure api calls as well. Can anyone point me in the direction of the spring component?

Upvotes: 0

Views: 155

Answers (1)

Raniz
Raniz

Reputation: 11113

I think you should take a look at Spring Security instead of rolling your own solution - it is built for handling authentication.

What you especially should look at is session management which sounds like what you're trying to do here.

Depending on how your users get their token you might have to implement your own authentication manager and/or login flow, though the default ones cover a lot of common cases too.

Once you have Spring Security set up and your session management working you would protect URLs either by annotating the controller methods:

@RequestMapping("/api/protected")
@PreAuthorize("hasRole('ROLE_USER')")
public String myProtectedController(Authentication authentication, Model model) {
    // User will be authenticated here
}

or by registering them into the HTTP security configuration:

@Configuration
public class SecurityConfig extends WebSecurityConfigurationAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                // Everyone can acess /login
                .antMatchers("/login").permitAll()
                // Only authorized users can access URLs under /api/
                .antMatchers("/api/**").access("hasRole('ROLE_USER')")
    }
}

Of course, in your case you might use something other than ROLE_USER since you may or may not have actual users but something else in your session that you can use.

Upvotes: 1

Related Questions