2016-11-16 2 views
0

Я пытаюсь понять безопасность весны-сети. Для этого я создал веб-приложение со страницей входа и двумя разными пользователями.Spring web security: не удалось получить доступ к странице после успешного входа в систему

  1. Администратор
  2. Пользователь/Гость

LoginController класс обрабатывает три типа URL-адресов.

/* 
    Used to guide the user to login page 
*/ 
@RequestMapping(value="/login/login.htm", method=RequestMethod.GET) 
public ModelAndView login(){ 
    ModelAndView modelAndView = new ModelAndView("login"); 
    System.out.println("Rendering login page................."); 
    return modelAndView; 
} 

/* 
Process the successful login and redirects user to Admin/User page as per the role. 
*/ 
@RequestMapping(value="/login/success") 
public ModelAndView loginSuccess(HttpServletRequest request){ 
    ModelAndView modelAndView = new ModelAndView(); 

    Set<String> roles = AuthorityUtils 
       .authorityListToSet(SecurityContextHolder.getContext() 
         .getAuthentication().getAuthorities()); 
    System.out.println("ROLES: "+roles); 

    if(roles.contains("USER_ADMIN")){ 
     modelAndView.setViewName("admin"); 
    }else{ 
     modelAndView.setViewName("user"); 
    } 

    return modelAndView; 
} 

/* 
    Admin page has a hyper link to access the manage user page. It is handled here. 
*/ 
@RequestMapping(value="/admin/manageUser.htm", method=RequestMethod.GET) 
public ModelAndView manageUser(){ 
    ModelAndView modelAndView = new ModelAndView("manageUser"); 
    return modelAndView; 
} 

web.xml

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/SecurityConfig.xml</param-value> 
</context-param> 

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


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


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

весной безопасности я все ограничения URLs с 'админ/' & "пользователь/.

<http auto-config="true"> 
    <intercept-url pattern="/admin/**" access="hasRole('USER_ADMIN')"/> 
    <intercept-url pattern="/user/**" access="hasRole('USER_GUEST')"/> 
    <form-login login-page="/login/login.htm" 
     username-parameter="userName" password-parameter="password" 
     login-processing-url="/j_spring_security_check" 
     authentication-success-forward-url="/login/success"/> 

    <remember-me/> 

</http> 

<authentication-manager> 
    <authentication-provider> 
     <user-service> 
      <user name="renju" password="12345" authorities="USER_ADMIN"/> 
      <user name="guest" password="guest" authorities="USER_GUEST"/> 
     </user-service> 
    </authentication-provider> 
</authentication-manager> 

Когда я пытаюсь 'http://localhost:8080/SpringWebSecurityThree-0.0.1-SNAPSHOT/login/login.htm', приложение открывает собственную страницу входа в систему. enter image description here

При предоставлении имени пользователя и пароля администратора приложение открывает страницу администратора.

enter image description here

Теперь, когда я нажимаю на «ManageUser», я ожидал приложение, чтобы взять меня TOTHE manageuser страницу. Но в нем говорится «Доступ запрещен».

enter image description here

Я считаю, что это что-то делать с конст-URL дал.

Не могли бы вы помочь мне решить эту проблему?

Я отправляю страниц JSP тоже ..

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
    <c:if test="${not empty error}"> 
     <c:out value="${error}"></c:out> 
    </c:if> 
    <form action="../j_spring_security_check" method="post"> 

     <table> 

      <tr> 
       <td>UserName</td> 
       <td><input type="text" name="userName"></td> 
      </tr> 
      <tr> 
       <td>Password</td> 
       <td><input type="password" name="password"></td> 
      </tr> 

         <tr> 
       <td><input type="submit" name="LOGIN"></td> 
      </tr> 
     </table> 

     <input type="hidden" name="${_csrf.parameterName}" 
      value="${_csrf.token}" /> 


    </form> 

</body> 
</html> 

admin.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
    <%@ page session="true" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
    Admin Page !!!!!!!!!! 
    <a href="${pageContext.request.contextPath}/admin/manageUser.htm">ManageUser</a> 
    <% session.setAttribute("userType", "admin"); %> 
</body> 
</html> 

manageuser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<%@ page session="true" %> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
    Managing User.... 
    <br/> 
    Logged In UserType: 
    <% 
     out.println(session.getAttribute("userType")); 
    %> 
</body> 
</html> 

ответ

0

Вы используете create-session = "never", который потребуется для повторной аутентификации для каждого вашего запроса.

<http auto-config="true" create-session="never"> 
    <intercept-url pattern="/admin/**" access="hasRole('USER_ADMIN')"/> 
    <intercept-url pattern="/user/**" access="hasRole('USER_GUEST')"/> 
    <form-login login-page="/login/login.htm" 
    username-parameter="userName" password-parameter="password" 
    login-processing-url="/j_spring_security_check" 
    authentication-success-forward-url="/login/success"/> 

    <remember-me/> 
</http> 

Это обычно используется, когда аутентификации на основе файлов cookie/сеансов не поддерживаются и не выполняются. Обязательно определите свою стратегию.

+0

Спасибо. Я не хранил его намеренно.Я сохранил его, пока я играл с тегом http, чтобы решить эту проблему. Также попробовал 'create-session =' always '. Это тоже не сработало. Удалили. – Renjith

+0

@Renju, пожалуйста, укажите журналы ошибок, чтобы определить проблему – ScanQR

+0

У меня нет журналов ошибок в консоли JBoss. Я считаю, что некоторые условия, которые я сохранил в конфигурации безопасности, блокируют его. Таким образом, нет ошибок. – Renjith

Смежные вопросы