English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

exemple XML de Spring Security

Dans ce tutoriel, nous utiliseronsMVC Spring implémentation du cadre Spring Security。Tous les exemples sont basés sur Spring MVC et sont créés avec un projet Maven.

Nous utilisons Spring Security 5.0.0.RELEASE Version, voici les dépendances Maven, que nous utilisons dans tous les exemples.

<dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.0.0.RELEASE</version>
</dependency>

Pour implémenter Spring Security dans une application Spring, nous pouvons le configurer en utilisant XML ou une configuration basée sur Java.

Regardons un exemple où nous utiliserons XML pour configurer Spring Security.

Créer un projet Maven

Comme nous, cliquez sur Fichier Menu trouver Nouveau→Projet Maven dans l'écran capture suivant.

Sélectionnez le nom du projet et l'emplacement

Fournissez le nom du projet

Fournissez le nom du projet, puis sélectionnez le type de paquet suivant en suivant les étapes suivantes war(archive réseau).

TerminéCe projet créera une structure de répertoires vide pour le projet, comme suit.

Au début, il était vide. Donc, créons une application Spring MVC et intégrons Spring Security.

Voici la structure de notre projet. Il contient un contrôleur, trois fichiers XML et deux fichiers JSP.

le code source du projet Spring Security

Le nom de notre projet est springsecurity ,y compris les fichiers source suivants.

contrôleur

HomeController. Java

package com.w3codebox.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HomeController {
    
    @RequestMapping(value="/, method=RequestMethod.GET)
    public String home() {
        return \
    }
    
    @RequestMapping(value="/admin", method=RequestMethod.GET)
    public String privateHome() {
        return "privatePage";
    }
}

Spring security configuration

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.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">
    <http auto-config="true">
        <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
    </http>
    <authentication-manager>
      <authentication-provider>
        <user-service>
        <user name="admin" password="1234" authorities="hasRole(ROLE_ADMIN)" />
        </user-service>
      </authentication-provider>
    </authentication-manager>
</beans:beans>

Servlet调度程序

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven />
   <context:component-scan base-package="com.w3codebox.controller">
   </context:component-scan>
   <context:annotation-config></context:annotation-config>
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/views/></property>
      <property name="suffix" value=".jsp"></property>
   </bean>
</beans>

Web描述符

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
        
        <!-- Spring Configuration -->
        <servlet>
            <servlet-name>spring</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        
        <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
        
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/spring-servlet.xml
                /WEB-INF/spring-security.xml
            </param-value>
        </context-param>
</web-app>

项目依赖项

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.w3codebox</groupId>
  <artifactId>springsecurity</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>   
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
  <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>5.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.0.0.RELEASE</version>
    </dependency>
        
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>

Consulter la page

home.jsp

<html>
<head>
<meta content="text/html; charset=UTF-8">
<title>Home</title>
</head>
<body>
<h2>Bienvenue à w3codebox spring tutorial!</h2>
</body>
</html>

privatePage.jsp

home.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin</title>
</head>
<body>
Hello Admin
</body>
</html>

Sortie

Ce exemple utilise Apache Tomcat v9.0 s'exécute. Après l'exécution, il produira les sorties suivantes pour le navigateur.

À l'origine, il présentera home.jsp Page, qui affiche les sorties suivantes.

Si nous saisissons/ admin Alors, spring security sera ajouté à la page de gestion. Le navigateur, l'application produira les sorties suivantes.

URL de la requête: http: //localhost: 8080/springsecurity/admin

Maintenant, voici la véritable magie de la protection des ressources fournie par Spring Security.

Voici les modules fournis par Spring Security, que nous n'avons pas créés. Il vérifie également les entrées de l'utilisateur.

Fournir des informations de connexion incorrectes.

Si nous fournissons des informations de connexion incorrectes, il utilisera celles que nous avons spring-security.xml Vérification des noms d'utilisateur et mots de passe mentionnés dans le fichier.

Après la vérification, si les informations de connexion ne sont pas correctes, un message d'erreur sera généré.

Dans cet exemple, nous avons vu le module de connexion de Spring Security et comment il vérifie le nom d'utilisateur et le mot de passe fournis.

À présent, nous allons réaliser des logiques supplémentaires sur le thème, par exemple : présenter l'utilisateur après une connexion réussie.