Spring auto login controller GrantedAuthority


      Click here to attend Spring Framework 4.x and certification course with a discount

package nl.kameroom.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AutoLoginController {

	@RequestMapping({ "/navigate.k" })
	public ModelAndView navigate(@RequestParam("email") final String email, 
			@RequestParam("k") String key, 
			HttpServletRequest request,
			HttpServletResponse response, Authentication auth) throws Exception { 			

		String nav= "index";

		if(auth== null) {
			//Spring Security Auto Login
			try {
				String keyinDB = userManager.getReminderUserPassKey(email);
				if(keyinDB.equals(key)) { 
					GrantedAuthority ga = new GrantedAuthorityImpl("USER");			
					List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
					authorities.add(ga);			
					AbstractAuthenticationToken token = new UsernamePasswordAuthenticationToken(email, "", authorities);
					SecurityContextHolder.getContext().setAuthentication(token);

				}else {
					nav = "login/login";					
				}			
			} catch (Exception e) {
				SecurityContextHolder.getContext().setAuthentication(null);

			}
		}

		return new ModelAndView(nav);
	}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s