繁体   English   中英

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

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

我是春季的Java配置功能的新手。 我正在尝试通过java config使用spring security,但是提交页面时我的登录页面没有任何作用。 看起来请求没有任何地方。 我正在使用Spring 4.0.6 RELEASE和Spring Security 3.2.4.RELEASE。 请帮忙。 提前致谢。

1)Spring Security 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);
    }
}

你必须用

.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/请参阅第3.3节ava配置和表单登录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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