tutorial j_spring_security_check example spring spring-mvc spring-security spring-java-config

j_spring_security_check - spring security spring boot



JavaConfiguration para Spring 4.0+Security 3.2+j_spring_security_check (1)

En la versión 3.2, los parámetros posteriores han cambiado de j_username a username y j_password a password. La URL de inicio de sesión también ha cambiado de / j_spring_security_check a / login.

Consulte este enlace para obtener una explicación de por qué se implementó este cambio: http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-httpsecurity . Estos son los cambios:

  • GET / login representa la página de inicio de sesión en lugar de / spring_security_login

  • POST / login autentica al usuario en lugar de / j_spring_security_check

  • El parámetro de nombre de usuario predeterminado es nombre de usuario en lugar de j_username

  • El parámetro de contraseña se establece por defecto en contraseña en lugar de j_password

Y esto para un ejemplo de un formulario de inicio de sesión: http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-form

  1. Crear una página de inicio de sesión

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Test</title> <script src="static/js/jquery-1.10.2.min.js"></script> <script src="static/js/app-controller.js"></script> </head> <body> <div>Login</div> <form name="f" action="<c:url value="/j_spring_security_check"/>" method="POST"> <label for="password">Username</label>&nbsp;<input type="text" id="j_username" name="j_username"><br/> <label for="password">Password</label>&nbsp;<input type="password" id="j_password" name="j_password"><br/> <input type="submit" value="Validate">&nbsp;<input name="reset" type="reset"> <input type="hidden" id="${_csrf.parameterName}" name="${_csrf.parameterName}" value="${_csrf.token}"/> </form> <hr/> <c:if test="${param.error != null}"> <div> Failed to login. <c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}"> Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" /> </c:if> </div> </c:if> <hr/> <input type="button" value="Echo" id="echo" name="echo" onclick="AppController.echo();"> <div id="echoContainer"></div> </body> </html>

  2. Declare un WebSecurityConfigurer AQUÍ ES DONDE ME FALTAba j_username AND j_password

    @Configuration @EnableWebSecurity @ComponentScan(basePackages = {"com.sample.init.security"}) public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter { @Inject private AuthenticationProvider authenticationProvider; @Inject public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers( "/resources/**", "/static/**", "/j_spring_security_check", "/AppController/echo.html").permitAll() .anyRequest().authenticated() .and() .formLogin() .usernameParameter("j_username") /* BY DEFAULT IS username!!! */ .passwordParameter("j_password") /* BY DEFAULT IS password!!! */ .loginProcessingUrl("/j_spring_security_check") .loginPage("/") .defaultSuccessUrl("/page") .permitAll() .and() .logout() .permitAll(); } @Override public void configure(WebSecurity web) throws Exception { web .ignoring() .antMatchers("/static/**"); } }

  3. Declarar un WebMvcConfigurer

    @EnableWebMvc @Configuration @ComponentScan(basePackages = { "com.app.controller", "com.app.service", "com.app.dao" }) public class WebMvcConfigurer extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/page").setViewName("page"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("static/**").addResourceLocations("static/"); } }

  4. Declarar un inicializador de seguridad

    public class SecurityWebAppInitializer extends AbstractSecurityWebApplicationInitializer { }

  5. Declarar una aplicación Initialzer

    public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[]{WebSecurityConfigurer.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{WebMvcConfigurer.class, DataSourceConfigurer.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }

  6. Implemente su Proveedor de Autenticación personalizado

    @Component @ComponentScan(basePackages = {"com.app.service"}) public class CustomAuthenticationProvider implements AuthenticationProvider { private static final Logger LOG = LoggerFactory.getLogger(CustomAuthenticationProvider.class); @Inject private AppService service; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { //Thread.dumpStack(); String username = authentication.getName(); String password = authentication.getCredentials().toString(); String message = String.format("Username: ''%s'' Password: ''%s''", username, password); UserBean userBean = service.validate(username, password); LOG.debug(message); if (userBean != null) { List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority("USER")); return new UsernamePasswordAuthenticationToken(userBean, authentication, grantedAuths); } else { String error = String.format("Invalid credentials [%s]", message); throw new BadCredentialsException(error); } } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } }

Me estoy saltando EchoController, AppService, AppDao y UserBean.

Gracias.