spring boot+freemarker+spring security標簽權限判斷


spring boot+freemarker+spring security標簽權限判斷

SpringBoot+SpringSecurity+Freemarker項目中在頁面上使用security標簽控制按鈕顯示隱藏達到對按鈕級權限控制還是比較方便的,如下配置即可。

1、引入依賴

<dependency>			
<groupId>org.springframework.security</groupId>			
<artifactId>spring-security-taglibs</artifactId>		
</dependency> 		

<dependency>			
<groupId>javax.servlet.jsp</groupId>			
<artifactId>jsp-api</artifactId>			
<version>2.2.1-b03</version>		
</dependency>

  

2、依賴引入后到spring-security-taglibs包中META-INF下security.tld復制出來,放到/resources/下,最后建一個目錄tags,如下:

 

3、建一個配置類:ClassPathTldsLoader.java

import java.util.Arrays;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

public class ClassPathTldsLoader {

	  /**
     * 指定路徑
     */
    private static final String SECURITY_TLD = "/security.tld";

    final private List<String> classPathTlds;

    public ClassPathTldsLoader(String... classPathTlds) {
        super();
        if(ArrayUtils.isEmpty(classPathTlds)){
            this.classPathTlds = Arrays.asList(SECURITY_TLD);
        }else{
            this.classPathTlds = Arrays.asList(classPathTlds);
        }
    }
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @PostConstruct
    public void loadClassPathTlds() {
        freeMarkerConfigurer.getTaglibFactory().setClasspathTlds(classPathTlds);
    }
}

  

4.然后在網站配置文件SecurityConfig.java中加入bean

/**
	 * 自動加載security-taglibs
	 * @return
	 */
	    @Bean
	    @ConditionalOnMissingBean(ClassPathTldsLoader.class)
	    public ClassPathTldsLoader classPathTldsLoader(){
	        return new ClassPathTldsLoader();
	    }

  

參考:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
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.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;

@EnableWebSecurity
//啟用全局post安全方法設置
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	private static final String key = "muyang.my";
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	
	@Bean
	public PasswordEncoder passwordEncoder()
	{
		return new BCryptPasswordEncoder();
		
	}
	
	@Bean
	public AuthenticationProvider authenticationProvider() {
		DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
		authenticationProvider.setUserDetailsService(userDetailsService);
		//密碼加密方式
		authenticationProvider.setPasswordEncoder(passwordEncoder());
		return authenticationProvider;
		
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// TODO Auto-generated method stub
		//super.configure(http);
		//關閉csrf驗證:跨站攻擊
		//http.csrf().disable();
		//權限設置
		http.authorizeRequests()     //定義那些url需要保護,哪些不需要保護
		.antMatchers("/static/**").permitAll()  //都可以訪問
		.antMatchers("/user/**").hasRole("ADMIN") //需要登陸才能訪問
		.and()		
		.headers().frameOptions().disable() //解決js跨站把x-frame-options disable即可
		.and()
		.formLogin() //基於FORM表單登陸驗證
		.loginPage("/login").failureUrl("/login-error") //自定義登陸界面//自定義登陸錯誤頁面
		.and().rememberMe().key(key) //記住我
		.and().exceptionHandling().accessDeniedPage("/403");  // 處理異常,拒絕訪問就重定向到 403 頁面
	}

	
	
	/**
	 * 認證信息管理
	 * @param auth
	 * @throws Exception
	 */
	@Autowired
	public  void configureGlobal(AuthenticationManagerBuilder  auth) throws Exception {
		// TODO Auto-generated method stub
		//super.configure(auth);
		//auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
		auth.userDetailsService(userDetailsService);
		auth.authenticationProvider(authenticationProvider());
	}

	
	/**
	 * 自動加載security-taglibs
	 * @return
	 */
	    @Bean
	    @ConditionalOnMissingBean(ClassPathTldsLoader.class)
	    public ClassPathTldsLoader classPathTldsLoader(){
	        return new ClassPathTldsLoader();
	    }
	
	
}

  

5、在freemarker頁面頂部引入標簽

<#assign security=JspTaglibs["http://www.springframework.org/security/tags"] />

  

使用標簽

<@security.authorize access="hasRole('ADMIN')">
222
</@security.authorize>

  

6.或者

 

<%@taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>
<sec:authorize access="isAuthenticated()">
    <% response.sendRedirect("main"); %>
</sec:authorize>

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM