Spring Boot中使用Spring Security进行安全控制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/83713314

一 点睛

我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面。要实现访问控制的方法多种多样,可以通过Aop、拦截器实现,也可以通过框架实现(如:Apache Shiro、Spring Security)。

本篇将具体介绍在Spring Boot中如何使用Spring Security进行安全控制。

二 实战

1 引入相关依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!--引入security-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</dependencies>

2 新建控制器

package com.didispace.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
public class HelloController {

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

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

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

}

3 安全配置

package com.didispace;

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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
//通过@EnableWebSecurity注解开启Spring Security的功能
@EnableWebSecurity
//必须继承WebSecurityConfigurerAdapter
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    //重写该方法来设置一些web安全的细节
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()    //通过authorizeRequests()定义哪些URL需要被保护、哪些不需要被保护。
                .antMatchers("/", "/home").permitAll()  //  /和/home不需要任何认证就可以访问。
                .anyRequest().authenticated()  //其他的路径都必须通过身份验证
                .and()
            .formLogin()   //当需要用户登录时候
                .loginPage("/login")   //转到的登录页面
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()   //在内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER。
                .withUser("user").password("password").roles("USER");
    }

}

4 启动类

package com.didispace;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}

5 hello.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-springsecurity3">
<head>
    <title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="注销"/>
</form>
</body>
</html>

6 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-springsecurity3">
<head>
    <title>Spring Security入门</title>
</head>
<body>
<h1>欢迎使用Spring Security!</h1>

<p>点击 <a th:href="@{/hello}">这里</a> 打个招呼吧</p>
</body>
</html>

7 login.html

扫描二维码关注公众号,回复: 3935608 查看本文章
<!--
Spring Security提供了一个过滤器来拦截请求并验证用户身份。
如果用户身份认证失败,页面就重定向到/login?error,并且页面中会展现相应的错误信息。
若用户想要注销登录,可以通过访问/login?logout请求,在完成注销之后,页面展现相应的成功消息。
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
    用户名或密码错
</div>
<div th:if="${param.logout}">
    您已注销成功
</div>
<form th:action="@{/login}" method="post">
    <div><label> 用户名 : <input type="text" name="username"/> </label></div>
    <div><label> 密 码 : <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="登录"/></div>
</form>
</body>
</html>

三 测试

1 启动应用程序

2 浏览器输入:http://localhost:8080/

3 点击页面中的“这里”链接,弹出下面页面

4 浏览器输入:http://localhost:8080/hello,弹出如下页面

5 输入一个错误的认证信息,然后点击登录,弹出如下页面

6 输入正确的认证信息,弹出如下页面

7 重开页面,浏览器输入http://localhost:8080/hello,弹出如下页面

8 点击注销,弹出页面如下

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/83713314