基于Spring Boot保护Web应用程序

2020-03-06 12:03:04于丽

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

XML

Gradle用户可以在build.gradle 文件中添加以下依赖项。

compile("org.springframework.boot:spring-boot-starter-security")

现在,创建一个Web安全配置文件,该文件用于保护应用程序以使用基本身份验证访问HTTP端点。

package com.yiibai.websecuritydemo;

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

@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 {
   auth
     .inMemoryAuthentication()
     .withUser("user").password("password").roles("USER");
  }
}

Java

现在,在src/main/resources 目录下创建一个login.html 文件,以允许用户通过登录屏幕访问HTTP端点。

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

HTML

最后,更新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">您好,[[${#httpServletRequest.remoteUser}]]!</h1>
   <form th:action = "@{/logout}" method = "post">
     <input type = "submit" value = "注销"/>
   </form>
  </body>

</html>