thymeleaf+springsecurity使用

在项目上使用springsecurity进行用户权限分配后使用springsecurity标签进行用户在线信息的获取和按钮权限。

 首先是增加依赖。这里有一个重点就是:thymeleaf依赖和thymeleaf-springsecurity的依赖版本要一致,不然会出现security标签无效的情况。

不清楚自己的thymeleaf依赖版本的可以直径Ctrl+点击thymeleaf的artifactId就可以知道对应的版本号了。可以直接使用这个去确定你的springsecurity的版本。

如:我的springsecurity是security4,但是我之前一直认为是我security5。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.1.RELEASE</version>
        </dependency>

增加依赖后实现一个springsecurity的config配置。

package com.shengxi.rs.common.config;

import com.shengxi.rs.common.filter.TokenFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;


/**
 * @author: Matthew
 * @Date: 2019/4/26 15:08
 * @Description: 权限配置
 * 继承 WebSecurityConfigurerAdapter 实现权限的配置初始化
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;


    @Autowired
    private TokenFilter tokenFilter;

    @Autowired
    private LogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    /***
     * 数据加密
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置策略
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        /**
         * 基于token, 关闭session
         */
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and();
        /**
         * 开放资源
         */
        http.authorizeRequests().antMatchers(
                "/webjar/**", "/", "/**", "/*.html", "/favicon.ico", "/css/**", "/js/**", "/fonts/**", "/layui/**", "/img/**",
                "/v2/api-docs/**", "/swagger-resources/**", "/webjars/**", "/pages/**", "/druid/**",
                "/statics/**").permitAll().anyRequest().authenticated();
        /**
         * 权限配置
         */
        http.formLogin().usernameParameter("userNo");
        http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
        /*登录页面和登录提交路径*/
        http.formLogin().usernameParameter("userNo").loginProcessingUrl("/login").successHandler(authenticationSuccessHandler).
                failureHandler(authenticationFailureHandler).and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and().rememberMe();
        http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler).and().rememberMe();
        http.headers().frameOptions().disable();
        http.headers().cacheControl();
        http.addFilterBefore(tokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.rememberMe();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }
}

然后在html上增加依赖,注意 :这里的springsecurity4或者5的版本一定要和pom.xml中的thymeleaf-springsecurity依赖一致。

<html lang="zh" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

只要你的依赖是thymeleaf-springsecurity是3.0以上就可以使用springsecurity标签直接进行用户信息获取和权限限定了。

<a href="javascript:;">
  <img th:src="@{/images/face.jpeg}" class="layui-nav-img userAvatar" width="35" height="35">
<!--sec:authentication获取对应的登录信息,获取的使用你登录以后的user信息,是实现了UserDetails的类的实例-->
  <cite class="adminName"  sec:authentication="principal.userName"></cite>
</a>

 

有时候视图上的一部分内容需要根据用户被授予了什么权限来确定是否渲染。Spring Security的标签能够根据用户被授予的权限有条件地渲染页面的部分内容。下面是一个简单的示例:

	<body sec:authorize="hasAnyAuthority('DSC_ADMIN')">
		首页
	</body>

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

matthew_leung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值