您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。