springboot security 登录接口
时间: 2023-07-24 17:21:20 浏览: 44
Spring Security 提供了一个登录认证的框架,可以轻松地实现登录认证功能。下面是一个简单的 Spring Boot Security 的登录接口示例。
首先,需要在 `pom.xml` 文件中添加 Spring Boot Security 的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后,在 Spring Boot 应用程序的主类上添加 `@EnableWebSecurity` 注释来启用 Spring Security 的 Web 安全功能。并创建一个实现了 `UserDetailsService` 接口的类,用于获取用户信息。
```java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").defaultSuccessUrl("/home").permitAll()
.and().logout().permitAll();
}
}
```
在登录页面需要提供一个表单,通过 POST 请求发送到 `/login` 接口。
```html
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Log In"/>
</div>
</form>
```
在服务器端,需要实现 `/login` 接口,用于接收登录请求并进行认证。
```java
@RestController
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam String username, @RequestParam String password) {
// 进行用户认证
Authentication authentication = new UsernamePasswordAuthenticationToken(username, password);
Authentication result = authenticationManager.authenticate(authentication);
SecurityContextHolder.getContext().setAuthentication(result);
return "Success";
}
}
```
以上代码仅提供了一个简单的 Spring Boot Security 的登录接口示例,实际上还需要更多的代码来实现完整的安全功能。