在预览文章中 ,我们使用XML文件在Spring MVC环境中配置Spring Security。 在本教程中,我们将向您展示如何将以前的基于XML的Spring Security项目转换为纯Spring批注项目。
使用的技术:
- 春天3.2.8。发布
- Spring Security 3.2.3发布
- Eclipse 4.2
- JDK 1.6
- Maven 3
- Tomcat 7(Servlet 3.x)
很少注意
- 本教程使用
WebApplicationInitializer
自动加载Spring Context Loader,仅Servlet 3.x容器(例如Tomcat 7和Jetty 8)支持。 - 由于我们使用的是
WebApplicationInitializer
,因此不需要web.xml
文件。 - 较早的Servlet 2.x容器(例如Tomcat 6)支持Spring Security批注。如果使用经典XML文件加载Spring上下文,则本教程仍可以在Servlet 2.x容器(例如Tomcat)上部署6
1.项目演示
看看它怎么运作。
2.目录结构
查看本教程的最终目录结构。
3. Spring安全依赖性
要使用Spring安全性,您需要spring-security-web
和spring-security-config
。
<properties>
<jdk.version>1.6</jdk.version>
<spring.version>3.2.8.RELEASE</spring.version>
<spring.security.version>3.2.3.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
</properties>
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<!-- jstl for jsp page -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
</dependencies>
4. Spring MVC Web应用程序
一个简单的控制器:
- 如果URL =
/welcome
或/
,则返回问候页面。 - 如果URL =
/admin
,则返回管理页面。 - 如果URL =
/dba
,则返回管理页面。
稍后,我们将保护/admin
和/dba
URL。
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.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页面。
<%@page session="false"%>
<html>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1>
</body>
</html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1>
<c:if test="${pageContext.request.userPrincipal.name != null}">
<h2>Welcome : ${pageContext.request.userPrincipal.name}
| <a href="<c:url value="/logout" />" > Logout</a></h2>
</c:if>
</body>
</html>
5. Spring安全配置
5.1创建一个Spring Security配置文件,并用@EnableWebSecurity
注释
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");
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();
}
}
相当于Spring Security xml文件:
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
<intercept-url pattern="/dba**" access="ROLE_ADMIN,ROLE_DBA" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="mkyong" password="123456" authorities="ROLE_USER" />
<user name="admin" password="123456" authorities="ROLE_ADMIN" />
<user name="dba" password="123456" authorities="ROLE_DBA" />
</user-service>
</authentication-provider>
</authentication-manager>
5.2创建一个扩展AbstractSecurityWebApplicationInitializer
的类,它将自动加载springSecurityFilterChain
。
package com.mkyong.config.core;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
//do nothing
}
相当于web.xml
文件中的Spring Security:
<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>
6. Spring MVC配置
6.1一个Config类,定义视图的技术并将其导入SecurityConfig.java
之上。
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;
}
}
相当于Spring XML文件:
<context:component-scan base-package="com.mkyong.web.*" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
6.2创建一个Initializer
类,以加载所有内容。
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[] { "/" };
}
}
做完了
注意
在Servlet 3.x容器环境中,Spring容器将自动检测并加载Initializer
类。
7.演示
7.1。 欢迎页面– http:// localhost:8080 / spring-security-helloworld-annotation / welcome
7.2尝试访问/admin
页面,Spring Security将拦截请求并重定向到/login
,并显示默认的登录表单。
7.3。 如果用户名和密码不正确,将显示错误消息,Spring将重定向到该URL /login?error
。
7.4。 如果用户名和密码正确,Spring会将请求重定向到原始请求的URL并显示页面。
7.5。 对于未经授权的用户,Spring将显示403访问被拒绝页面。 例如,用户“ mkyong”或“ dba”尝试访问/admin
URL。
下载源代码
下载它– spring-security-helloworld-annotation.zip (12 KB)
参考文献
- Spring安全
- Spring Security Java配置预览:Web安全
- 您好Spring MVC Security Java Config
- 维基百科:Java Servlet
- 维基百科:Apache Tomcat
- Spring Security Hello World XML示例
翻译自: https://mkyong.com/spring-security/spring-security-hello-world-annotation-example/