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

spring boot+freemarker+spring security標籤權限判斷java

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

一、引入依賴spring

<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>

  

二、依賴引入後到spring-security-taglibs包中META-INF下security.tld複製出來,放到/resources/下,最後建一個目錄tags,以下:apache

 

三、建一個配置類:ClassPathTldsLoader.javaapi

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();
	    }

  

參考:jsp

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();
	    }
	
	
}

  

五、在freemarker頁面頂部引入標籤ide

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

  

使用標籤post

<@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>
相關文章
相關標籤/搜索