在 Spring Boot 项目的 pom.xml 文件中添加 Spring Cloud Security 的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>在 Spring Boot 项目的 application.yml 或 application.properties 文件中添加安全规则,以控制访问权限。以下是一个简单的示例:
spring:
security:
user:
name: user
password: password这里我们配置了一个简单的用户名和密码的认证方式。
创建一个安全配置类,继承 WebSecurityConfigurerAdapter 类,实现其中的 configure() 方法。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login?logout")
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}这里我们配置了一个简单的认证规则,只允许经过认证的用户访问其他资源,未认证的用户访问 /login 路径并登录,用户认证信息在内存中设置。
创建一个登录页面,以便用户进行认证。以下是一个简单的登录页面示例:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<div th:if="${param.error}">
<p class="error">Invalid username and password.</p>
</div>
<div th:if="${param.logout}">
<p>You have been logged out.</p>
</div>
<form th:action="@{/login}" method="post">
<div><label>Username: <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>运行应用程序,访问 http://localhost:8080/login 页面,输入用户名和密码,然后成功登录。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。