ошибка входа в базу данных Spring, объект ошибки не равен NULL - PullRequest
0 голосов
/ 13 апреля 2020

Я новичок в весенней безопасности. Я попытался реализовать следующий пример. https://mkyong.com/spring-security/spring-security-form-login-example/

Я использовал URL в Google chrome и firefox:

http://localhost: 8080 / Mkyong-SpringSecurity-Database -XML / admin

Он автоматически переадресует меня на страницу входа: http://localhost: 8080 / Mkyong-SpringSecurity-Database-XML / login

I введите id: alex пароль: 123456

или id: mkyong

пароль: 123456

снимок экрана с ошибкой. Не уверен, почему объект ошибки не нулевой, а '': enter image description here

Это мой MainController. java:

                package com.mkyong.web.controller;

            import org.springframework.security.authentication.AnonymousAuthenticationToken;
            import org.springframework.security.core.Authentication;
            import org.springframework.security.core.context.SecurityContextHolder;
            import org.springframework.security.core.userdetails.UserDetails;
            import org.springframework.stereotype.Controller;
            import org.springframework.web.bind.annotation.RequestMapping;
            import org.springframework.web.bind.annotation.RequestMethod;
            import org.springframework.web.bind.annotation.RequestParam;
            import org.springframework.web.servlet.ModelAndView;

            @Controller
            public class MainController {

                @RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
                public ModelAndView defaultPage() {

                    ModelAndView model = new ModelAndView();
                    model.addObject("title", "Spring Security Login Form - Database Authentication");
                    model.addObject("message", "This is default page!");
                    model.setViewName("hello");
                    return model;

                }

                @RequestMapping(value = "/admin**", method = RequestMethod.GET)
                public ModelAndView adminPage() {

                    ModelAndView model = new ModelAndView();
                    model.addObject("title", "Spring Security Login Form - Database Authentication");
                    model.addObject("message", "This page is for ROLE_ADMIN only!");
                    model.setViewName("admin");

                    return model;

                }

                @RequestMapping(value = "/login", method = RequestMethod.GET)
                public ModelAndView login(@RequestParam(value = "error", required = false) String error,
                        @RequestParam(value = "logout", required = false) String logout) {

                    ModelAndView model = new ModelAndView();
                    if (error != null) {
                        model.addObject("error", "Invalid username and password!");
                    }

                    if (logout != null) {
                        model.addObject("msg", "You've been logged out successfully.");
                    }
                    model.setViewName("login");

                    return model;

                }

                //for 403 access denied page
                @RequestMapping(value = "/403", method = RequestMethod.GET)
                public ModelAndView accesssDenied() {

                    ModelAndView model = new ModelAndView();

                    //check if user is login
                    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                    if (!(auth instanceof AnonymousAuthenticationToken)) {
                        UserDetails userDetail = (UserDetails) auth.getPrincipal();
                        System.out.println(userDetail);

                        model.addObject("username", userDetail.getUsername());

                    }

                    model.setViewName("403");
                    return model;

                }

            }

Это мой mvc -dispatcher-servlet. xml:

                <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"
                xsi:schemaLocation="
                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">

                <context:component-scan base-package="com.mkyong.*" />

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

            </beans>

Это моя база данных Spring. xml:

                <beans xmlns="http://www.springframework.org/schema/beans"
                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-3.0.xsd">

                <bean id="dataSource"
                    class="org.springframework.jdbc.datasource.DriverManagerDataSource">

                    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://localhost:3306/test1" />
                    <property name="username" value="albert" />
                    <property name="password" value="Jadeite1" />
                </bean>

            </beans>

Это моя весенняя защита. xml :

                <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"
                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.2.xsd">

                <!-- enable use-expressions -->
                <http auto-config="true" use-expressions="true">
                    <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />

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

                <!-- Select users and user_roles from database -->
                <authentication-manager>
                    <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 username, role from user_roles where username =?  " />
                    </authentication-provider>
                </authentication-manager>

            </beans:beans>`

Это моя сеть. xml:

                <web-app id="WebApp_ID" version="2.4"
                xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
                http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

                <display-name>Spring MVC Application</display-name>


                <!-- Spring MVC -->
                <servlet>
                    <servlet-name>mvc-dispatcher</servlet-name>
                    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                    <load-on-startup>1</load-on-startup>
                </servlet>
                <servlet-mapping>
                    <servlet-name>mvc-dispatcher</servlet-name>
                    <url-pattern>/</url-pattern>
                </servlet-mapping>

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

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

                <!-- Spring Security -->
                <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>


            </web-app>

Это mysql. sql скрипт:

            CREATE  TABLE users (
              username VARCHAR(45) NOT NULL ,
              password VARCHAR(45) NOT NULL ,
              enabled TINYINT NOT NULL DEFAULT 1 ,
              PRIMARY KEY (username));

            CREATE TABLE user_roles (
              user_role_id int(11) NOT NULL AUTO_INCREMENT,
              username varchar(45) NOT NULL,
              role varchar(45) NOT NULL,
              PRIMARY KEY (user_role_id),
              UNIQUE KEY uni_username_role (role,username),
              KEY fk_username_idx (username),
              CONSTRAINT fk_username FOREIGN KEY (username) REFERENCES users (username));

            INSERT INTO users(username,password,enabled)
            VALUES ('mkyong','123456', true);
            INSERT INTO users(username,password,enabled)
            VALUES ('alex','123456', true);

            INSERT INTO user_roles (username, role)
            VALUES ('mkyong', 'ROLE_USER');
            INSERT INTO user_roles (username, role)
            VALUES ('mkyong', 'ROLE_ADMIN');
            INSERT INTO user_roles (username, role)
            VALUES ('alex', 'ROLE_USER');

Это моя база данных:

enter image description here Любая подсказка или помощь будет принята с благодарностью.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...