весенняя безопасность в веб-сервисе отдыха - PullRequest
0 голосов
/ 07 июня 2018

Я пытаюсь внедрить Spring Security в службу restweb.

Я всегда получаю сообщение " Вступление началось из-за неудачной аутентификации ".Это не входит в CustomAuthenticationProvider.java.Мой код возвращает меня от CustomEntryPoint.Я думаю, что есть неправильная конфигурация.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:web="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" version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value> WEB-INF/security-config.xml

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

  <servlet>
    <servlet-name>appServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

      <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/security-config.xml</param-value>
      </init-param>
     <load-on-startup>1</load-on-startup>
  </servlet>

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

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

<!--   <welcome-file-list>
    <welcome-file>/WEB-INF/index.jsp</welcome-file>
</welcome-file-list> -->
<!-- Tag Libary -->

</web-app>

Файл безопасности Spring

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

    <sec:http entry-point-ref="customEntryPoint" use-expressions="true">

        <sec:custom-filter ref="authenticationFilter"
            before="PRE_AUTH_FILTER" />

        <sec:intercept-url pattern="/**"
            access="hasAuthority('AUTH_USER')" />

        <sec:logout delete-cookies="JSESSIONID" />

        <sec:csrf disabled="true" />
    </sec:http>

    <context:component-scan base-package="org.arpit.java2blog" />

    <sec:authentication-manager alias="authenticationManager">
        <authentication-provider ref="customAuthenticationProvider" />
    </sec:authentication-manager>

    <!-- <context:component-scan base-package="org.arpit.java2blog" /> -->

    <beans:bean id="authenticationFilter"
        class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
        <beans:property name="authenticationManager" ref="authenticationManager" />
        <beans:property name="postOnly" value="false" />
        <beans:property name="authenticationSuccessHandler" ref="customSuccessHandler" />
    </beans:bean>

    <beans:bean id="customSuccessHandler"   class="org.arpit.java2blog.controller.CustomSuccessHandler" />
        <beans:bean id="customAuthenticationProvider"   class="org.arpit.java2blog.controller.CustomAuthenticationProvider" />

</beans:beans>

Файлы классов

package org.arpit.java2blog.controller;

import java.util.Collections;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication auth) 
      throws AuthenticationException {
        String username = auth.getName();
        String password = auth.getCredentials()
            .toString();
        System.out.println(username +"::"+password);

        if ("user".equals(username) && "pass".equals(password)) {
            return new UsernamePasswordAuthenticationToken
              (username, password, Collections.emptyList());
        } else {
            throw new
              BadCredentialsException("External system authentication failed");
        }
    }

    @Override
    public boolean supports(Class<?> auth) {
        return auth.equals(UsernamePasswordAuthenticationToken.class);
    }
}

package org.arpit.java2blog.controller;
import java.io.IOException;

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

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

@Component
public class CustomEntryPoint implements AuthenticationEntryPoint
{

        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException
        {
                    System.out.println("Entering commence due to failed Authentication");
                 response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized Access!" );
        }

}

package org.arpit.java2blog.controller;

import java.io.IOException;

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

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;


public class CustomSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler
{

        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException
        {
                System.out.println("authentication successful!");
        }
}

1 Ответ

0 голосов
/ 07 июня 2018

Похоже, что вы тормозите цепочку фильтров с этим customEntryPoint, потому что он запускается перед любой аутентификацией, и так как он отправляет response.sendError, цепочка, если она сломана.Итак, удалите этот bean-объект точки входа.
Вы можете зарегистрировать пользовательские обработчики успеха и ошибок, добавив их в sec: http secition:

<sec:form-login
        authentication-failure-handler-ref="authenticationFailedHandler"
        authentication-success-handler-ref="authenticationSuccessHandler" />

, где обработчик успеха:

@Component
public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        // success
    }
}

и неисправный обработчик:

@Component
public class AuthenticationFailedHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // super.onAuthenticationFailure(request, response, exception);    
        // failed
    }
}

Надеюсь, это поможет.

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