简体   繁体   中英

Spring MVC web security 404 error

pir-servlet.xml

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

    <context:annotation-config />

    <context:component-scan base-package="com.pir" />
    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="myTransactionManager" />


    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1048576" />
    </bean>

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="com.mysql.jdbc.Driver"
    p:url="jdbc:mysql://localhost:3306/pir"
    p:username="root"
    p:password="user" />

    <bean id="tilesViewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass">
            <value>
                org.springframework.web.servlet.view.tiles3.TilesView
            </value>
        </property> 
    </bean>
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles.xml</value>
            </list>
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />


    <!-- enable use-expressions -->
    <security:http auto-config="true" authentication-manager-ref="authManager">
        <security:intercept-url pattern="/admin**" access="hasRole('ROLE_admin')" />
        <security:intercept-url pattern="/login*" />

        <!-- access denied page -->
        <security:access-denied-handler error-page="/403" />
        <security:form-login 
            login-page="/login" 
            login-processing-url="/postlogin"
            default-target-url="/index"
            authentication-failure-url="/login?error" 
            username-parameter="emailID"
            password-parameter="password" />
        <security:logout logout-success-url="/login?logout" />
        <!-- enable csrf protection -->
        <security:csrf />
    </security:http>

    <bean id="userAuthenticationProviderImpl" class="com.pir.authentication.UserAuthenticationProviderImpl" />

    <security:authentication-manager id="authManager">
        <security:authentication-provider user-service-ref="userAuthenticationProviderImpl" >
            <security:password-encoder hash="plaintext" />    
        </security:authentication-provider>
    </security:authentication-manager>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            WEB-INF/pir-servlet.xml 
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <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>

    <servlet>
        <servlet-name>pir</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>pir</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

UserAuthenticationProviderImpl.java

@Component(value = "authenticationProvider")
public class UserAuthenticationProviderImpl implements UserDetailsService,
        UserAuthenticationProvider {

    UserFunctionsService userFunctionsService;

    @Autowired(required=true)
    @Qualifier(value="userFunctionsService")
    public void setUserFunctionsService(UserFunctionsService userFunctionsService)
    {
        this.userFunctionsService = userFunctionsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) {
        // TODO Auto-generated method stub

        Users users = (Users) this.userFunctionsService.getUserDetails(authentication.getPrincipal().toString());

        if(users == null)
            throw new UsernameNotFoundException(String.format("Invalid credentials", authentication.getPrincipal()));

        String suppliedPasswordHash = authentication.getCredentials().toString();

        if(!users.getPassword().equals(suppliedPasswordHash)){
            throw new BadCredentialsException("Invalid credentials");
        }

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(users, users.getAuthorities());

        return token;
    }

    @Override
    public UserDetails loadUserByUsername(String emailID)
            throws UsernameNotFoundException {
        // TODO Auto-generated method stub

        Users users = this.userFunctionsService.findByEmail(emailID);

        //List<GrantedAuthority> authorities = buildUserAuthority(users.getUserType());

        if(users == null)
            throw new UsernameNotFoundException("User not found");
        return (UserDetails) users;
    }

    public List<GrantedAuthority> buildUserAuthority(String userRoles){

        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

        setAuths.add(new SimpleGrantedAuthority(userRoles));

        List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);

        return result;
    }
}

login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

    <c:url value="/postlogin" var="loginurl" />
    <form action="${loginurl}" method="POST">
        <table>
            <tr>
                <td colspan="2" align="center">Already have an account - Login</td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="text" id="emailID" name="emailID" /></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" id="password" name="password" /></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="Login" /></td>
            </tr>   
            <tr>
                <td colspan="2" align="center">
                    <a href="${pageontext.request.contextPath }/forgotpassword">Forgot Password</a>
                </td>
            </tr>                                   
        </table>                                        
    </form>
    <span class="error">${loginMessage}</span>

Whenever I click on submit button, I expect the form should either allow login or give invalid password. But I am getting this error.

Error

HTTP Status 404 -

type Status report

message

description The requested resource is not available.
Apache Tomcat/7.0.41

Why this error is coming?

The url that is being called from login form is just /postlogin or /[context-name]/postlogin ?

I'm afraid your jsp is calling to just /postlogin... and that's maybe the reason to get 404

Edit: try with this:

<security:http auto-config="true" authentication-manager-ref="authManager">
        <security:intercept-url pattern="/admin**" access="hasRole('ROLE_admin')" />
        <security:intercept-url pattern="/postlogin" access="hasRole('ROLE_admin')" />
        <security:intercept-url pattern="/login*" />

...

You should use

login-processing-url="/j_spring_security_check"

Form login with Spring Security

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