Spring Security从零开始学习SpringBoot

SpringBoot 2.x - SpringSecurity(

2018-06-26  本文已影响113人  BzCoder

Spring中使用的主要有两个安全框架——Shiro与SpringSecurity,本次学习的是SpringSecurity。
首先还是查看官方文档来学习。我们使用的WEB模版是Thymeleaf。

两个概念:

1.引入Maven

由于我们本次采用的是Thymeleaf+SpringSecurity。所以我们需要引入thymeleaf-extras-springsecurity,相关使用方法可以查看Github

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

2.配置类

本次采用是在内存中记录用户,大多数要点已经写在注释中,但是有一点值得注意的是,从Spring Security 5.0开始必须要设置加密方式,SpringSecurity提供了以下加密方式。当然最重要的一点,在配置类中不要忘记添加@EnableWebSecurity来开启Security功能。

Security提供的加密方式
/**
 * @author BaoZhou
 * @date 2018/6/21
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /*匹配所有路径的*/
        http.authorizeRequests().antMatchers("/").permitAll()
                /*level1路径下需要VIP1身份才能访问*/
                .antMatchers("/level1/**").hasRole("VIP1")
                /*level1路径下需要VIP2身份才能访问*/
                .antMatchers("/level2/**").hasRole("VIP2")
                /*level1路径下需要VIP3身份才能访问*/
                .antMatchers("/level3/**").hasRole("VIP3")
                .and()
                /*
                1.formLogin系统会自动配置/login页面用于登录
                2.假如登录失败会重定向到login/error/
                 */
                .formLogin()
                /*
                定制自己的登录界面
                默认username字段提交用户名,可以通过usernameParameter自定义
                默认password字段提交密码,可以用过passwordParameter自定义
                定制了登录页面后
                登录页面地址的POST请求就是登录请求,可以用过loginProcessingUrl自定义
                */
                .loginPage("/userlogin")
                .and()
                /*开启注销功能,访问/logout并清空session*/
                .logout()
                /*注销成功去首页*/
                .logoutSuccessUrl("/")
                .and()
                .exceptionHandling()
                /*设置403错误跳转页面*/
                .accessDeniedHandler(new CustomAccessDeniedHandler())
                .and()
                /*开启记住我功能,登录会添加Cookie,点击注销会删除Cookie*/
                .rememberMe()
                /*设置记住我参数*/
                .rememberMeParameter("remember");
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth
                /*从内存中读取认证*/
                .inMemoryAuthentication()
                /*Spring Security 5.0开始必须要设置加密方式*/
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user1").password(new BCryptPasswordEncoder().encode("123")).roles("VIP1")
                .and()
                .withUser("user2").password(new BCryptPasswordEncoder().encode("123")).roles("VIP2")
                .and()
                .withUser("user3").password(new BCryptPasswordEncoder().encode("123")).roles("VIP3");
    }
}

3.Web页

主要就是利用sec提供的方法。

数据页面

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

<head>
    <meta charset="UTF-8">
    <title>登录界面</title>
</head>
<body>
<div sec:authorize="isAuthenticated()">
    <h2 align="center"><span sec:authentication="name"></span>,你好,你是
        <span sec:authentication="principal.authorities"></span></h2>
</div>
<div sec:authorize="!isAuthenticated()">
    <h2 align="center">游客你好<a th:href="@{/userlogin}">请登录</a></h2>
</div>

<div sec:authorize="isAuthenticated()">
    <form th:action="@{/logout}" method="post">
        <input type="submit" value="注销"></form>
</div>


<h3 sec:authorize="isAuthenticated()">VIP专区</h3>
<ul>
    <li sec:authorize="hasRole('VIP1')"><a th:href="@{/level1/1}">VIP1专区</a></li>
    <li sec:authorize="hasRole('VIP2')"><a th:href="@{/level2/2}">VIP2专区</a></li>
    <li sec:authorize="hasRole('VIP3')"><a th:href="@{/level3/3}">VIP3专区</a></li>
</ul>
</body>
</html>

自定义登录界面UserLogin

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
<h1 align="center">用户安全登录系统</h1>

<hr>
<div align="center">
    <form th:action="@{/userlogin}" method="post">
        用户名:<input name="username"/><br>
        密码:<input name="password"/><br>
        <input type="checkbox" name="remember">记住我<br/>
        <input type="submit" value="登录">
    </form>
</div>
</body>
</html>

4.Demo GitHub地址

https://github.com/BzCoder/security

上一篇 下一篇

猜你喜欢

热点阅读