1 Star 0 Fork 165

ElonChung / Java-Review

forked from flatfish / Java-Review 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
SpringBoot中集成SpringSecurity.md 14.19 KB
一键复制 编辑 原始数据 按行查看 历史
icanci 提交于 2020-09-07 22:43 . :fire:更新文件名

SpringBoot 中集成 Spring Security

认证与授权

具体内容查看上一级 SpringBoot 中集成 Shiro.md

Spring Security

是Spring官方 提供的认证与授权框架.

也是SpringBoot底层安全模块默认的技术选型,他可以实现强大的Web安全机制,仅仅需要 spring-boot-starter-security 模块进行少量配置,就可以完成强大的授权功能

记住几个类:

  • WebSecurityConfigurationAdapter:自定义Security策略
  • AuthenticationMangerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

Spring Security 的两个主要目标是“忍真”和“授权” (访问控制)

建立项目

pom.xml 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

编写配置类 SecurityConfig

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
}

完整基于内存的配置

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 授权
     *
     * @param http
     * @throws Exception
     */
    @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();
    }

    /**
     * 认证
     *
     * @param auth
     * @throws Exception
     *
     * PasswordEncoder:需要对密码编码
     * 在Spring Security 5.0 + 新增了很多的加密方式
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 这些数据应该从数据库中拿到
        auth.inMemoryAuthentication()
            .passwordEncoder(new BCryptPasswordEncoder())
            .withUser("icanci").password(new BCryptPasswordEncoder().encode("icanci")).roles("vip1")
            .and()
            .withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1", "vip2", "vip3")
            .and()
            .withUser("ic").password(new BCryptPasswordEncoder().encode("ic")).roles("vip2", "vip3");
    }
}

使用数据库

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    /**
     * 授权
     *
     * @param http
     * @throws Exception
     */
    @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();
    }

    /**
     * 认证
     *
     * @param auth
     * @throws Exception
     *
     * PasswordEncoder:需要对密码编码
     * 在Spring Security 5.0 + 新增了很多的加密方式
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 这些数据应该从数据库中拿到
        auth.jdbcAuthentication()
            .dataSource(dataSource)
            .withDefaultSchema()
            .withUser(users.username("user").password("password")).roles("USER")
            .withUser(users.username("user").password("password")).roles("USER");
    }
}

如果需要控制界面访问,需再添加 依赖

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

案例代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.w3.org/thymeleaf-extras-springsecurity4">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <title>首页</title>
        <!--semantic-ui-->
        <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
        <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
    </head>
    <body>

        <!--主容器-->
        <div class="ui container">

            <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
                <div class="ui secondary menu">
                    <a class="item"  th:href="@{/index}">首页</a>

                    <!--登录注销-->
                    <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>
                            </a>
                        </div>
                        <div sec:authorize="isAuthenticated()">
                            <a class="item" th:href="@{/logout}">
                                <i class="address card icon"></i> 注销
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="ui segment" style="text-align: center">
                <h3>Spring Security Study by 秦疆</h3>
            </div>

            <div>
                <br>
                <div class="ui three column stackable grid">
                    <div class="column"  sec:authorize="hasRole('vip1')">
                        <div class="ui raised segment">
                            <div class="ui">
                                <div class="content">
                                    <h5 class="content">Level 1</h5>
                                    <hr>
                                    <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                                    <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                                    <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="column"  sec:authorize="hasRole('vip2')">
                        <div class="ui raised segment">
                            <div class="ui">
                                <div class="content">
                                    <h5 class="content">Level 2</h5>
                                    <hr>
                                    <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                                    <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                                    <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="column"  sec:authorize="hasRole('vip3')">
                        <div class="ui raised segment">
                            <div class="ui">
                                <div class="content">
                                    <h5 class="content">Level 3</h5>
                                    <hr>
                                    <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                                    <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                                    <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
        <script th:src="@{/qinjiang/js/semantic.min.js}"></script>
    </body>
</html>
package cn.icanci.security.config;

import org.springframework.beans.factory.annotation.Autowired;
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;

import javax.sql.DataSource;

/**
 * @Author: icanci
 * @ProjectName: security
 * @PackageName: cn.icanci.security.config
 * @Date: Created in 2020/7/11 21:59
 * @ClassAction:
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 授权
     *
     * @param http
     * @throws Exception
     */
    @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().loginPage("/toLogin");
        // 开启注销功能 删除Cookie和Session
        // http.logout().deleteCookies("remove").invalidateHttpSession(true);
        //防止网站攻击
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");

        //记住我功能 Cookie 默认保存 14天
        http.rememberMe().rememberMeParameter("remember");
    }

    /**
     * 认证
     *
     * @param auth
     * @throws Exception
     *
     * PasswordEncoder:需要对密码编码
     * 在Spring Security 5.0 + 新增了很多的加密方式
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 这些数据应该从数据库中拿到
        auth.inMemoryAuthentication()
            .passwordEncoder(new BCryptPasswordEncoder())
            .withUser("icanci").password(new BCryptPasswordEncoder().encode("icanci")).roles("vip1")
            .and()
            .withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1", "vip2", "vip3")
            .and()
            .withUser("ic").password(new BCry`ptPasswordEncoder().encode("ic")).roles("vip2", "vip3");
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <title>登录</title>
        <!--semantic-ui-->
        <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
    </head>
    <body>

        <!--主容器-->
        <div class="ui container">

            <div class="ui segment">

                <div style="text-align: center">
                    <h1 class="header">登录</h1>
                </div>

                <div class="ui placeholder segment">
                    <div class="ui column very relaxed stackable grid">
                        <div class="column">
                            <div class="ui form">
                                <form th:action="@{/toLogin}" method="post">
                                    <div class="field">
                                        <label>Username</label>
                                        <div class="ui left icon input">
                                            <input type="text" placeholder="Username" name="username">
                                            <i class="user icon"></i>
                                        </div>
                                    </div>
                                    <div class="field">
                                        <label>Password</label>
                                        <div class="ui left icon input">
                                            <input type="password" name="password">
                                            <i class="lock icon"></i>
                                        </div>
                                    </div>
                                    <input type="checkbox" name="remember"> 记住我
                                    <input type="submit" class="ui blue submit button"/>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <div style="text-align: center">
                    <div class="ui label">
                        </i>注册
                </div>
                <br><br>
                <small>blog.kuangstudy.com</small>
            </div>
            <div class="ui segment" style="text-align: center">
                <h3>Spring Security Study by 秦疆</h3>
            </div>
        </div>


        </div>

    <script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
    <script th:src="@{/qinjiang/js/semantic.min.js}"></script>

    </body>
</html>
1
https://gitee.com/elonchung/Java-Review.git
git@gitee.com:elonchung/Java-Review.git
elonchung
Java-Review
Java-Review
master

搜索帮助