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)
estoy manteniendo ejemplos de código en mi blog: http://technotes.tostaky.biz/p/spring_27.html – JVerstry