通过修改Security的配置来实现 参考:https://docs.spring.io/spring-security/site/docs/current/guides/html5//helloworld-boot.html#creating-your-spring-security-configuration
@EnableWebSecurity
public class SecurityConfig 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");
}
}
与/ css / **和/ index匹配的请求是完全可访问的 | |
与/ user / **匹配的请求要求用户进行身份验证,并且必须与USER角色相关联 | |
使用自定义登录页面和失败URL启用基于表单的身份验证 |
显示用户名
现在我们已经过身份验证,让我们更新应用程序以显示用户名。使用以下内容更新/index.html的完整内容:
SRC /主/资源/模板/ 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-springsecurity5">
<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>
我们使用Thymeleaf作为视图模板引擎和 Thymeleaf - Spring Security集成模块 ,以便使用sec:authentication和sec:authorize属性。 |
如果当前用户已经过身份验证,则显示Thymeleaf片段(DOM节点)。 | |
显示当前已验证的主体的名称。 | |
显示当前已验证的主体的权限。 | |
注销表格。 |
Thymeleaf会自动将CSRF令牌添加到我们的注销表单中。如果我们没有使用Thymleaf或Spring MVC taglib,我们也可以使用手动添加CSRF令牌<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> 。 |
更新安全页面
最后一步是更新安全页面以显示当前已验证的主体。使用以下内容更新/user/index.html的完整内容:
SRC /主/资源/模板/用户/ 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>
启动服务器并尝试访问http:// localhost:8080 /以查看我们的应用程序的更新。