Spring SecurityConfiguration

时间:2017-03-28 09:52:24

标签: spring-mvc spring-security

我遇到此代码的问题... 当运行应用程序时,它将转到登录页面而不是转到索引页面 这是我的安全配置

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/index").permitAll()
            .antMatchers("/login").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasRole("USER")
            .antMatchers("/dba/**").hasRole("DBA").and().formLogin().loginPage("/login")
            .loginProcessingUrl("/login").usernameParameter("email").passwordParameter("password").and()
            .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
            .tokenValiditySeconds(86400).and().csrf().and().exceptionHandling().accessDeniedPage("/Access_Denied");

}

我有索引文件但是当我把地址我有404 ...

不要搞错了

UPDATE 现在我有其他问题 我已将代码更改为

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/admin*/**").hasRole("ADMIN")
            .antMatchers("/user*/**").hasRole("USER")
            .antMatchers("/dba*/**").hasRole("DBA").and().formLogin().loginPage("/index").permitAll()
            .loginProcessingUrl("/login").usernameParameter("email").passwordParameter("password").and()
            .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
            .tokenValiditySeconds(86400).and().csrf().and().exceptionHandling().accessDeniedPage("/Access_Denied");
}

从索引页面开始,我选择登录,我把我的凭证和我返回索引...再次选择登录我要去我的管理页面

这是我的控制器

@Controller
@RequestMapping("/")
@SessionAttributes("roles")
public class IndexController {

    private static final Logger logger = LoggerFactory.getLogger(Atividades.class);

    @Autowired
    AtividadesService as;

    @Autowired
    UserService userService;

    @Autowired
    UserProfileService userProfileService;

    @Autowired
    MessageSource messageSource;

    @Autowired
    PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;

    @Autowired
    AuthenticationTrustResolver authenticationTrustResolver;


   @RequestMapping(value = { "/"}, method = RequestMethod.GET)
    public String homePage(ModelMap model) {
        //Lista as atividades da semana
        List<Atividades> atividades = as.listAllAtividades();
        model.addAttribute("atividades", atividades);
        return "index";
    }

    @RequestMapping(value = { "/admin" }, method = RequestMethod.GET)
    public String listUsers(ModelMap model) {
        List<AppUser> users = userService.listAllUsers();
        model.addAttribute("users", users);
        model.addAttribute("loggedinuser", getPrincipal());
        return "/admin/admin";
    }

    @ModelAttribute("roles")
    public List<UserProfile> initializeProfiles() {
        return userProfileService.findAll();
    }

    @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
    public String accessDeniedPage(ModelMap model) {
        model.addAttribute("loggedinuser", getPrincipal());
        return "accessDenied";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage() {
        if (isCurrentAuthenticationAnonymous()) {
            return "login";
        } else {
            return "redirect:/admin";
        }
    }

    @RequestMapping(value="/logout", method = RequestMethod.GET)
    public String logoutPage (HttpServletRequest request, HttpServletResponse response){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            //new SecurityContextLogoutHandler().logout(request, response, auth);
            persistentTokenBasedRememberMeServices.logout(request, response, auth);
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        return "redirect:/login?logout";
    }

    private String getPrincipal(){
        String userName = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            userName = ((UserDetails)principal).getUsername();
        } else {
            userName = principal.toString();
        }
        return userName;
    }

    private boolean isCurrentAuthenticationAnonymous() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authenticationTrustResolver.isAnonymous(authentication);
    }

}

我已经使用了调试,当我点击Login链接时,调试器会转到该方法

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage() {
    if (isCurrentAuthenticationAnonymous()) {
        return "login";
    } else {
        return "redirect:/admin";
    }
}

并检查isCurrentAuthenticationAnonymous()是否为null,因为我没有提供任何凭据。 发生这种情况是因为主页面是登录...但我想要一个包含信息和链接(登录)的索引页面..

这里有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

你应该添加.loginPage(&#34; / login&#34;);或.loginPage(&#34; / index&#34;);

了解更多信息:http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/guides/form.html