Spring Boot是一个基于Spring框架的快速开发平台,它提供了许多开箱即用的功能,包括用户认证和授权。在Spring Boot中实现用户认证授权,通常使用Spring Security框架。下面是一个简单的示例,展示如何在Spring Boot项目中实现用户认证和授权。
首先,在你的pom.xml
文件中添加Spring Security的依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
创建一个配置类来设置Spring Security。以下是一个简单的示例:
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
// 添加CSRF过滤器
http.csrf().disable();
// 添加自定义的认证过滤器
http.addFilterBefore(new CustomAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
创建一个自定义的认证过滤器,用于处理用户登录请求。以下是一个简单的示例:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationException("Authentication method not supported: " + request.getMethod()) {};
}
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
CustomAuthenticationToken authRequest = new CustomAuthenticationToken(username, password);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
创建一个自定义的认证令牌类,继承自UsernamePasswordAuthenticationToken
。以下是一个简单的示例:
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
public class CustomAuthenticationToken extends UsernamePasswordAuthenticationToken {
public CustomAuthenticationToken(String principal, String credentials) {
super(principal, credentials);
}
}
创建一个简单的登录页面/login
,可以使用Thymeleaf或其他模板引擎来创建。以下是一个简单的Thymeleaf示例:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="/login">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required /><br/>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required /><br/>
<button type="submit">Login</button>
</form>
</body>
</html>
创建一个控制器来处理登录页面和其他请求。以下是一个简单的示例:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/public")
public String publicPage() {
return "public";
}
}
现在你可以运行你的Spring Boot应用程序,并尝试访问/login
和/public
两个页面。访问/login
页面进行登录,登录成功后可以访问/public
页面。
以上就是一个简单的Spring Boot用户认证和授权的示例。你可以根据实际需求进行扩展和修改。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。