java - 运行 Spring 安全

标签 java spring

我的第一篇文章在这里 Spring security. Cant run automaticly 。我的 Spring 安全工作不好。我添加redirect.jsp <%response.sendRedirect("login.do");%>一切都很好,但我可以随时输入 http://localhost:8081/test/index.do而且我没有使用登录页面。我的代码有什么问题?请帮助我。

web.xml:

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

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            /WEB-INF/spring-security.xml 
        </param-value>      
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>        

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>


    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>   

</web-app>

Spring 安全:

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

    <security:http auto-config="true">
    <security:http-basic/>
        <security:intercept-url pattern="/welcome.do" access="ROLE_USER" />  
    <!--     <intercept-url pattern="/login*" access="isAnonymous()"/>  -->

        <security:form-login login-page="/login.do" default-target-url="/welcome.do"
            authentication-failure-url="/loginfailed.do" />
        <security:logout logout-success-url="/login.do" />
    </security:http>

    <security:authentication-manager>
       <security:authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"

           users-by-username-query="
              select username,password, enabled 
              from users where username=?" 

           authorities-by-username-query="
              select u.username, ur.authority from users u, user_roles ur 
              where u.user_id = ur.user_id and u.username =?  " 

        />
       </security:authentication-provider>
    </security:authentication-manager>

</beans:beans>

调度程序servlet:

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

<!--  <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />    -->

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>          
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

        <property name="urlMap">
            <map>
                <entry key="/index.do"> <ref bean="index" /></entry>      
                <entry key="/registration.do"> <ref bean="registration" /></entry>
                <entry key="/usertestlist.do"> <ref bean="usertest" /></entry>    
                <entry key="/showContacts.do"> <ref bean="contact" /></entry>
             <!--       <entry key="/add.html"> <ref bean="contact" /></entry>  --> 
                <entry key="/saveContact.do"> <ref bean="contact" /></entry>
                <entry key="/updateContact.do"> <ref bean="contact" /></entry>                    
                <entry key="/deleteContact.do"> <ref bean="contact" /></entry> 
                <entry key="/searchContacts.do"> <ref bean="contact" /></entry>
                <entry key="/login.do"> <ref bean="login" /></entry>
                <entry key="/loginfailed.do"> <ref bean="login" /></entry>
                <entry key="/logout.do"> <ref bean="login" /></entry>             
                <entry key="/welcome.do"> <ref bean="login" /></entry>       
                <!--    <entry key="/delete/*.html"> <ref bean="contact" /></entry>      -->                
            </map>
        </property>
    </bean>

    <bean id="index" class="pl.ivmx.web.IndexController"/>      

        <bean id="registrationValidator" class="pl.ivmx.validation.RegistrationValidator" />  
        <bean id="registration" class="pl.ivmx.web.RegistrationFormController" >                 
            <property name="commandName"><value>userTest</value></property> 
            <property name="commandClass"><value>pl.ivmx.model.UserTest</value></property> 
            <property name="validator"><ref local="registrationValidator"/></property>  
            <property name="formView"><value>registration</value></property> 
            <property name="successView"><value>registrationsuccess</value></property> 
            <property name="userTestDao"><ref bean="userTestDao"/></property>               
        </bean>     

        <bean id="usertest" class="pl.ivmx.web.UserTestController">                  
             <property name="userTestDao"><ref bean="userTestDao"/></property>          
        </bean>      



    <context:component-scan base-package="pl.ivmx" />

    <bean id="contact" class="pl.ivmx.contact.controller.ContactController"/>
    <bean id="login" class="pl.ivmx.service.servlet.LoginController"/>   

    <bean id="contactFormValidator" class="pl.ivmx.contact.validator.ContactFormValidator"/>

  <!--      <mvc:annotation-driven/>    --> 

</beans>

applicationContext.xml:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean> 


    <import resource="commonContext.xml" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="userTestDao" class="pl.ivmx.dao.impl.UserTestDaoImpl">
    <!--     <property name="dataSource" ref="dataSource" />   -->
        <property name="sessionFactory" ref="sessionFactory" />             
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >  
    <!--    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
        <property name="dataSource" ref="dataSource" />                 
         <property name="configLocation" value="META-INF/hibernate.cfg.xml" />    
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
    <!--    <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>      
            </props>
        </property>         
        <property name="annotatedClasses">
            <list>
                <value>pl.ivmx.model.UserTest</value>
            </list>
        </property>    -->     
    </bean> 

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>  

    <context:annotation-config />    
    <tx:annotation-driven />

    <bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl" />

    <bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl"/>

</beans>

重定向.jsp:

<%
response.sendRedirect("login.do");
%>

登录.jsp:

<%@ include file="header.jsp"%>

<div id="menu"></div>


<div id="subMenu"></div>

<div id="main">


    <c:if test="${not empty error}">
        <div class="errorblock">
            Your login attempt was not successful, try again.<br /> Caused :
            ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
        </div>
    </c:if>
             <!--    <form class="jqtransform" id="loginForm" action='/test/j_spring_security_check' method="POST">     -->
    <form name='f' action="<c:url value='j_spring_security_check' />"
        method='POST'>

        <table>
            <tr>
                <td>User:</td>
                <td><input type='text' name='j_username' value=''>
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='j_password' />
                </td>
            </tr>
            <tr>
                <td colspan='2'><input name="submit" type="submit"
                    value="submit" />
                </td>
            </tr>
            <tr>
                <td colspan='2'><input name="reset" type="reset" />
                </td>
            </tr>
        </table>

    </form>

</div>


<%@ include file="footer.jsp"%>

index.jsp:

<%@ include file="header.jsp"%>

<div id="menu">
    <div id="subMenu">
        <div class="menuDiv">Kliknij</div>
        <ul>
            <li><a href="registration.do">REJESTRUJ</a></li>
            <li><a href="usertestlist.do">lista uzytkownikow</a></li>
            <li><a href="showContacts.do">contact</a></li>
        </ul>
    </div>
</div>


<div id="main">

</div>



<%@ include file="footer.jsp"%>

索引 Controller : 包 pl.ivmx.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {

    @RequestMapping(value = "/index")
    public ModelAndView index(){
    ModelAndView mav = new ModelAndView("index");

    return mav;
    }

登录 Controller :

package pl.ivmx.service.servlet;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import pl.ivmx.contact.form.Contact;

@Controller
public class LoginController  {

//  public String login(HttpServletRequest request, HttpServletResponse response) {
//      return "login";
//  }

//  @RequestMapping(value="/index", method = RequestMethod.GET)
//  public String printWelcome(ModelMap model) {
// 
//      User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//      String name = user.getUsername();       
//      model.addAttribute("username", name);
//      model.addAttribute("message", "Spring Security login + database example");
//      return "index";
//  }

    @RequestMapping(value="/welcome.do", method = RequestMethod.GET)
    public String printWelcome(Map<String, Object> map) {
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = user.getUsername();       
        map.put("username", name);      
        return "index";
    }

    @RequestMapping(value="/login.do", method = RequestMethod.GET)
    public String login(ModelMap model) {
        return "login"; 
    }

    @RequestMapping(value="/loginfailed.do", method = RequestMethod.GET)
    public String loginerror(ModelMap model) { 
        model.addAttribute("error", "true");
        return "login"; 
    }

    @RequestMapping(value="/logout.do", method = RequestMethod.GET)
    public String logout(ModelMap model) { 
        return "login"; 
    }

}

最佳答案

快速浏览一下,我发现对 index.do 的请求并没有要求您登录,因为您没有要求它登录。事实上,您似乎需要身份验证的唯一 URL 是 welcome.do;

<security:http auto-config="true">
  <security:http-basic/>
  <security:intercept-url pattern="/welcome.do" access="ROLE_USER" />  
  <security:form-login login-page="/login.do" default-target-url="/welcome.do"
        authentication-failure-url="/loginfailed.do" />
  <security:logout logout-success-url="/login.do" />
</security:http>

你基本上有两个选择;

默认要求对所有网址进行身份验证,然后手动指定不需要的网址

<security:http auto-config="true">
  <security:http-basic/>
  <security:intercept-url pattern="/css/**" filters="none"/>
  <security:intercept-url pattern="/img/**" filters="none"/>
  <security:intercept-url pattern="/jscript/**" filters="none"/>
  <security:intercept-url pattern="/login.do" filters="none"/>
  <security:intercept-url pattern="/loginfailed.do" filters="none"/>
  <security:intercept-url pattern="/**" access="ROLE_USER"/>
  <security:form-login login-page="/login.do" default-target-url="/welcome.do"
        authentication-failure-url="/loginfailed.do" />
  <security:logout logout-success-url="/login.do" />
</security:http>

注意,你必须告诉spring css/img/script 资源不需要登录,登录页面也不需要登录。

默认不要求对任何 URL 进行身份验证,然后手动指定需要身份验证的 URL

<security:http auto-config="true">
  <security:http-basic/>
  <security:intercept-url pattern="/welcome.do" access="ROLE_USER" />  
  <security:intercept-url pattern="/index.do" access="ROLE_USER" />  
  <security:form-login login-page="/login.do" default-target-url="/welcome.do"
        authentication-failure-url="/loginfailed.do" />
  <security:logout logout-success-url="/login.do" />
</security:http>

请注意,您必须指定每个需要身份验证的 URL。维护起来可能会很痛苦。

关于java - 运行 Spring 安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14643786/

相关文章:

java - Spring安全注销使 session 范围对象无效,这不是必需的

javascript - Thymeleaf 对象到 Javascript 对象错误 : TemplateProcessingException

java - HandlerInterceptorAdapter 不起作用

java - 应用程序初始化的首选方式

java - SpringBoot 2 功能区启动器的 ClassNotFoundException : com.netflix.config.CachedDynamicIntProperty

c# - 为什么 Sun 不做 C# 到 Java 字节码编译器?

java - docx4j 3.0 pdf 导出失败并出现 Docx4JException

java - 是否可以仅对 JTextpane 的一部分进行着色?

java - 无法访问应用程序中的 h2 数据库文件

java - 带参数的 Spring 原型(prototype) bean?