3.SpringBoot + Security 整合官方示例

本文中使用SpringBoot 2.0.4 + Security5.0.7
SpringSecurity是一个功能强大且高度定制的身份验证和访问控制框架。
Security官方示例下载
Security官方API
源码下载



1、老规矩学习第一步实现helloworld示例。
下载官方示例,解压后 samples >> boot >> helloworld
官方示例不是Maven项目,下面是目录结构:
项目结构

从示例中可以看出主要包含SecurityConfig.javaMainController.java
2、创建SpringBoot的Maven项目,在pom文件中添加Security依赖。

        <!-- thymeleaf  依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <version>3.0.2.RELEASE</version><!--$NO-MVN-MAN-VER$-->
        </dependency>
        <!-- security  依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

3、创建SecurityConfig.java,继承WebSecurityConfigurerAdapter。
官方示例中未连接数据库,而是将用户存储到内存中,在添加下面代码时,可以看出withDefaultPasswordEncoder()方法是过时的,但不影响程序。

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置拦截器保护请求
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/css/**", "/index").permitAll()     /*与之匹配的请求/CSS/*和/索引完全无障碍*/
                .antMatchers("/user/**").hasRole("USER")          /*与之匹配的请求/用户/*要求对用户进行身份验证,并且必须与用户角色*/
                .and().formLogin()
                .loginPage("/login").failureUrl("/login-error");                /*基于表单的身份验证是通过自定义登录页和故障url启用的。*/
    }

    /**
     * 配置user-detail服务
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER"));
    }
}

4、创建LoginController.java,就是我们一般用到的Controller,看代码。

@Controller
public class LoginController {

    @RequestMapping("/")
    public String root() {
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/user/index")
    public String userIndex() {
        return "user/index";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/login-error")
    public String loginError(Model model) {
        model.addAttribute("loginError", true);
        return "login";
    }
}

5、创建index.htmllogin.htmluser/index.html,想偷懒可以从示例中将html拷贝过来,结构不变。

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <title>Hello Spring Security</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
</head>
<body>
<div th:fragment="logout" class="logout" sec:authorize="isAuthenticated()">
    用户名: <span sec:authentication="name"></span> |
    角色: <span sec:authentication="principal.authorities"></span>
    <div>
        <form action="#" th:action="@{/logout}" method="post">
            <input type="submit" value="退出" />
        </form>
    </div>
</div>
<h1>Hello Spring Security</h1>
<p>This is an unsecured page, but you can access the secured pages after authenticating.</p>
<ul>
    <li>Go to the <a href="/user/index" th:href="@{/user/index}">secured pages</a></li>
</ul>
</body>
</html>

login.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login page</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
</head>
<body>
<h1>Login page</h1>
<p>Example user: user / password</p>
<p th:if="${loginError}" class="error">Wrong user or password</p>
<form th:action="@{/login}" method="post">
    <label for="username">Username</label>:
    <input type="text" id="username" name="username" autofocus="autofocus" /> <br />
    <label for="password">Password</label>:
    <input type="password" id="password" name="password" /> <br />
    <input type="submit" value="Log in" />
</form>
<p><a href="/index" th:href="@{/index}">Back to home page</a></p>
</body>
</html>

user/index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello Spring Security</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
</head>
<body>
<div th:substituteby="index::logout"></div>
<h1>This is a secured page!</h1>
<p><a href="/index" th:href="@{/index}">Back to home page</a></p>
</body>
</html>

6、测试项目,运行后访问localhost:8080,页面会跳转到index.html

首页

点击 secured pages 跳转到登陆页,输入错误用户密码登陆。
用户密码错误提示

输入正确用户密码,登陆后页面跳转到user/index.html,并显示用户名和用户角色。
登陆后

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。