如何在spring应用程序中启用@Secured注释

时间:2018-06-08 14:58:04

标签: java spring spring-mvc spring-security

我在Spring 4.2.5.RELEASE应用程序中使用了sprig security 4.0.4.RELEASE。 我想使用@Secured注释在我的应用程序中实现方法级别的角色明智安全性 我尝试通过添加@EnableGlobalMethodSecurity(securedEnabled = true)来实现此功能,但发生了一些错误。

这是我的SecurityConfiguration类



package com.application.security;

import com.application.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Autowired
	@Qualifier("customUserDetailsService")
	UserDetailsService userDetailsService;

	@Autowired
    LoginSuccessHandler loginSuccessHandler;
	
	@Autowired
	PersistentTokenRepository tokenRepository;
	
		
	/*@Autowired
	public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService);
		auth.authenticationProvider(authenticationProvider());
	}*/
	
	@Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
	
	@Autowired
	public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService);
		auth.authenticationProvider(customDaoAuthenticationProvider());
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.sessionManagement().invalidSessionUrl("/logout");
		http.authorizeRequests()
				/*.antMatchers("/").access("hasRole('USER') or hasRole('ADMIN') or hasRole('DBA')")*/
				.antMatchers("/registration").permitAll()
				.antMatchers("/exclusion").permitAll()
				.antMatchers("/landing").permitAll()
				.antMatchers("/uploadSingle").permitAll()
				.antMatchers("/uploadSingleNoFile").permitAll()
				.antMatchers("/loadHtmlTableAjax").permitAll()
				.antMatchers("/AllclaimDetails").permitAll()
				.antMatchers("/deleteclaim").permitAll()
				.antMatchers("/claimComplete").permitAll()	
				.antMatchers("/exclusionComplete").permitAll()
				.anyRequest().authenticated()
				.and()
			.formLogin().loginPage("/login").permitAll()			
				.loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password")
				.successHandler(loginSuccessHandler)
				.failureUrl("/login?error=true")
				.and()
	        .logout()
	            .logoutUrl("/logout")
	            .deleteCookies("JSESSIONID")
	            .permitAll()
	            .and()
			.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository).tokenValiditySeconds(86400)
			    .and()
			    .csrf()
			    .and()
			    .exceptionHandling().accessDeniedPage("/Access_Denied");
	}
	
	@Override
	public void configure(WebSecurity web) throws Exception {
	    web
	       .ignoring()
	       .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/logoff");
	}
		
	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	public DaoAuthenticationProvider authenticationProvider() {
		DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
		authenticationProvider.setUserDetailsService(userDetailsService);
		authenticationProvider.setPasswordEncoder(passwordEncoder());
		return authenticationProvider;
	}
	
    @Bean
    CustomDaoAuthenticationProvider customDaoAuthenticationProvider() {
    	CustomDaoAuthenticationProvider customAuthenticationProvider = new CustomDaoAuthenticationProvider();
    	customAuthenticationProvider.setUserDetailsService(userDetailsService);
    	customAuthenticationProvider.setPasswordEncoder(passwordEncoder());
		return customAuthenticationProvider;
    }
    
	@Bean
	public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
		PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
				"remember-me", userDetailsService, tokenRepository);
		return tokenBasedservice;
	}

	@Bean
	public AuthenticationTrustResolver getAuthenticationTrustResolver() {
		return new AuthenticationTrustResolverImpl();
	}

}




当我提供@EnableGlobalMethodSecurity(securedEnabled = true)时,应用程序无法启动。我收到以下错误。

问题来自AuthenticationTrustResolver bean



AnnotationConfigWebApplicationContext:546 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appConfig': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'metaDataSourceAdvisor': Cannot resolve reference to bean 'methodSecurityMetadataSource' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration.setAuthenticationTrustResolver(org.springframework.security.authentication.AuthenticationTrustResolver); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setTrustResolver(org.springframework.security.authentication.AuthenticationTrustResolver); nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'getAuthenticationTrustResolver': Requested bean is currently in creation: Is there an unresolvable circular reference?



 有人可以告诉我原因吗?

2 个答案:

答案 0 :(得分:0)

请通过展开Initializer来创建AbstractSecurityWebApplicationInitializer课程。

请在这里参考我的答案。

No bean named 'springSecurityFilterChain' available

答案 1 :(得分:0)

我通过将我的spring安全依赖项更新到pom.xml中的最新版

来解决了这个问题

我从

更改了版本

<springsecurity.version>4.0.4.RELEASE</springsecurity.version>

<springsecurity.version>4.2.3.RELEASE</springsecurity.version>