SpringMVC4零配置--SpringSecurity相关配置【SpringSecurityConfig】

 SpringSecurity的配置相对来说有些复杂,如果是完整的bean配置,则需要配置大量的bean,所以xml配置时使用了命名空间来简化配置,同样,spring为我们提供了一个抽象类WebSecurityConfigurerAdapter和一个注解@EnableWebMvcSecurity,达到同样减少bean配置的目的,如下:

 

applicationContext-SpringSecurityConfig.xml

<http security="none" pattern="/static/**" />
	<http security="none" pattern="/**/*.jsp" />

	<http auto-config='true' access-decision-manager-ref="accessDecisionManager" access-denied-page="/login"
		use-expressions="true">
		<logout logout-url="/logout" invalidate-session="true"
			logout-success-url="/login" />


		<form-login login-page="/login" authentication-failure-url="/login?error=1"
			login-processing-url="/j_spring_security_check" password-parameter="j_password"
			username-parameter="j_username" />


		<intercept-url pattern="/**/*.do*" access="hasRole('ROLE_USER')" />
		<intercept-url pattern="/**/*.htm" access="hasRole('ROLE_ADMIN')" />

		<session-management session-fixation-protection="changeSessionId">
			<concurrency-control max-sessions="1"
				expired-url="/access/sameLogin.do" />
		</session-management>

		<remember-me key="webmvc#FD637E6D9C0F1A5A67082AF56CE32485"
			remember-me-parameter="remember-me" />
	</http>

	<!-- 启用表达式 为了后面的投票器做准备 -->
	<beans:bean
		class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"
		id="expressionHandler" />
	<beans:bean
		class="org.springframework.security.web.access.expression.WebExpressionVoter"
		id="expressionVoter">
		<beans:property name="expressionHandler" ref="expressionHandler" />
	</beans:bean>

	<!-- Automatically receives AuthenticationEvent messages -->
	<beans:bean id="loggerListener"
		class="org.springframework.security.authentication.event.LoggerListener" />
	<beans:bean id="authorizationListener"
		class="org.springframework.security.access.event.LoggerListener" />

	<!-- 认证管理器,使用自定义的UserDetailsService,并对密码采用md5加密 -->
	<authentication-manager>
		<authentication-provider user-service-ref="userService">
			<password-encoder hash="md5" />
		</authentication-provider>
	</authentication-manager>





	<beans:bean id="userService" class="web.security.CP_UserDetailsService" />

	<beans:bean id="accessDecisionManager"
		class="org.springframework.security.access.vote.AffirmativeBased">
		<beans:property name="decisionVoters">
			<beans:list>
				<beans:bean class="org.springframework.security.access.vote.RoleVoter" />
				<beans:bean
					class="org.springframework.security.access.vote.AuthenticatedVoter" />
				<beans:ref bean="expressionVoter" />
			</beans:list>
		</beans:property>
	</beans:bean>

SpringSecurityConfig.java

@Configuration
@EnableWebMvcSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

	private static final Logger logger = Logger
			.getLogger(SpringSecurityConfig.class);

	@Override
	public void configure(WebSecurity web) throws Exception {
		// 设置不拦截规则
		web.ignoring().antMatchers("/static/**", "/**/*.jsp");

	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 设置拦截规则
		// 自定义accessDecisionManager访问控制器,并开启表达式语言
		http.authorizeRequests().accessDecisionManager(accessDecisionManager())
				.expressionHandler(webSecurityExpressionHandler())
				.antMatchers("/**/*.do*").hasRole("USER")
				.antMatchers("/**/*.htm").hasRole("ADMIN").and()
				.exceptionHandling().accessDeniedPage("/login");

		// 开启默认登录页面
		// http.formLogin();

		// 自定义登录页面
		http.csrf().disable().formLogin().loginPage("/login")
				.failureUrl("/login?error=1")
				.loginProcessingUrl("/j_spring_security_check")
				.usernameParameter("j_username")
				.passwordParameter("j_password").permitAll();

		// 自定义注销
		http.logout().logoutUrl("/logout").logoutSuccessUrl("/login")
				.invalidateHttpSession(true);

		// session管理
		http.sessionManagement().sessionFixation().changeSessionId()
				.maximumSessions(1).expiredUrl("/");

		// RemeberMe
		http.rememberMe().key("webmvc#FD637E6D9C0F1A5A67082AF56CE32485");

	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth)
			throws Exception {

		// 自定义UserDetailsService
		auth.userDetailsService(userDetailsService()).passwordEncoder(
				new Md5PasswordEncoder());

	}

	@Bean
	public CP_UserDetailsService userDetailsService() {
		logger.info("CP_UserDetailsService");
		CP_UserDetailsService userDetailsService = new CP_UserDetailsService();
		return userDetailsService;
	}

	@Bean
	public LoggerListener loggerListener() {
		logger.info("org.springframework.security.authentication.event.LoggerListener");
		LoggerListener loggerListener = new LoggerListener();

		return loggerListener;
	}

	@Bean
	public org.springframework.security.access.event.LoggerListener eventLoggerListener() {
		logger.info("org.springframework.security.access.event.LoggerListener");
		org.springframework.security.access.event.LoggerListener eventLoggerListener = new org.springframework.security.access.event.LoggerListener();

		return eventLoggerListener;
	}

	/*
	 * 
	 * 这里可以增加自定义的投票器
	 */
	@SuppressWarnings("rawtypes")
	@Bean(name = "accessDecisionManager")
	public AccessDecisionManager accessDecisionManager() {
		logger.info("AccessDecisionManager");
		List<AccessDecisionVoter> decisionVoters = new ArrayList<AccessDecisionVoter>();
		decisionVoters.add(new RoleVoter());
		decisionVoters.add(new AuthenticatedVoter());
		decisionVoters.add(webExpressionVoter());// 启用表达式投票器

		AffirmativeBased accessDecisionManager = new AffirmativeBased(
				decisionVoters);

		return accessDecisionManager;
	}

	/*
	 * 表达式控制器
	 */
	@Bean(name = "expressionHandler")
	public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {
		logger.info("DefaultWebSecurityExpressionHandler");
		DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
		return webSecurityExpressionHandler;
	}

	/*
	 * 表达式投票器
	 */
	@Bean(name = "expressionVoter")
	public WebExpressionVoter webExpressionVoter() {
		logger.info("WebExpressionVoter");
		WebExpressionVoter webExpressionVoter = new WebExpressionVoter();
		webExpressionVoter.setExpressionHandler(webSecurityExpressionHandler());
		return webExpressionVoter;
	}

}

 

SpringMVC4零配置 :代码下载

SpringMVC4零配置--web.xml

SpringMVC4零配置--应用上下文配置【AppConfig】

SpringMVC4零配置--SpringSecurity相关配置【SpringSecurityConfig】

SpringMVC4零配置--Web上下文配置【MvcConfig】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值