Рубрики
Без рубрики

Пример аннотации Пользовательской формы входа Spring Security

– Пример аннотации Пользовательской формы входа в систему Spring Security

Автор оригинала: mkyong.

В этом уроке мы преобразуем предыдущую пользовательскую форму входа в систему Spring Security (XML) проект в проект на основе аннотаций.

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

  1. Пружина 3.2.8.ОТПУСТИТЕ
  2. Пружинная защита 3.2.3.ВЫПУСК
  3. Затмение 4.2
  4. JDK 1.6
  5. Мавен 3
  6. Tomcat 7 (сервлет 3.x)

1. Демонстрация проекта

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

Ознакомьтесь с окончательной структурой каталогов этого руководства.

3. Конфигурация безопасности Spring

Настройка безопасности Spring с помощью аннотаций.

package com.mkyong.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("mkyong").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(); 		
	}
}

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

	
	  
	  
	  
	  
	  
	

	
	  
	    
		
	    
	  
	

4. Пользовательская Форма Входа В Систему

4.1 Страница для отображения пользовательской формы входа. Если защита CSRF включена, не забудьте добавить ${_csrf.token} как в форме входа, так и в форме выхода.

<%@ 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 session="false"%>


	

Title : ${title}

Message : ${message}

4.3 Эта страница защищена паролем, доступ к ней разрешен только аутентифицированному пользователю.

<%@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. Пружинный контроллер MVC

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

package com.mkyong.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. Классы инициализаторов

Вот классы инициализаторов, чтобы сделать этот проект чисто аннотационным.

6.1 Класс инициализатора для включения конфигурации безопасности Spring.

package com.mkyong.config.core;

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

}

6.2 Класс инициализатора для включения Spring MVC.

package com.mkyong.config.core;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.mkyong.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[] { "/" };
	}
	
}
package com.mkyong.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.mkyong.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. Демонстрация

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

7.2 Попытайтесь получить доступ /администратор страница, отображается ваша пользовательская форма входа в систему.

7.3. Если имя пользователя и пароль неверны, отобразите /логин?ошибка .

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

7.5. Попробуйте выйти из системы, он перенаправит на /вход в систему?выход из системы страница.

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

Рекомендации

  1. Пример аннотации Spring Security Hello World
  2. Создание пользовательской формы входа в систему
  3. Основные моменты Spring Security 3.2.0.RC1: Защита CSRF
  4. Википедия: Подделка межсайтового запроса

Оригинал: “https://mkyong.com/spring-security/spring-security-custom-login-form-annotation-example/”