Exemple d’annotation de formulaire de connexion personnalisée Spring Security

Exemple d'annotation de formulaire de connexion personnalisé Spring Security

Dans ce didacticiel, nous allons convertir le projetSpring Security custom login form (XML) précédent en un projet purement basé sur des annotations.

Technologies utilisées:

  1. Spring 3.2.8.RELEASE

  2. Spring Security 3.2.3.RELEASE

  3. Eclipse 4.2

  4. JDK 1.6

  5. Maven 3

  6. Tomcat 7 (Servlet 3.x)

Note
Dans cet exemple, les derniersSpring Security hello world annotation example seront réutilisés, améliorez-le pour prendre en charge un formulaire de connexion personnalisé.

1. Démo du projet

2. Structure du répertoire

Consultez la structure finale des répertoires de ce didacticiel.

spring-security-custom-login-annotation-directory

3. Configuration de sécurité de printemps

Configuration de Spring Security via des annotations.

SecurityConfig.java

package com.example.config;

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
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                   .withUser("example").password("123456").roles("USER");
    }

    //.csrf() is optional, enabled by default, if using WebSecurityConfigurerAdapter constructor
    @Override
    protected void configure(HttpSecurity http) throws Exception {

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

L'équivalent du fichier XML de Spring Security:

    
      
      
      
      
      
    

    
      
        
        
        
      
    

4. Formulaire de connexion personnalisé

4.1 Page to display the custom login form. Si la protection CSRF est activée, n'oubliez pas d'ajouter${_csrf.token} dans le formulaire de connexion et de déconnexion.

login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


Login Page




    

Spring Security Custom Login Form (Annotation)

Login with Username and Password

${error}
${msg}
User:
Password:

4.2 Page to display the welcome message, default page.

hello.jsp

<%@page session="false"%>


    

Title : ${title}

Message : ${message}

4.3 This page is password protected, only authenticated user is allowed to access.

admin.jsp + logout

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>


    

Title : ${title}

Message : ${message}

Welcome : ${pageContext.request.userPrincipal.name} | Logout

5. Contrôleur Spring MVC

Un contrôleur simple.

HelloController.java

package com.example.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

    @RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
    public ModelAndView welcomePage() {

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security Custom Login Form");
        model.addObject("message", "This is welcome page!");
        model.setViewName("hello");
        return model;

    }

    @RequestMapping(value = "/admin**", method = RequestMethod.GET)
    public ModelAndView adminPage() {

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security Custom Login Form");
        model.addObject("message", "This is protected page!");
        model.setViewName("admin");

        return model;

    }

    //Spring Security see this :
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(
        @RequestParam(value = "error", required = false) String error,
        @RequestParam(value = "logout", required = false) String logout) {

        ModelAndView model = new ModelAndView();
        if (error != null) {
            model.addObject("error", "Invalid username and password!");
        }

        if (logout != null) {
            model.addObject("msg", "You've been logged out successfully.");
        }
        model.setViewName("login");

        return model;

    }

}

6. Classes d'initialisation

Voici les classes Initializer pour en faire un pur projet basé sur des annotations.

6.1 Initializer class to enable the Spring Security configuration.

SpringSecurityInitializer.java

package com.example.config.core;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

}

6.2 Initializer class to enable the Spring MVC.

SpringMvcInitializer.java

package com.example.config.core;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.example.config.AppConfig;

public class SpringMvcInitializer
    extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[] { AppConfig.class };
    }

    @Override
    protected Class[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

AppConfig.java

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.example.web.*" })
@Import({ SecurityConfig.class })
public class AppConfig {

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver
                           = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

}

7. Demo

spring-security-custom-login-annotation-welcome

7.2 Try to access /admin page, your custom login form is displayed.

spring-security-custom-login-annotation-login

7.3. Si le nom d'utilisateur et le mot de passe sont incorrects, affichez/login?error.

spring-security-custom-login-annotation-error

7.4. Si le nom d'utilisateur et le mot de passe sont corrects, Spring redirigera la demande vers l'URL d'origine demandée et affichera la page.

spring-security-custom-login-annotation-admin

7.5. Essayez de vous déconnecter, il sera redirigé vers la page/login?logout.

spring-security-custom-login-annotation-logout

Télécharger le code source