Пример аннотации Hello Security Hello World

Пример аннотации Hello World в Spring Security

security

В предварительном просмотреpost мы используем файлы XML для настройки безопасности Spring в среде Spring MVC. В этом руководстве мы покажем вам, как преобразовать предыдущий проект Spring Security на базе XML в чистый проект аннотаций Spring.

Используемые технологии:

  1. Весна 3.2.8. ВЫПУСК

  2. Spring Security 3.2.3.RELEASE

  3. Затмение 4.2

  4. JDK 1.6

  5. Maven 3

  6. Tomcat 7 (Servlet 3.x)

Несколько заметок

  1. В этом руководствеWebApplicationInitializer используется для автоматической загрузки Spring Context Loader, который поддерживается только в контейнере Servlet 3.x, например, Tomcat 7 и Jetty 8.

  2. Поскольку мы используемWebApplicationInitializer, файлweb.xml НЕ требуется.

  3. Аннотации Spring Security поддерживаются в более старом контейнере Servlet 2.x, например, Tomcat 6. Если вы используете классический XML-файл для загрузки контекста Spring, этот учебник все еще может быть развернут в контейнере Servlet 2.x, например, Tomcat 6

1. Проект Демо

Посмотри, как это работает.

2. Структура каталогов

Просмотрите окончательную структуру каталогов этого руководства.

spring-security-helloworld-annotation-directory

3. Зависимости Spring Security

Чтобы использовать безопасность Spring, вам нужныspring-security-web иspring-security-config.

pom.xml

    
        1.6
        3.2.8.RELEASE
        3.2.3.RELEASE
        1.2
    

    

        
        
            org.springframework
            spring-core
            ${spring.version}
        

        
            org.springframework
            spring-web
            ${spring.version}
        

        
            org.springframework
            spring-webmvc
            ${spring.version}
        

        
        
            org.springframework.security
            spring-security-web
            ${spring.security.version}
        

        
            org.springframework.security
            spring-security-config
            ${spring.security.version}
        

        
        
            jstl
            jstl
            ${jstl.version}
        

    

4. Spring MVC Web Application

Простой контроллер:

  1. Если URL =/welcome или/, вернуть страницу приветствия.

  2. Если URL =/admin, вернуть страницу администратора.

  3. Если URL =/dba, вернуть страницу администратора.

Позже мы защитим URL-адреса/admin и/dba.

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.servlet.ModelAndView;

@Controller
public class HelloController {

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

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security Hello World");
        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 Hello World");
        model.addObject("message", "This is protected page - Admin Page!");
        model.setViewName("admin");

        return model;

    }

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

        ModelAndView model = new ModelAndView();
        model.addObject("title", "Spring Security Hello World");
        model.addObject("message", "This is protected page - Database Page!");
        model.setViewName("admin");

        return model;

    }

}

Две страницы JSP.

hello.jsp

<%@page session="false"%>


    

Title : ${title}

Message : ${message}

admin.jsp

<%@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. Конфигурация Spring Security

5.1 Создайте файл конфигурации Spring Security и пометьте его@EnableWebSecurity

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");
      auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
      auth.inMemoryAuthentication().withUser("dba").password("123456").roles("DBA");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

      http.authorizeRequests()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .antMatchers("/dba/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')")
        .and().formLogin();

    }
}

Эквивалент XML-файла Spring Security:

    
        
        
    

    
      
        
        
        
        
        
      
    

5.2 Создайте класс extendsAbstractSecurityWebApplicationInitializer, он автоматически загрузитspringSecurityFilterChain.

SpringSecurityInitializer.java

package com.example.config.core;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
   //do nothing
}

Эквивалент Spring Security в файлеweb.xml:

    
        springSecurityFilterChain
        org.springframework.web.filter.DelegatingFilterProxy
                
    

    
        springSecurityFilterChain
        /*
    

6. Конфигурация Spring MVC

6.1 Класс Config, определяющий технологию представления и импорт вышеSecurityConfig.java.

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;
    }

}

Эквивалент XML-файла Spring:

    

    
        
            /WEB-INF/pages/
        
        
            .jsp
        
    

6.2 Создайте классInitializer, чтобы загрузить все.

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[] { "/" };
    }

}

Готово.

Note
В среде контейнера Servlet 3.x + контейнер Spring автоматически обнаружит и загрузит классыInitializer.

7. Demo

7.1. Страница приветствия -http://localhost:8080/spring-security-helloworld-annotation/welcome

spring-security-helloworld-annotation-welcome

7.2 Try to access /admin page, Spring Security will intercept the request and redirect to /login, and a default login form is displayed.

spring-security-helloworld-annotation-login

7.3. Если имя пользователя и пароль неверны, будут отображаться сообщения об ошибках, и Spring будет перенаправлять на этот URL/login?error.

spring-security-helloworld-annotation-login-error

7.4. Если имя пользователя и пароль верны, Spring перенаправит запрос на исходный запрошенный URL-адрес и отобразит страницу.

spring-security-helloworld-annotation-admin

7.5. Для неавторизованного пользователя Spring отобразит страницу с отказом в доступе 403. Например, пользователь «example» или «dba» пытается получить доступ к URL-адресу/admin.

spring-security-helloworld-annotation-403

Скачать исходный код

Скачать -spring-security-helloworld-annotation.zip (12 КБ)