Spring Boot官方提供了一个登陆认证的清晰易懂的 例子

我们在次以此例展开演示Spring Boot是如何实现登陆认证的。

首先我们去 https://start.spring.io/ 下载一个样例工程 spring-test。

我们这个例子中包含三个页面,放在src/main/resources/templates/目录下:

  • 登陆页面:login.html
  • 主页:home.html
  • 欢迎页面:hello.html

包含三个类:

  • 主类:SpringTestApplication.java
  • MVC映射关系类:MvcConfig.java
  • 安全控制类:WebSecurityConfig.java

相关的maven依赖:

pom.xml

    <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- tag::security[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- end::security[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

MvcConfig.java

package com.zifeiy.springtest.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration
public class MvcConfig implements WebMvcConfigurer { public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
} }

这个类主要用于配置url和view的对应关系。

WebSecurityConfig.java

package com.zifeiy.springtest.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager; @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();
} @Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build(); return new InMemoryUserDetailsManager(user);
}
}

其中:

        http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();

表示的意思是:

允许所有用户可以访问"/"和"/home";

通过form上传表单的形式登陆,form对应的url为"/login";

允许所有用户登出(logout)。

但是除此之外的所有的url都不能直接访问,除非登陆了,比如这里的"/hello"链接,就不能直接登陆。

这里的 UserDetails 用于设置登陆的用户名为user,密码为password的时候才能正确登陆。

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}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>

home.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>
<h1>Welcome!</h1> <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</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">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>

Spring Boot确保Web应用安全(登陆认证)的更多相关文章

  1. 使用Spring Boot开发Web项目(二)之添加HTTPS支持

    上篇博客使用Spring Boot开发Web项目我们简单介绍了使用如何使用Spring Boot创建一个使用了Thymeleaf模板引擎的Web项目,当然这还远远不够.今天我们再来看看如何给我们的We ...

  2. 【spring boot】5.spring boot 创建web项目并使用jsp作前台页面

    贼烦的是,使用spring boot 创建web项目,然后我再idea下创建的,but 仅仅启动spring boot的启动类,就算整个项目都是好着的,就算是能够进入controller中,也不能成功 ...

  3. 通过docker-composer启动容器nginx,并完成spring.boot的web站点端口转发

    前面已经讲过2篇基于docker的mysql.redis容器编排并启动.这次将练习下nginx的docker方式的部署,以及通过nginx去代理宿主主机上的Web服务应该怎么配 PS:(这里由于ngi ...

  4. Spring Boot 2.X(四):Spring Boot 自定义 Web MVC 配置

    0.准备 Spring Boot 不仅提供了相当简单使用的自动配置功能,而且开放了非常自由灵活的配置类.Spring MVC 为我们提供了 WebMvcConfigurationSupport 类和一 ...

  5. Spring Boot开发Web应用之Thymeleaf篇

    前言 Web开发是我们平时开发中至关重要的,这里就来介绍一下Spring Boot对Web开发的支持. 正文 Spring Boot提供了spring-boot-starter-web为Web开发予以 ...

  6. Spring Boot 嵌入式Web容器

    目录 前言 1.起源 2.容器启动流程解析 2.1.获取应用类型 2.2.容器启动流程 3.加载 Web 容器工厂 4.总结 前言         最近在学习Spring Boot相关的课程,过程中以 ...

  7. 使用Spring Boot开发Web项目

    前面两篇博客中我们简单介绍了Spring Boot项目的创建.并且也带小伙伴们来DIY了一个Spring Boot自动配置功能,那么这些东西说到底最终还是要回归到Web上才能体现出它的更大的价值,so ...

  8. spring boot 搭建web项目常见五种返回形式

    在web项目中一般常见的五种返回形式: 返回页面,使用模板引擎,spring boot推荐使用thymeleaf,类似的还有freemarker等. 返回字符串(json),一般用于完全的前后端分离开 ...

  9. Spring Boot的web开发

    web开发的自动配置类:org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration 自动配置的ViewResolver 视图的 ...

随机推荐

  1. c/c++编译器配置(交叉编译重要参数)、交叉编译动态库与as配置、mk初步

    gcc/g++/clang,相当于javac: 了解c/c++编译器的基本使用,能够在后续移植第三方框架进行交叉编译时,清楚的了解应该传递什么参数. clang: clang 是一个C.C++.Obj ...

  2. nuxt入门

    之前一直都是做vue-spa单页面,不利于SEO.而便于SEO的SSR(服务器端渲染)多页应用,可以使用nuxt.js这个框架来实现 (0)nuxt安装 npx create-nuxt-app < ...

  3. bcb ole拖拽功能的实现

    最近项目中用到了OLE 拖拽功能 和BCB 一个Form的Drag 不同的是,只有实现了OLE 拖拽才能,从其他程序拖拽数据到Form 下面的代码实现了,同HTML网页拖拽到Form时,Form获得H ...

  4. python中常用的九种预处理方法

    本文总结的是我们大家在python中常见的数据预处理方法,以下通过sklearn的preprocessing模块来介绍; 1. 标准化(Standardization or Mean Removal ...

  5. 通过Java调用Python脚本

    在进行开发的过程中,偶尔会遇到需要使用Java调用Python脚本的时候,毕竟Python在诸如爬虫,以及科学计算等方面具有天然的优势.最近在工作中遇到需要在Java程序中调用已经写好的Python程 ...

  6. The "web.xml" is called web application deployment descriptor

    3.3  Configure the Application Deployment Descriptor - "web.xml" A web user invokes a serv ...

  7. 使用python批量造测试数据

    # -*- coding:utf-8 -*- import json import os import time class Virtual_Data: def __init__(self): sel ...

  8. webdriver对各种浏览器的支持

    1.Firefox WebDriver实现了FireFoxDriver,无需用户下载FireFoxDriver. 优点:FireFoxDriver对页面的自动化测试支持得比较好,很直观地模拟页面的操作 ...

  9. HDU 6154 - CaoHaha's staff | 2017 中国大学生程序设计竞赛 - 网络选拔赛

    /* HDU 6154 - CaoHaha's staff [ 构造,贪心 ] | 2017 中国大学生程序设计竞赛 - 网络选拔赛 题意: 整点图,每条线只能连每个方格的边或者对角线 问面积大于n的 ...

  10. *51nod 1409

    https://blog.csdn.net/stay_accept/article/details/81476358 不懂啊 #include <map> #include <que ...