springsecurity自带的登录
时间: 2023-11-21 15:58:49 浏览: 39
以下是Spring Security自带的登录的介绍和示例:
Spring Security是一个基于Spring框架的安全框架,它提供了一套完整的安全解决方案,包括认证、授权、攻击防护等功能。Spring Security自带的登录功能可以让用户在登录后记住用户信息,下次访问时自动登录。
要使用Spring Security自带的登录功能,需要进行如下配置:
1.在pom.xml文件中添加Spring Security依赖:
```xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.5.0</version>
</dependency>
```
2.在Spring Security的配置类中添加如下代码:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.rememberMe()
.and()
.logout()
.logoutSuccessUrl("/login")
.permitAll()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
3.在Spring Security的配置类中添加一个UserDetailsService的实现类,用于从数据库中获取用户信息:
```java
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}
}
```
4.在登录页面中添加如下代码:
```html
<form action="/login" method="post">
<div>
<label for="username">用户名:</label>
<input type="text" id="username" name="username" />
</div>
<div>
<label for="password">密码:</label>
<input type="password" id="password" name="password" />
</div>
<div>
<input type="checkbox" id="remember-me" name="remember-me" />
<label for="remember-me">记住我</label>
</div>
<div>
<button type="submit">登录</button>
</div>
</form>
```
5.在Spring Security的配置类中添加一个/login接口,用于处理登录请求:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// ...
@Override
protected void configure(HttpSecurity http) throws Exception {
// ...
http.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/")
.failureUrl("/login?error=true")
.permitAll();
// ...
}
}
```
以上就是Spring Security自带的登录功能的介绍和示例。