Springboot 1.5.1整合Spring security 4.2.1

来源:互联网 发布:mp3伴奏提取软件 编辑:程序博客网 时间:2024/05/07 03:29

由于Spring security具有非常多的高级强大功能,也是Springboot官方推荐的安全框架,因此这一篇文章我们将在上一篇《构建Springboot 1.5.1 Maven工程》的基础上整合spring security.

1) 首先写一个简单的html登录界面login.html:代码如下

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head>    <meta content="text/html;charset=UTF-8"/>    <title>Springboot login</title></head><body>    <p th:if="${param.logout}" class="error-code">已成功注销</p>    <p th:if="${param.error}" class="error-code">有错误,请重试</p>    <form class="form-signin" th:action="@{/login}" action="/login" method="POST">        <h2 class="form-signin-heading">Welcome to Springboot</h2>        <input type="text" class="form-control" name="username" value="" placeholder="账号" />        <input type="password" class="form-control" name="password" placeholder="密码" />        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>    </form></body></html>

再写一个简单的带有登出的主页index.html,代码如下:

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"><head>    <title>Hello World!</title></head><body>    <h1 th:inline="text">Hello World</h1>    <form th:action="@{/logout}" action="./logout" method="post">        <input type="submit" value="Sign Out"/>    </form></body></html>

2) pom.xml引入spring-boot-starter-security依赖

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

2) 配置spring security 的相关配置
我们写个类WebMvcConfig 来继承WebMvcConfigurerAdapter

package com.liting.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter{    @Override    public void addViewControllers(ViewControllerRegistry registry) {        registry.addViewController("/login").setViewName("login");    }}

配置WebSecurityConfig

package com.liting.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;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.WebSecurityConfigurerAdapter;@Configurationpublic class WebSecurityConfig extends WebSecurityConfigurerAdapter{    @Autowired    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {        auth.inMemoryAuthentication()            .withUser("admin").password("123456").roles("USER");    }    @Override    protected void configure(HttpSecurity http) throws Exception {        //http.csrf().disable();        http.authorizeRequests()                        .antMatchers("/", "/springbootbase").permitAll()                        .anyRequest().authenticated()                        .and()                    .formLogin()                        .loginPage("/login")                        .failureUrl("/login?error")                        .permitAll() //5                        .and()                    .logout().permitAll();    }}

现在整个代码的目录结构如下:
这里写图片描述
3) 到此,我们已经配置完成,下面我们来运行一下我们的web,
启动tomcat service, springboot 正常启动。
在浏览器输入http://localhost:8080/springbootbase/
这里写图片描述
并没得到我们预期的结果,仔细查看地址栏,我们输入的url确实被拦截并转到login 界面,只是这个登录界面没有找到而已。再看页面错误提示信息,是login.html页面没找到,可以我们明明它明明在webapp目录下,为什么会找不到呢?原因是spring security 默认的查找路径是在\src\main\resources\templates\目录下,那我们直接将login.html 移到templates的目录下,再试一下,得到如下结果:
这里写图片描述
输入账号admin, 密码123456,(这里为了方便演示,我们直接在代码中写死了,)点击sign in 按钮,成功登录
这里写图片描述
接下来,如果我们按sign out 按钮,理论上应该回到重新登录界面,但是得到的结果却是403错误
这里写图片描述
Could not verify the provided CSRF token because your session was not found. 这又是怎么回事?这是因为我们成功登录后,spring security为了防止CSRF攻击,需要在每个页面中验证成功登录后创建的csrf token值,而我们在静态页面中又无法传递这个token, 因此我们暂时先将其disable。至于有没有必要及如何传递这个csrf token,将在今后的文章介绍。

@Override    protected void configure(HttpSecurity http) throws Exception {        http.csrf().disable();        http.authorizeRequests()                        .antMatchers("/", "/springbootbase").permitAll()                        .anyRequest().authenticated()                        .and()                    .formLogin()                        .loginPage("/login")                        .failureUrl("/login?error")                        .permitAll() //5                        .and()                    .logout().permitAll();    }

查看结果:
这里写图片描述
已成功注销。
至此,基于Springboot配置Spring security 4 已整合完成。

0 0
原创粉丝点击