1. 程式人生 > 實用技巧 >SpringBoot整合SpringSecurity:集中式專案

SpringBoot整合SpringSecurity:集中式專案

程式碼已提交至github:https://github.com/JGZY/springboot-security-family
sql指令碼在resource目錄下,使用者密碼是1234
只實現了部分主要功能(認證授權),增刪改查沒有實現。

pom依賴

注意打包方式要改成war包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>

配置檔案

spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///security_authority?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=1234

mybatis.type-aliases-package=com.wj.springsecurity.domain
mybatis.configuration.map-underscore-to-camel-case=true

logging.level.com.wj.springsecurity.mapper=debug

配置類

@EnableGlobalMethodSecurity(securedEnabled = true)//開啟@Secured註解
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login.jsp","/failer.jsp","/css/**","/img/**","/plugins/**","/favicon.ico").permitAll()
                .antMatchers("/**").hasAnyRole("USER","ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login.jsp").loginProcessingUrl("/login")
                .successForwardUrl("/index.jsp").failureForwardUrl("/failer.jsp")
                .permitAll()
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login.jsp")
                .invalidateHttpSession(true)//是否清空session
                .permitAll()
                .and()
                .csrf().disable();
    }

    /**
     * 認證的來源(記憶體還是資料庫)
     * @param auth
     * @throws Exception
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        //auth.inMemoryAuthentication().withUser("user").password("{noop}1234").roles("USER");
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
}

主啟動類

@MapperScan("com.wj.springsecurity.mapper")
@SpringBootApplication
public class SpringbootSecurityJspApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootSecurityJspApplication.class, args);
    }

}

UserService

實體類

#### SysUser
public class SysUser implements UserDetails {

    private Integer id;
    private String username;
    private String password;
    private Integer status;

    private List<SysRole> roles;

    public List<SysRole> getRoles() {
        return roles;
    }

    public void setRoles(List<SysRole> roles) {
        this.roles = 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 setStatus(Integer status) {
        this.status = status;
    }

    public Integer getId() {
        return id;
    }

    public Integer getStatus() {
        return status;
    }

    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

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

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

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}

SysRole

public class SysRole implements GrantedAuthority {
    private Integer id;
    private String roleName;
    private String roleDesc;

    @JsonIgnore
    @Override
    public String getAuthority() {
        return null;
    }

    public Integer getId() {
        return id;
    }

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

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

}

service

介面

public interface UserService extends UserDetailsService {
}

實現類

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userMapper.findByName(username);
    }
}

Mapper

public interface UserMapper extends Mapper<SysUser> {

    @Select("select * from sys_user where username = #{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roles", column = "id", javaType = List.class,
                many = @Many(select = "com.wj.springsecurity.mapper.RoleMapper.findByUid"))
    })
    public SysUser findByName(String username);
}

public interface RoleMapper extends Mapper<SysRole> {

    @Select("select r.id,r.role_name as roleName,r.role_desc as roleDesc " +
            "from sys_role r , sys_user_role ur " +
            "where uid = #{uid} and r.id = ur.rid")
    public List<SysRole> findByUid(Integer uid);
}

啟動專案

點選m按鈕

輸入:spring-boot:run,按下enter鍵

執行成功

進入http://localhost:8080/login.jsp

使用者名稱:wj

密碼:1234

如果能進入系統,說明搭建整合成功。