本篇博客仅记录,为了方便以后的复习,如果有错误,还请博友指出
新建一个config包,放置各种配置
新建SecurityConfig配置类
package com.drc.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import javax.sql.DataSource;
@Configuration
public class SecurityConfigTest1 extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private DataSource dataSource; // 注入数据源
// 配置对象,这个是配置自动登录
@Bean
public PersistentTokenRepository tokenRepository(){
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
return jdbcTokenRepository;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().accessDeniedPage("/unauth.html"); // 自定义403页面
http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();
http.formLogin() // 自定义自己编写的登录界面
.loginPage("/login.html") // 登录页面设置
.loginProcessingUrl("/user/login") // 登录访问路径(有一个就行,这个逻辑不需要我们做,SpringSecurity帮我们做)
.defaultSuccessUrl("/success.html").permitAll() // 登录成功后,跳转的路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/user/login").permitAll() // 设置哪些路径可以直接访问,不需要认证
.antMatchers("/test/index").hasAnyAuthority("admin")
.anyRequest().authenticated()
.and().rememberMe().tokenRepository(tokenRepository())
.tokenValiditySeconds(60) // 设置token时长
.userDetailsService(userDetailsService) // 调用service操作数据库
.and().csrf().disable(); // 关闭csrf的防护
}
}
mapper层代码
package com.drc.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.drc.bean.Users;
import org.springframework.stereotype.Repository;
@Repository // 继承了mybatisplus里面的BaseMapper
public interface UserMapper extends BaseMapper<Users> {
}
service层代码
package com.drc.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drc.bean.Users;
import com.drc.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 使用的是MybatisPlus
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username",username);
Users users = userMapper.selectOne(wrapper);
if (users == null) {
throw new UsernameNotFoundException("用户名不存在,请输入正确的用户名");
}
// 角色的添加
List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("admins");
return new User(users.getUsername(),
new BCryptPasswordEncoder().encode(users.getPassword()),
role);
}
}
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/user/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
记住我:<input type="checkbox" name="remember-me"><br><!-- name必须为remember-me -->
<input type="submit" value="登录" >
</form>
</body>
</html>
文章结束,为了方便以后的复习,写了这篇博客,如有错误,请大家指正!