Подтвердить что ты не робот

Поиск простого примера безопасности Spring

Я новичок в spring -security (Java), и я ищу хороший и простой пример:

  • Как использовать spring безопасность для входа и выхода из системы

  • Убедитесь, что сеанс существует на каждой странице, а если не перенаправлен на вход снова

  • Как получить доступ к текущему сеансу пользователя

Мой проект в настоящее время работает с spring MVC и спящим.
Я создал loginAI + loginDAO, теперь мне нужно объединить безопасность и сделать некоторые из страниц обеспеченными.

Я искал учебники, но многие из них очень сложны.

4b9b3361

Ответ 5

Spring Учебник по безопасности от MKyong

как выполнить проверку подлинности базы данных (используя как XML, так и аннотации) в Spring Безопасность.

Используемые технологии:

Spring 3.2.8.RELEASE
Spring Безопасность 3.2.3.RELEASE
Spring JDBC 3.2.3.RELEASE
Eclipse 4.2
JDK 1.6
Maven 3
Tomcat 6 или 7 (Servlet 3.x)
MySQL Server 5.6

SecurityConfig.java

package com.mkyong.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery(
            "select username,password, enabled from users where username=?")
        .authoritiesByUsernameQuery(
            "select username, role from user_roles where username=?");
    }   

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .and()
          .formLogin().loginPage("/login").failureUrl("/login?error")
          .usernameParameter("username").passwordParameter("password")
        .and()
          .logout().logoutSuccessUrl("/login?logout")
        .and()
          .exceptionHandling().accessDeniedPage("/403")
        .and()
          .csrf();
    }
}

Spring -security.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>
  • В приведенном выше поздравлении, /admin и его подпапки защищены паролем.
  • login-page="/login" - Страница для отображения пользовательской формы входа
  • authentication-failure-url="/login?error" - Если аутентификация не удалась, перейдите на страницу /login?error
  • logout-success-url="/login?logout" - Если выход завершен, перейдите к просмотру /logout
  • username-parameter="username" - имя запроса, содержащего "имя пользователя". В HTML это имя вводимого текста.
  • <csrf/> - Включить защиту от перекрестного запроса (CSRF)