02 springboot与springsecurity的整合

上一节我们了解了spring与springsecurity的配置整合,在大多数使用中,人们都还是用springboot去整合springsecurity。这一节,我们将看一下springboot与springsecurity的整合。

1、环境约束

  • idea2018.1
  • maven3.6.1

2、操作步骤

  • 创建一个springboot项目,假设名称为springsecuritydemo,pom.xml内容如下:


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.2.RELEASE
         
    
    net.wanho
    springsecuritydemo
    0.0.1-SNAPSHOT
    springsecuritydemo
    Demo project for Spring Boot

    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.security
            spring-security-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-security
        
    

    
        1.8
    

    
        
            spring-releases
            Spring Releases
            https://repo.spring.io/libs-release
        
    
    
        
            spring-releases
            Spring Releases
            https://repo.spring.io/libs-release
        
    


2.1 使用springsecurity的默认界面

springsecurity提供了默认的登录页面,尽管我们根本不会去用。

  • 启动,测试,访问 http://localhost:8080/abcd,会跳转到以下页面:
    自带登录页面

2.2 配置约束路径和固定账号密码

  • 在项目/src/resources/templates文件夹下创建文件:
    login.html



    
    home





index.html




    Hello World!


Hello [[${#httpServletRequest.remoteUser}]]!

error.html




    Hello World!


出错了或者没权限
去登录


  • 在项目/src/main/java文件夹下创建MvcConfig.java

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 MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/login").setViewName("login");
    }

}
  • 在项目/src/main/java文件夹下创建WebSecurityConfig.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/login").permitAll()
                .antMatchers("/**").hasRole("USER")
                .and()
                .csrf().disable()//关闭CSRF
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/form")
                .defaultSuccessUrl("/index") //成功登陆后跳转页面
                .failureUrl("/loginError").permitAll();
    }



    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
                .withUser("ali").password("123456").roles("USER")
                .and()
                .withUser("xiaoli").password("123456").roles("ADMIN");
}
  • 启动,测试
    1,访问http://localhost:8080/abcd,跳转到以下页面:
    跳转到登录页面

    2,输入xiaoli/123456,点击登录,跳转到以下页面:
    没有权限

    3,重新登陆,输入xiaoli/123456,点击登录,跳转到以下页面:
    登录成功

2.3 从“数据库”中获取密码

之所以将数据库加密码是因为我们并没有真的去查数据库,而是固定的账号密码。

  • 在项目/src/main/java文件夹下创建Role.java

public class Role {
    private long id;
    private String name;

    public Role(long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Role() {
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • 在项目/src/main/java文件夹下创建User.java

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.List;

public class User implements UserDetails {
    private Long id;
    private String username;
    private String password;
    private List roles;

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() { // 帐户是否过期
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() { // 帐户是否被冻结
        return true;
    }

    // 帐户密码是否过期,一般有的密码要求性高的系统会使用到,比较每隔一段时间就要求用户重置密码
    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {  // 帐号是否可用
        return true;
    }

    @Override
    @JsonIgnore
    public List getAuthorities() {
        List authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List getRoles() {
        return roles;
    }

    public void setRoles(List roles) {
        this.roles = roles;
    }

}
  • 在项目/src/main/java文件夹下创建MyUserDetailsService.java

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (username.equals("admin")) {
            //假设返回的用户信息如下,这里本应该去查数据库,但我们的关注点不在存储,所以这里写固定了
            User userInfo = new User();
            userInfo.setUsername("admin");
            userInfo.setPassword("123456");
            Role role = new Role(1L, "USER");
            List list = new ArrayList();
            list.add(role);
            userInfo.setRoles(list);
            return userInfo;
        }
        return null;
    }
}
  • 在项目/src/main/java文件夹下创建MyAuthenticationProvider.java

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private UserDetailsService userDetailService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName();// 这个获取表单输入中返回的用户名;
        String password = (String) authentication.getCredentials();// 这个是表单中输入的密码;
        User userInfo = (User) userDetailService.loadUserByUsername(userName); // 这里调用我们的自己写的获取用户的方法;
        if (userInfo == null) {
            throw new BadCredentialsException("用户名不存在");
        }
        if (!userInfo.getPassword().equals(password)) {
            throw new BadCredentialsException("密码不正确");
        }
        Collection authorities = userInfo.getAuthorities();
        return new UsernamePasswordAuthenticationToken(userInfo, password, authorities);
    }

    @Override
    public boolean supports(Class authentication) {
        return true;
    }
}
  • 修改WebSecurityConfig.java

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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/login").permitAll()
                .antMatchers("/**").hasRole("USER")
                .and()
                .csrf().disable()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/form")
                .defaultSuccessUrl("/index")
                .failureUrl("/error").permitAll();
    }


    @Resource
    MyAuthenticationProvider provider;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(provider);
    }
}
  • 启动,测试
    1,访问http://localhost:8080/abcd,出现以下界面:
    跳转到登录页面

    2,输入admin/123456,点击登录,出现以下界面:
    登陆成功页面

    3,再次访问http://localhost:8080/abcd,出现以下页面:
    已经登录但是没权限

    至此,我们完成了springboot与springsecurity的整合。

你可能感兴趣的:(02 springboot与springsecurity的整合)