2011-02-04 18 views
21

Soy nuevo a la primavera-seguridad (Java) y estoy buscando un buen y sencilla ejemplo de:Buscando un ejemplo de seguridad simple muelle

  1. Cómo utilizar la seguridad de muelle para conectarse y desconectarse

  2. Asegúrese de que existe la sesión en cada página y si no se redirigir a la entrada de nuevo

  3. Cómo obtener acceso a la sesión del usuario actual

Mi proyecto está trabajando actualmente con Spring MVC e hibernate.
He creado el loginAPI + loginDAO, ahora necesito combinar la seguridad y asegurar algunas de las páginas.

He buscado tutoriales, pero muchos de ellos son muy complicados.

+0

estoy manteniendo ejemplos de código en mi blog: http://technotes.tostaky.biz/p/spring_27.html – JVerstry

Respuesta

1

Si aún no ha visto this video by the lead developer of Spring Security. En realidad, se hace referencia en el sitio de Spring Security, pero es fácil pasar por alto. Aunque estoy de acuerdo, bueno Los ejemplos de Spring Security son difíciles de encontrar.

+0

gracias, suena bien pero la calidad es tan mala que no puedo ver el código en segundo plano. Por favor, si alguien puede publicar un ejemplo, sería genial. – MushMushon

1

Spring Security Tutorial by MKyong

how to perform database authentication (using both XML and Annotations) in Spring Security.

Tecnologías utilizadas:

Spring 3.2.8.RELEASE
Spring Security 3.2.3.RELEASE
primavera JDBC 3.2.3.RELEASE
Eclipse 4.2
JDK 1.6
Maven 3
Tomcat 6 o 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(); 
    } 
} 

Primavera-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> 
  • En felicitación anteriormente, los /admin y subcarpetas de que están protegidos todo contraseña.
  • login-page=”/login” - La página para mostrar el formulario de inicio de sesión personalizado
  • authentication-failure-url=”/login?error” - Si falla la autenticación, avance a la página /login?error
  • logout-success-url=”/login?logout” - Si cierre de sesión con éxito, hacia delante para ver /logout
  • username-parameter=”username” - El nombre de la solicitud, que contiene el "nombre de usuario". En HTML, este es el nombre del texto de entrada.
  • <csrf/> - desactiva la solicitud de falsificación Cross Site protección (CSRF)