简体   繁体   中英

Spring Security using java config doesn't submit the login page

I am new to Java config feature of the spring. I am trying to use spring security using java config but my login page doesn't do anything when i submit the page. It looks like the request is not going anywhere. I am using Spring 4.0.6 RELEASE and Spring security 3.2.4.RELEASE. Please help. Thanks in advance.

1) Spring security Java Config class

@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) Login page using tiles so this is just one of the body page

<%@ 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) Controllers

A) in this controller if the URL is .../admin/reports or admin/login...it displays the proper view but when I submit login, it doesn't do anything...

@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);
    }
}

You have to use

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

if you want to submit the form to /login .

So replace

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

with

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

The other option is to submit to /login/form and keep the current configuration.

Docs: http://docs.spring.io/spring-security/site/docs/3.2.5.RELEASE/reference/htmlsingle/See section 3.3 ava Configuration and Form Login.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM