`
hanqunfeng
  • 浏览: 1526143 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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】

分享到:
评论
3 楼 bing_it 2016-03-14  
2 楼 bewithme 2015-08-25  
Md5PasswordEncoder  被谁吃了吗
1 楼 bewithme 2015-08-20  
楼主你的抠抠号多少,请教一下这个如果权限都配置在数据库里的,如何写这些代码?我的抠抠359709421

相关推荐

Global site tag (gtag.js) - Google Analytics