Безопасность Spring: не может получить доступ к целевой странице после ввода правильных учетных данных - PullRequest
2 голосов
/ 18 января 2020

Я пытаюсь создать базовое c приложение Spring Security (3.0), следуя общим учебникам из inte rnet. Однако даже после ввода настроенных учетных данных страница входа снова открывается. Журналы отладки показывают, что пользователь проходит проверку подлинности как анонимный пользователь. Пожалуйста, дайте мне знать, что мне не хватает.

Вот мой интернет. xml: -

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    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">
    <display-name>Spring Security Example</display-name>


    <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</param-value>
    </context-param>

    <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>/</url-pattern>
    </servlet-mapping>

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


    <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>

Моя пружинная защита. xml: -

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


    <http >
        <intercept-url pattern="/app/*"
            access="ROLE_USER" />
        <form-login login-page="/app/login/"
            default-target-url="/app/home/"
            authentication-failure-url="/app/login?error=true" />
    </http>


    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="sumit" password="1234"
                    authorities="ROLE_USER" />
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>  

Мой логин. jsp: -

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login</title>
</head>
<body>
    <h2>Login page</h2>


    <form:form method="POST" action="../home" commandName="user">
        Username: <form:input path="username" />
        <br>

        Password: <form:input path="password" />
        <br>

        <input type="submit" value="Login">
    </form:form>



</body>
</html>

Мой контроллер: -

package com.test.basicspring.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.test.model.UserModel;

@Controller
@RequestMapping(value = "/app")
public class HelloWorldController {

    private Logger logger = Logger.getLogger(HelloWorldController.class);

    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    public void SayHello(HttpServletResponse response) {
        System.out.println("Hello World");
        logger.info("Logging Hello World");
        try {
            response.getWriter().write("Request completed");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/login")
    public String login(Model modelMap) {
        System.out.println("In login method");
        modelMap.addAttribute("user", new UserModel());
        return "login";

    }

    @RequestMapping(method = RequestMethod.POST, value = "/home")
    public String home() {
        System.out.println("Login successful");
        return "";

    }

}

Отладка журналов после отправки учетных данных: -

    DEBUG   2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - Converted URL to lowercase, from: '/app/home'; to: '/app/home'
DEBUG   2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - Candidate is: '/app/home'; pattern is /**; matched=true
DEBUG   2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - /app/home at position 1 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.context.SecurityContextPersistenceFilter@26f6ad34'
DEBUG   2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.context.HttpSessionSecurityContextRepository  - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG   2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.context.HttpSessionSecurityContextRepository  - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@4f884b44. A new one will be created.
DEBUG   2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - /app/home at position 2 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@7d0a1070'
DEBUG   2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - /app/home at position 3 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.savedrequest.RequestCacheAwareFilter@542dcf66'
DEBUG   2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.savedrequest.DefaultSavedRequest  - pathInfo: both null (property equals)
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.savedrequest.DefaultSavedRequest  - queryString: both null (property equals)
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.savedrequest.DefaultSavedRequest  - requestURI: arg1=/springSecurityExample/app/hello; arg2=/springSecurityExample/app/home (property not equals)
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.savedrequest.HttpSessionRequestCache  - saved request doesn't match
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - /app/home at position 4 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6d55a0ba'
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - /app/home at position 5 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6ec0b31f'
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.authentication.AnonymousAuthenticationFilter  - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@6fabe8e0: Principal: anonymousUser; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffe9938: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: F09C61DDA9D42B649B89CD650863A289; Granted Authorities: ROLE_ANONYMOUS'
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - /app/home at position 6 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.session.SessionManagementFilter@1f29202'
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - /app/home at position 7 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.access.ExceptionTranslationFilter@77240701'
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy  - /app/home at position 8 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.access.intercept.FilterSecurityInterceptor@72e500b4'
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource  - Converted URL to lowercase, from: '/app/home'; to: '/app/home'
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource  - Candidate is: '/app/home'; pattern is /app/*; matched=true
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.intercept.FilterSecurityInterceptor  - Secure object: FilterInvocation: URL: /app/home; Attributes: [ROLE_USER]
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.intercept.FilterSecurityInterceptor  - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@6fabe8e0: Principal: anonymousUser; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffe9938: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: F09C61DDA9D42B649B89CD650863A289; Granted Authorities: ROLE_ANONYMOUS
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.access.vote.AffirmativeBased  - Voter: org.springframework.security.access.vote.RoleVoter@4bb7d66d, returned: -1
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.access.vote.AffirmativeBased  - Voter: org.springframework.security.access.vote.AuthenticatedVoter@eb5417f, returned: 0
TRACE   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.web.context.support.XmlWebApplicationContext  - Publishing event in Root WebApplicationContext: org.springframework.security.access.event.AuthorizationFailureEvent[source=FilterInvocation: URL: /app/home]
DEBUG   2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.ExceptionTranslationFilter  - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied

1 Ответ

0 голосов
/ 02 февраля 2020

Я смог заставить вышеуказанный код работать, указав атрибут action и login-processing-url для '/login'. При такой конфигурации Spring активирует встроенный фильтр для проверки имени пользователя и пароля. Затем он переходит к конечной точке, указанной default-target-url.

...