Spring Boot :Security+thymeleaf

本文介绍如何在SpringBoot项目中集成SpringSecurity实现基础的安全控制。包括配置登录认证、页面授权及错误处理等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、首先是构造Spring Boot 基本的架构,之后需要添加几个其余的文件

请参考 使用STS 构建 Spring Boot 项目

2、所有文件添加完毕之后结构

红色方框内的内容为新增或者有修改。

Spring boot 默认静态文件在src/main/java/static下

前台页面文件默认在 src/main/resources/templates 下

报错默认访问/error,所以需要自己写error.html 

3、静态css文件

main.css

@CHARSET "UTF-8";
body {
    font-family: sans;
    font-size: 1em;
}

p.error {
    font-weight: bold;
    color: red;
}

div.logout {
    float: right;
}


4、前台页面文件

error.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8"/>
    <title>出错了</title>
</head>
<body>
<h1>报错了</h1>
</body>
</html>

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-springsecurity4">
    <head>
        <title>Hello Spring Security</title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
    </head>
    <body>
        <div th:fragment="logout" class="logout" sec:authorize="isAuthenticated()">
            Logged in user: <span sec:authentication="name"></span> |
            Roles: <span sec:authentication="principal.authorities"></span>
            <div>
                <form action="#" th:action="@{/logout}" method="post">
                    <input type="submit" value="Logout" />
                </form>
            </div>
        </div>
        <h1>Hello Spring Security</h1>
        <p>This is an unsecured page, but you can access the secured pages after authenticating.</p>
        <ul>
            <li>Go to the <a href="/user/index" th:href="@{/user/index}">secured pages</a></li>
        </ul>
    </body>
</html>


login.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Login page</title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
	</head>
    <body>
        <h1>Login page</h1>
        <p>Example user: user / password</p>
        <p th:if="${loginError}" class="error">Wrong user or password</p>
        <form th:action="@{/login}" method="post">
            <label for="username">Username</label>:
            <input type="text" id="username" name="username" autofocus="autofocus" /> <br />
            <label for="password">Password</label>:
            <input type="password" id="password" name="password" /> <br />
            <input type="submit" value="Log in" />
        </form>
        <p><a href="/index" th:href="@{/index}">Back to home page</a></p>
    </body>
</html>


user/index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Hello Spring Security</title>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="/css/main.css" th:href="@{/css/main.css}" />
    </head>
    <body>
        <div th:substituteby="index::logout"></div>
        <h1>This is a secured page!</h1>
        <p><a href="/index" th:href="@{/index}">Back to home page</a></p>
    </body>
</html>

5、配置日志打印

application.properties

logging.level.org.springframework.security=DEBUG

6、权限配置 WebSecurityConfig.java

需要说明的是,本例限定了登录名和密码,以及权限。没有加密措施,页不支持动态权限,代码还是比较容易看懂的。

com.bestcxx.stu.springbootsecurity.security.config 下 WebSecurityConfig.java

package com.bestcxx.stu.springbootsecurity.security.config;

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("/css/**", "/index").permitAll()//无需权限即可访问的路径
				.antMatchers("/user/**").hasRole("USER")//需要权限才可以访问的路径
				.and()
				.formLogin().loginPage("/login").failureUrl("/login-error");//登陆页面和失败登陆页面
		}
		
		@Autowired
		public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
			auth.inMemoryAuthentication()
				.withUser("user")//登陆验证用户名
				.password("password")//登陆验证密码
				.roles("USER");//使用该用户名和密码赋予的角色为 USER
		}
		
}

7、controller类的编写

com.bestcxx.stu.springbootsecurity.controller 包下 HomeController.java

package com.bestcxx.stu.springbootsecurity.controller;

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

@Controller
public class HomeController {
	
	//默认页
	@RequestMapping("/")
	public String root() {
		return "redirect:/index";
	}

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

	//用户登陆成功页-如果未登陆返回登陆页,否则返回登陆成功页
	@RequestMapping("/user/index")
	public String userIndex() {
		return "user/index";
	}

	//登陆页
	@RequestMapping("/login")
	public String login() {
		return "login";
	}

	//登陆失败
	@RequestMapping("/login-error")
	public String loginError(Model model) {
		model.addAttribute("loginError", true);
		return "login";
	}
	
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值