@parkito

Как настроить spring security?

Здравствуйте. Помогите, пожалуйста, подключить к моему прилложение spring-security.
Итак, я:
1) Прописал фреймворк в pom, web.
2) Первая страница, которая будет открываться (с формой логина и пароля) -index.jsp
c формой

<div class="col-sm-6 col-md-4 col-lg-3" style="margin:40px auto; float:none;">
    <form method="post" action="/main">
        <c:url var="loginUrl" value="/j_spring_security_check"></c:url>
        <div class="col-xs-12">
            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-addon"><i class="fa fa-fw fa-user"></i></div>
                    <input type="email" name="j_username" class="form-control" placeholder="E-mail">
                </div>
            </div>
            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-addon"><i class="fa fa-fw fa-lock"></i></div>
                    <input type="password" name="j_password" class="form-control" placeholder="Password">
                </div>
            </div>
        </div>


3) Пользователи и пароли хранятся в базе. Настройки spring-security.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"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xmlns:context="http://www.springframework.org/schema/context"
             xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            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">
    <beans:import resource="appServlet/servlet-context.xml"/>
    <!-- Configuring RoleVoter bean to use custom access roles, by default roles
        should be in the form ROLE_{XXX} -->
    <beans:bean id="roleVoter"
                class="org.springframework.security.access.vote.RoleVoter">
        <beans:property name="rolePrefix" value=""></beans:property>
    </beans:bean>

    <beans:bean id="accessDecisionManager"
                class="org.springframework.security.access.vote.AffirmativeBased">
        <beans:constructor-arg name="decisionVoters"
                               ref="roleVoter"/>
    </beans:bean>


    <http realm="JavaStudy example" use-expressions="false"
          authentication-manager-ref="dao-auth"
          access-decision-manager-ref="accessDecisionManager">
        <intercept-url pattern="/main" access="ROLE_USER,ROLE_ANONYMOUS"/>
        <intercept-url pattern="/user/*" access="ROLE_USER"/>
        <intercept-url pattern="/admin/*" access="ROLE_ADMIN"/>
        <form-login login-page="/index" default-target-url="/main"
                    authentication-failure-url="/login.jsp?error=true"/>
        <logout logout-url="/logout" logout-success-url="/main"/>
        <anonymous username="guest" granted-authority="ROLE_ANONYMOUS"/>
    </http>

    <authentication-manager>
        <authentication-provider>
            <user-service>
                <user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN"/>
                <user name="user" password="user" authorities="ROLE_USER"/>
                <user name="guest" password="guest" authorities="ROLE_GUEST"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

    <authentication-manager id="dao-auth">
        <authentication-provider user-service-ref="userDetailsService">
            <password-encoder ref="passwordEncoder"/>
        </authentication-provider>
    </authentication-manager>
    <beans:bean id="passwordEncoder"
                class="operator.utils.Converter">
    </beans:bean>


</beans:beans>


4) В контролере имею
@RequestMapping(value = "/main", method = RequestMethod.GET)
    public String dispatch(HttpServletRequest request, Locale locale, Model model) {
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User)
                SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User currentUser = userService.getUserByEMAil(user.getUsername());
        request.getSession().setAttribute("currentUserU", currentUser);
        request.getSession().setAttribute("language", RussianLanguage.getRussianLanguage());
        if (currentUser.getAccessLevel().getAccessLevelId() == 1) {
            return "user/index";
        }
        else if (currentUser.getAccessLevel().getAccessLevelId() == 3){
            return "admin/index";
        }
        else return "index";
    }


5) Организовал проверку пароля по хешу в Converter

Однако при прохождении формы получаю шибку Could not verify the provided CSRF token because your session was not found.

Что я делаю не так?
  • Вопрос задан
  • 1753 просмотра
Пригласить эксперта
Ответы на вопрос 1
zolt85
@zolt85
Программист
Добавьте в настройках в тег http такую штучку.
<csrf disabled="true"/>

Подробнее зачем все это и как работает описано в документации
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы