springboot整合springsecurity

导入maven依赖包


    org.springframework.boot
    spring-boot-starter-security

官方文档的内容
springboot整合springsecurity_第1张图片

springboot整合springsecurity_第2张图片
重写源码的方法
springboot整合springsecurity_第3张图片
springboot整合springsecurity_第4张图片

package com.xionger.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 链式编程
    // 授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 首页所有人可以访问,对应的功能也对应权限的人才能访问
        // 请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        // 没有权限默认会跳转登录页面,需要开启登录的页面
        http.formLogin();

        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");

    }

    // 认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                // 这些数据正常来说应该从数据库中读
                .withUser("xionger").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and()
                .withUser("vv1").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1").and()
                .withUser("vv2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2").and()
                .withUser("vv3").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
    }
}

thymeleaf 与 springsecurity 整合

导入包

<dependency>
     <groupId>org.thymeleaf.extras</groupId>
     <artifactId>thymeleaf-extras-springsecurity4</artifactId>
     <version>3.0.4.RELEASE</version>
 </dependency>

命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

使用

<!--登录注销-->
<div class="right menu">
   <!--如果未登录-->
   <div sec:authorize="!isAuthenticated()">
       <a class="item" th:href="@{/toLogin}">
           <i class="address card icon"></i> 登录
       </a>
   </div>

   <!--如果已登录,用户名和注销按钮-->
   <div sec:authorize="!isAuthenticated()">
       <a class="item">
           用户名:   <span sec:authentication="name"></span>
           角色: <span sec:authentication="principal.getAuthorities()"></span>
       </a>
   </div>
   <div sec:authorize="isAuthenticated()">
       <a class="item" th:href="@{/logout}">
           <i class="sign-out icon"></i> 注销
       </a>
   </div>

你可能感兴趣的:(spring)