SpringBoot整合Security+Thymeleaf案例

一、引入相关jar

1)、修改Thymeleaf版本改为3,Layout版本改为2,以及修改Security+Thymeleaf的整合版本

<properties>
    <java.version>1.8</java.version>
    <!--thymeleaf切换成3版本,layout切换成2-->
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
    <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
</properties>

2)、引入Security+Thymeleaf的的整合包

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

二、自定义Security配置

/**SpringBoot整合Security自定义配置
 * @author hq.zheng
 * @create 2019-03-23-下午 11:12
 */
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       // super.configure(http);
        //定制请求的授权规则
        http.authorizeRequests().antMatchers("/").permitAll()//所有人都可以访问根目录
                .antMatchers("/level1/**").hasRole("VIP1")//访问“/level1”下的请求需要“VIP1”权限
                .antMatchers("/level2/**").hasRole("VIP2")//访问“/level2”下的请求需要“VIP2”权限
                .antMatchers("/level3/**").hasRole("VIP3");//访问“/level3”下的请求需要“VIP3”权限
        //开启自动配置的登入功能,如果没有权限就会来到登入页面
        http.formLogin().loginPage("/userlogin").loginProcessingUrl("/login").usernameParameter("user").passwordParameter("pwd");

        //开启自动配置的注销功能,访问/logout表示用户注销,清空session,注销以后默认又返回登入页
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");



    }

    /**
     * 定义认证规则
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("VIP1","VIP2","VIP3")
        .and().withUser("lisi").password("123456").roles("VIP1");
    }
}

三、自定义Thymeleaf页面

1)、引入安全标签提示

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

2)、判断是否已经认证

<!--如果没认证-->
<div sec:authorize="!isAuthenticated()">显示没认证的内容</div>
<!--如果认证了-->
<div sec:authorize="isAuthenticated()">显示认证的内容</div>

3)、获取用户名和角色

<!--获取用户名-->
<span sec:authentication="name"></span>
<!--获取角色-->
<span sec:authentication="principal.authorities"></span>

 4)、判断是否拥有某个角色

<div sec:authorize="hasRole('VIP1')"></div>

猜你喜欢

转载自blog.csdn.net/xm393392625/article/details/88775893