springsecurity03web
配置ymlorg.springframework.boot spring-boot-starter-securityorg.springframework.boot spring-boot-starter-thymeleaforg.springframework.boot spring-boot-starter-weborg.thymeleaf.extras thymeleaf-extras-springsecurity5com.alibaba druid-spring-boot-starter1.2.5 mysql mysql-connector-java5.1.49 org.mybatis.spring.boot mybatis-spring-boot-starter2.1.4 org.projectlombok lomboktrue org.springframework.boot spring-boot-starter-testtest org.springframework.security spring-security-testtest
server:
port: 8001
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
river-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# security:
# user:
# name: root
# password: root
#关闭thymeleaf缓存
thymeleaf:
cache: false
#Mybatis设置
mybatis:
type-aliases-package: com.hb.entity
mapper-locations: classpath*:mapper
//需要实现UserDetailService,需要返回一个UserDetail,为了能对应上所以实现UserDetail
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;//账户是否激活
private Boolean accountNonExpired;//账户是否过期
private Boolean accountNonLocked;//账户是否锁定
private Boolean credentialsNonExpired;//密码是都过期
private List role=new ArrayList<>();//关系属性,用来存储当前用户所有角色信息
//返回权限信息
@Override
public Collection extends GrantedAuthority> getAuthorities() {
Set auth = new HashSet<>();
role.forEach(role->{
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role.getName());
auth.add(simpleGrantedAuthority);
});
return null;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}
@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}
@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
@Override
public boolean isEnabled() {
return enabled;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List getRole() {
return role;
}
public void setRole(List role) {
this.role = role;
}
}
Role类
import lombok.Data;
//角色类
@Data
public class Role {
private Integer id;
private String name;
private String nameZh;
}
DAO层
@Mapper
public interface UserDao {
//根据用户名返回用户方法
User loadUserByUserName(String username);
//提供根据用户id查询用户角色信息方法
List getRoleByUid(Integer id);
}
xml
Serviceselect id, username, password, enabled, accountNonExpired, accountNonLocked, credentialsNonExpired from user where username=#{username}
重写loadUserByUsername方法
@Service
public class UserService implements UserDetailsService {
@Autowired
UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.loadUserByUserName(username);
//查询用户
if(ObjectUtils.isEmpty(user))throw new UsernameNotFoundException("用户名不正确");
//查询权限信息
List roleByUid = userDao.getRoleByUid(user.getId());
user.setRole(roleByUid);
return user;
}
}
自定义security相关配置
编写mvc相关配置,这样我们就不需要在controller中写跳转登陆页面了
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
//页面跳转
public class MvcConfigure implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login.html").setViewName("login");
registry.addViewController("/index.html").setViewName("index");
}
}
编写SecurityConfigure配置类
- configure(HttpSecurity http) 用来传UserService可以覆盖原有的
- configure(AuthenticationManagerBuilder auth)自定义配置全局的AuthenticationManager
import com.hb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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;
@Configuration
public class SecurityConfigure extends WebSecurityConfigurerAdapter {
//数据库实现
@Autowired
UserService userService;
//全局AuthenticationManager
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//登陆页面login.html需要放行
.mvcMatchers("/login.html").permitAll()
//所有请求开启认证
.anyRequest().authenticated()
.and()
//开启表单认证,就是上面一开始说的login页面
.formLogin()
//指定自定义登录页面,如果没有自定义的话就会跳转到springsecurity自己提供的
.loginPage("/login.html")
//指定登录的url
.loginProcessingUrl("/dologin")
//加个true,表示成功登录后总是跳转到这个页面
.defaultSuccessUrl("/index.html",true)
//失败后重定向到登录页面
.failureUrl("/login.html")
.and()
.logout()//开启退出登录
.logoutUrl("/logout")
//退出成功后,跳转到login.html
.logoutSuccessUrl("/login.html")
.and()
.csrf().disable();//关闭csrf
}
}
结果
登陆成功
输入错误的密码
返回错误信息



