1. 程式人生 > >Spring Boot中使用Spring Security進行安全控制

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

一 點睛

我們在編寫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

<!--
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 啟動應用程式

3 點選頁面中的“這裡”連結,彈出下面頁面

5 輸入一個錯誤的認證資訊,然後點選登入,彈出如下頁面

6 輸入正確的認證資訊,彈出如下頁面

8 點選登出,彈出頁面如下