使用java config的Spring Security不提交登录页面

时间:2014-09-08 18:30:34

标签: java spring security spring-mvc spring-security

我是Spring的Java配置功能的新手。我正在尝试使用java配置使用spring安全性,但是当我提交页面时,我的登录页面没有做任何事情。看起来请求不会在任何地方。我正在使用Spring 4.0.6 RELEASE和Spring security 3.2.4.RELEASE。请帮忙。提前谢谢。

1)Spring安全性Java Config类

@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired 
    private CustomUserDetailsService customUserDetailsService; 

    @Override 
    protected void configure(AuthenticationManagerBuilder registry) throws Exception { 
        registry.userDetailsService(customUserDetailsService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
         web.ignoring().antMatchers("/resources/**"); 
    }

    protected void configure(HttpSecurity http) throws Exception {
        http 
        .csrf().disable() 
        .authorizeRequests() 
           .antMatchers("/login","/login/form**","/register","/logout").permitAll() //any user can access a request if the URL starts with these URLs 
           .antMatchers("/admin","/admin/**").hasRole("ADMIN") //Any URL that starts with "/admin/" will be resticted to users who have the role "ROLE_ADMIN" 
           .anyRequest().authenticated() 
           .and() 
        .formLogin() 
           .loginPage("/login/form") 
           .loginProcessingUrl("/login") 
           .failureUrl("/login/form?error") 
           .permitAll(); 
    }
}

2)使用图块登录页面,这只是正文页面之一

<%@ page pageEncoding="UTF-8"%>
<p>
    Locale is:
    <%=request.getLocale()%></p>
<%-- this form-login-page form is also used as the
         form-error-page to ask for a login again.
         --%>
<c:if test="${not empty param.login_error}">
    <font style="font-weight:bold;font-color:red"> Your login attempt was not successful, try
        again.<br />
    <br /> Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />.
    </font>
</c:if>

<br class="smaller" />
<!-- in spring security 3 the value is replaced to /login from j_spring_security_check -->
<form name="adminLogin" action="<c:url value='/login'/>"
    method="POST">
    <fieldset>
        <legend>Login</legend>
        <br />
        <div class="largeFormEntry">
            <label class="standardFormLabel" for="username">User Name:</label> <input
                type='text' name='username'
                value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>' />
        </div>
        <div class="clear"></div>
        <div class="largeFormEntry">
            <label class="standardFormLabel" for="password">Password:</label> <input
                type='password' name='password'>
        </div>
        <div class="largeFormEntry">
            <input type="checkbox" name="_spring_security_remember_me"> 
            <span>Don't ask for my password for two weeks</span>
        </div>
        <div class="clear"></div>
        <!-- form footer -->
        <br />
        <div id="loginFooter">
            <input class="buttons" type="button" value="Login" />
        </div>
        <!-- end of form footer -->
    </fieldset>
    <input type="hidden" name="${_csrf.parameterName}"
        value="${_csrf.token}" />
    <div class="clear"></div>
    <div class="bodylink">
        <br /> <a href="loginExample.jsp" title="Forgot User Name?">Forgot
            User Name or Password?</a> <br /> <br /> <br /> If you
        don't have an account, you can <a href="loginExample.jsp"
            title="Create an account now">create an account now.</a>
    </div>
</form>

3)控制器

A)在此控制器中,如果URL为... / admin / reports或admin / login ...它显示正确的视图,但是当我提交登录时,它没有做任何事情......

@Controller
@RequestMapping("/admin")
public class AdminLoginController {

    @Autowired
    SecurityRoleService securityRoleService;

    /*
     * @RequestMapping(value="{loginType}", method = RequestMethod.GET) public
     * String getAdminLogin(@PathVariable String loginType, ModelMap model) {
     * 
     * model.addAttribute("model", loginType); return "adminlogin";
     * 
     * }
     */
    // nothing is passed, show the login page
    @RequestMapping(value = { "", "/login" }, method = RequestMethod.GET)
    public ModelAndView adminLoginPage() {

        // ModelAndView model = new ModelAndView();
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("pageInstructionText", "Admin login");
        // model.addObject("title",
        // "Spring Security 3.2.3 Hello World Application");
        // model.addObject("message", "Welcome Page !");
        // model.setViewName("adminlogin",loginModel);
        return new ModelAndView("adminlogin", model);

    }

    @RequestMapping(value = { "", "/login" }, method = RequestMethod.POST)
    public ModelAndView handleLogin(BindingResult errors) {
        Map<String, Object> model = new HashMap<String, Object>();
        String view = "";
        if (errors.hasErrors()) {
            model.put("pageInstructionText", "Admin login");
            view = "adminLogin";
        } else {
            view = "reports";
            model.put("pageInstructionText", "List of Admin Reports");
        }
        return new ModelAndView(view, model);
    }

    @RequestMapping(value = { "/reports" }, method = RequestMethod.GET)
    public ModelAndView adminReportsPage() 
    {

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("pageInstructionText", "List of Admin Reports");
        Date now = new Date();
        SecurityRole securityRole = (SecurityRole.getBuilder("ROLE_ADMIN",
                "Admin User", "Y", new Long(1), now, now)).build();
        // securityRoleRepo.save(securityRole);
        securityRoleService.save(securityRole);
        System.out.println("SecurityRole inserted!");
        return new ModelAndView("reports", model);
    }
}

B)

@Controller
@RequestMapping("/")
public class AppController {
    @RequestMapping(value = { "/helloworld**" ,"/welcome**","/home**"}, method = RequestMethod.GET)
    public ModelAndView welcomePage() {
        return getWelcomePage();
    }

    @RequestMapping(value = { "" }, method = RequestMethod.GET)
    public ModelAndView getWelcomePage() {
        ModelAndView model = new ModelAndView();
        model.addObject("title",
                "Spring Security 3.2.3 Hello World Application");
        model.addObject("message", "Welcome Page !");
        model.setViewName("helloworld");
        return model;
    }

    @RequestMapping(value = "/protected**", method = RequestMethod.GET)
    public ModelAndView protectedPage() {

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security 3.2.3 Hello World");
        model.addObject("pageInstructionText", "This is a protected page : Admin login");
        model.setViewName("adminlogin");
        return model;
    }

    @RequestMapping(value = "/confidential**", method = RequestMethod.GET)
    public ModelAndView superAdminPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security 3.2.3 Hello World");
        model.addObject("message",
                "This is confidential page - Need Super Admin Role !");
        model.setViewName("protected");

        return model;
    }

    @RequestMapping(value = { "/login" }, method = RequestMethod.POST)
    public ModelAndView adminReportsPage() {

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("pageInstructionText", "List of Admin Reports");
        Date now = new Date();
        //SecurityRole securityRole = (SecurityRole.getBuilder("ROLE_ADMIN",
        //      "Admin User", "Y", new Long(1), now, now)).build();
        // securityRoleRepo.save(securityRole);
        //securityRoleService.save(securityRole);
        System.out.println("SecurityRole inserted!");
        return new ModelAndView("reports", model);
    }
}

1 个答案:

答案 0 :(得分:0)

你必须使用

.formLogin()
        .loginPage("/login")

如果您想将表单提交到/login

所以替换

.formLogin() 
           .loginPage("/login/form") 
           .loginProcessingUrl("/login") 
           .failureUrl("/login/form?error") 
           .permitAll(); 

 .formLogin() 
           .loginPage("/login") 
           .failureUrl("/login/form?error") 
           .permitAll(); 

另一个选项是提交到/login/form并保留当前配置。

文档:http://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle/See第3.3节ava配置和表单登录。