第9章 保护Web应用--Spring Security 之 HelloWord 基于注解形式

概述:

上一篇学习基于xml,继续学习基于javaConfig配置Spring Security

1、工程结构:


2、增加Controller一个方法 HelloController 

package com.jack.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 welcom page!");
		model.setViewName("hello");
		return model;
	}
	
	@RequestMapping(value ="/admin**", method= RequestMethod.GET)
	public ModelAndView adminPage(){
		ModelAndView model = new ModelAndView();
		model.addObject("title", "SpringSecurity 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;
	}
	
}
3、配置文件,主要包括Springmvc、 spring-security 、过滤器代理、DispatcherServlet  对应四个类


DispatcherServlet : 只要实现AbstractAnnotationConfigDispatcherServletInitializer 在Servlet3.0自动扫描继承该类定为Servlet,也就是tomcat7以上

package com.jack.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

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

}

SpringMVC:

package com.jack.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.jack.*"})
@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;
	}
}


总结:

1、@EnableWebMvc 启动webmvc 注解

2、@ComponentScan 扫描对应包

3、@Import 导入对应配置类,其实就是连接配置类的纽带,只要加载AppConfig, 自然会加载SecurityConfig.class


Spring-security:

package com.jack.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 // 启动web安全控制
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
		auth.inMemoryAuthentication().withUser("jack").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();
	}
	
	

}


总结:

1、@EnableWebSecurity 就是启动web安全, 也就是说明这个类是Spring-Security类

2、通过注入AuthenticationManagerBuilder来构建用户名和密码策略

3、通过连续点操作,inMemoryAuthentication() 表示内存级

4、antMatchers("/admin/**") 利用Ant的匹配规则, hasRole('ROLE_ADMIN') 是SpEL表达式

5、formLogin()表示表单登录

与之对应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>


4、配置过滤器代理,这个必须配置,没有拦截者,安全策略就是失去意义

package com.jack.config;

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

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer{

}

总结:

注意这个是没有@Component注解,却能被Spring实例化,说明是Servlet自动会寻找继承AbstractSecurityWebApplicationInitializer的类进行实例化

这里配置拦截mapping,它跟Servlet一样 “/”

等效于:

<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.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值