只要引入security依赖,SpringBoot默认会在工厂中创建AuthenticationManager bean,直接使用即可,但是使用是通过AuthenticationManagerBuilder来使用,如下
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 自定义一个方法,把springboot工厂中默认配置的AuthenticationManager拿出来使用即可
*/
@Autowired
public void authManager(AuthenticationManagerBuilder builder){
System.out.println("默认=="+builder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin();
}
}
对于默认方式,默认工厂中有userDetailsService之后,AuthenticationManager自动会配置userDetailsService,所以使用的时候无需再自定义
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService(){
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
userDetailsManager.createUser(User.withUsername("root").password("root").roles("admin").build());
return userDetailsManager;
}
/*工厂中的AuthenticationManager会自动配置上面的userDetailsService 所以无需自定义
@Autowired
public void authManager(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService());
}*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin();
}
}
重写配置中的configure(AuthenticationManagerBuilder builder)方法,就会覆盖工厂默认的AuthenticationManager bean
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService(){
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
userDetailsManager.createUser(User.withUsername("root").password("root").roles("admin").build());
return userDetailsManager;
}
//自定义
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
//自定义AuthenticationManager后需要手动配置上面的userDetailsService
builder.userDetailsService(userDetailsService());//改的是DaoAuthenticationProvider
//也可通过builder.authenticationProvider()自定authenticationProvider
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin();
}
}
默认的AuthenticationManager,在任何地方都可以注入使用,但是这种自定义方式创建的AuthenticationManager是对象工厂内部本地的一个AuthenticationManager,在其他地方使用,比如我们的controller中注入的时候就会出错,需要我们将自定义的AuthenticationManager暴露出去
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService(){
InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
userDetailsManager.createUser(User.withUsername("root").password("root").roles("admin").build());
return userDetailsManager;
}
//自定义
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
//手动配置上面的userDetailsService
builder.userDetailsService(userDetailsService());//改的是DaoAuthenticationProvider
//也可通过builder.authenticationProvider()自定authenticationProvider
}
//将上面自定义的AuthenticationManager在工厂中暴露,可以在任何位置注入
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin();
}
}
boot整合mybatis流程省略
实体类如下(省略get set)
//角色
public class Role {
private Integer id;
private String name;
private String nameZh;
}
//用户
/**
* 自定义用户类实现UserDetails
* 定义所有set方法
* get方法只需要id和roles就行
*/
public class User implements UserDetails {
private Integer id;
private String username;
private String password;
private Boolean enabled;
private Boolean accountNonLocked;//账号是否被锁
private Boolean accountNonExpired;//账号是否过期
private Boolean credentialsNonExpired;//密码是否过期
private List roles = new ArrayList<>();//当前用户所有角色
//权限信息
@Override
public Collection extends GrantedAuthority> getAuthorities() {
Set authorities = new HashSet<>();
//数据库角色转成权限信息
roles.forEach(role -> {
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role.getName());
authorities.add(simpleGrantedAuthority);
});
return authorities;
}
@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 List getRoles() {
return roles;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public void setAccountNonLocked(Boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public void setAccountNonExpired(Boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public void setCredentialsNonExpired(Boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
public void setRoles(List roles) {
this.roles = roles;
}
}
自定义数据源类
@Component
public class MyUserDetailsService 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 roles = userDao.getRolesByUid(user.getId());
//设置权限 后续直接可通过getAuthorities获取到权限信息
user.setRoles(roles);
return user;
}
}
mapper.xml两个方法
配置类
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
//注入自定义的数据源
@Autowired
private MyUserDetailsService myUserDetailsService;
//自定义AuthenticationManager
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(myUserDetailsService);
}
//暴露自定义的AuthenticationManager
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//=================资源拦截=============
.mvcMatchers("/user/login").permitAll()//permitAll()表示放行资源 无需认证就可访问 必须放在所有认证前
.anyRequest().authenticated()//anyRequest()所有请求 .authenticated()表示所有请求需要认证才能访问
.and().formLogin() //formLogin()表示表单认证
//=================登录界面配置=================
.loginPage("/login.html")//自定义访问登录页面地址
.loginProcessingUrl("/doLogin")//自定义登录请求的url
.usernameParameter("name")//自定义用户名、密码变量名
.passwordParameter("pass")
//=================认证配置=================
.successForwardUrl("/index")//认证成功始终跳转的路径.defaultSuccessUrl("/hello") redirect 重定向跳转 但是优先跳转到请求的路径 ,可以传入第二个参数true总是重定向到hello
.failureForwardUrl("/user/toLoginPage")//认证失败 跳转 错误信息在request中,.failureUrl("/login.html")认证失败 redirect跳转 错误信息在session中
//=================注销相关配置==========================
.and().logout()//开启注销,默认是配置的
.logoutUrl("/user/logout")//注销地址,默认是logout 并且请求方式只能是get
.invalidateHttpSession(true)//清除session信息,默认true
.clearAuthentication(true)//清除认证信息,默认true
.logoutSuccessUrl("/user/toLoginPage")//退出,默认是登录页面地址
.and().csrf().disable();
}
}