Spring security安全框架
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
2.配置SecurityConfig
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserServiceImp userServiceImp;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2") // /level2/**只有vip2才能访问
.antMatchers("/level3/**").hasRole("vip3"); // /level3/**只有vip3才能访问
//没有权限默认跳转到登陆页面,需要开启登陆页面
//http.formLogin();//系统自带的login页面
//设置默认跳转的登陆页面,登陆成功后跳转到首页 这里的tologin是和from里面对应的 username password是前端用户输入的name
http.formLogin().loginPage("/tologin").usernameParameter("username").passwordParameter("password");
http.csrf().disable();//关闭csrf功能,如果不关的话 注销可能会有提示
//注销 注销成功后跳到首页
http.logout().logoutSuccessUrl("/");
//开启记住我功能,自定义接收前端的参数
http.rememberMe().rememberMeParameter("rememberMe");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userServiceImp);
}
//加密方法
@Bean
public BCryptPasswordEncoder bcryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
3.UserServiceImp实现UserDetailsService
@Service
public class UserServiceImp implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userMapper.querUserByName(username);
if (user == null){
throw new UsernameNotFoundException("用户名不存在");
}
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getPerms()));
String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
}
}
4.前端页面
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/tologin}">
<i class="address card icon"></i> 登录
</a>
</div>
<div sec:authorize="isAuthenticated()">
<a class="item">
用户名:<span sec:authentication="name"></span>
</a>
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
</div>
<div class="column" sec:authorize="hasRole('vip1')">
vip1用户才能看得见
</div>