2013-08-18 2 views
0

Я пытаюсь создать веб-приложение на основе Spring, и я хотел бы начать с настройки простой системы аутентификации на основе имени пользователя & паролей, хранящихся в таблице базы данных.Spring security - ресурс j_spring_security_check not avaiable

Насколько я понимаю, это можно легко достичь с помощью весенней безопасности, но я не могу заставить его работать.

следующее: web.xml файл.

<?xml version="1.0" encoding="UTF-8"?> 
<web-app 
    version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 

    <servlet> 
     <servlet-name>Servlet</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>/WEB-INF/spring/Servlet/servlet-context.xml</param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 

    <servlet-mapping> 
     <servlet-name>Servlet</servlet-name> 
     <url-pattern>/</url-pattern> 
    </servlet-mapping> 

Следит за сервлет-context.xml файл. Пользователи bob и sam находятся в тестовых целях. После того, как я получу это право, я перейду на службу пользователей на основе JDBC.

<?xml version="1.0" encoding="UTF-8"?> 
<beans 
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:sec="http://www.springframework.org/schema/security" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
     http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> 

    <sec:http use-expressions="true"> 
     <sec:intercept-url pattern="/**" access="permitAll" /> 
     <sec:form-login 
      login-page="/home.html" 
      login-processing-url="/j_spring_security_check" 
      authentication-failure-url="/login-error.html" 
      default-target-url="/welcome.html" /> 
     <sec:logout logout-success-url="/home.html" /> 
    </sec:http> 

    <sec:authentication-manager> 
     <sec:authentication-provider> 
      <sec:password-encoder hash="md5"/> 
      <sec:user-service> 
       <sec:user name="bob" password="12b141f35d58b8b3a46eea65e6ac179e" authorities="ROLE_SUPERVISOR, ROLE_USER" /> 
       <sec:user name="sam" password="d1a5e26d0558c455d386085fad77d427" authorities="ROLE_USER" /> 
      </sec:user-service> 
     </sec:authentication-provider> 
    </sec:authentication-manager> 

    <context:component-scan base-package="cz.dusanrychnovsky.whattoreadnext" /> 
    <mvc:annotation-driven /> 
</beans> 

Это мой главный контроллер.

@Controller 
public class HomeController 
{ 
    @RequestMapping(value = "/home.html") 
    public String home() { 
     return "home"; 
    } 

    @RequestMapping(value = "/login-error.html") 
    public String loginError(Model model) { 
     model.addAttribute("loginError", true); 
     return "home"; 
    } 
} 

И это мой взгляд на тимелеаф.

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd"> 
<html 
    xmlns="http://www.w3.org/1999/xhtml" 
    xmlns:th="http://www.thymeleaf.org"> 

    <head> 
     <title>Contacts</title> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    </head> 
    <body> 
     <div id="content"> 
      <h1>Welcome to the site!</h1> 

      <p th:if="${loginError}">Wrong user or password</p> 
      <form th:action="@{/j_spring_security_check}" method="post"> 
       <label for="j_username">Email address</label>: 
       <input type="text" id="j_username" name="j_username" /> <br /> 
       <label for="j_password">Password</label>: 
       <input type="password" id="j_password" name="j_password" /> <br /> 
       <input type="submit" value="Log in" /> 
      </form> 
     </div> 
    </body> 
</html> 

Когда я развернуть файл WAR на мою локальную установку Tomcat и посетить http://localhost:8080/test/home.html URL, домашняя страница открывается нормально. Однако, когда я заполняю форму, которая отправляется в http://localhost:8080/test/j_spring_security_check, я получаю ошибку 404 - The requested resource() is not available..

Что я делаю неправильно? Пожалуйста, несите меня, поскольку я новичок в Spring MVC/Security и Thymeleaf.

ответ

3
  1. Вы должны configure Spring Security filter in web.xml

  2. Вы не можете настроить Spring Security в servlet-context.xml, потому что servlet-context.xml принадлежит к конкретному DispatcherServlet, но фильтр Spring Security работает, прежде чем запрос достигнет любого сервлета.

    Необходимо установить create a root application context using ContextLoaderListener и установить там конфигурацию Spring Security.

    На самом деле, до тех пор, пока вы не нужны отдельные servlet-context.xml и applicationContext.xml, я предлагаю вам, чтобы переместить все из servlet-context.xml в applicationContext.xml и оставить servlet-context.xml эффективно пустой (то есть оставить свой <beans> элемент пуст).

 Смежные вопросы

  • Нет связанных вопросов^_^