SpringSecurity身份驗證基礎入門

對於沒有訪問權限的用戶須要轉到登陸表單頁面。要實現訪問控制的方法多種多樣,能夠經過Aop、攔截器實現,也能夠經過框架實現(如:Apache Shiro、Spring Security)。

pom.xml添加依賴html

<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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

建立SpringSecurity配置類java

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
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //inMemoryAuthentication 從內存中獲取
        auth
                .inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("admin")
                .password(new BCryptPasswordEncoder()
                        .encode("123456")).roles("USER");
    }
}

經過@EnableWebSecurity註解開啓Spring Security的功能
繼承WebSecurityConfigurerAdapter,並重寫它的方法來設置一些web安全的細節
configure(HttpSecurity http)方法,經過authorizeRequests()定義哪些URL須要被保護、哪些不須要被保護。例如以上代碼指定了/和/home不須要任何認證就能夠訪問,其餘的路徑都必須經過身份驗證。
經過formLogin()定義當須要用戶登陸時候,轉到的登陸頁面。
configureGlobal(AuthenticationManagerBuilder auth)方法,在內存中建立了一個用戶,該用戶的名稱爲admin,密碼爲123456,用戶角色爲USER。web

控制器:spring

@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";
    }

}

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>

hello.htmlapp

<!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>

login.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 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>

運行:ide

打開index.html,點擊這裏,若是沒有登陸進入登陸頁,已登陸跳轉到hello.htmlspring-boot

轉載於:這篇文章web安全