当一个系统建立之后,通常需要适当地做一些权限控制,使得不同用户具有不同的权限操作系统。
用户自定义访问控制
- 实际生产中,网站访问多是基于HTTP请求的,我们可以通过重写WebSecurityConfigurerAdapter类的configure(HTTPSecurity http)方法来对基于Http的请求访问进行控制。
- configure(HttpSecurity http)方法的参数类型是HttpSecurity类,该类提供了Http请求的限制以及权限、Session管理配置、CSRF跨站请求问题。
authorizeRequest() |
开启基于HttpServletRequest请求访问的控制 |
formLgoin() |
开启基于表单的用户登录 |
httpBasic() |
开启基于HTTP请求的Basic认证登录 |
logout() |
开启退出登录的支持 |
sessionManagement() |
开启Session管理配置 |
rememberMe() |
开启记住我功能 |
csrf() |
配置CSRF跨站请求伪造防护功能 |
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/detail/common/**").hasRole("common")
.antMatchers("/detail/vip/**").hasRole("vip")
.and()
.formLogin();
}
- 测试,登录首页,进入common和vip页面会提示登录,根据权限控制访问部分。
自定义用户登录
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登录界面</title>
<link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" th:action="@{/userLogin}" th:method="post" >
<img class="mb-4" th:src="@{/login/img/login.jpg}" width="72px" height="72px">
<h1 class="h3 mb-3 font-weight-normal">请登录</h1>
<div th:if="${param.error}" style="color: red;height: 40px;text-align: left;font-size: 1.1em">
<img th:src="@{/login/img/loginError.jpg}" width="20px">用户名或密码错误,请重新登录!
</div>
<input type="text" name="name" class="form-control" placeholder="用户名" required="" autofocus