美文网首页
22 springboot中集成springsecurity并使

22 springboot中集成springsecurity并使

作者: lijiaccy | 来源:发表于2018-05-12 23:16 被阅读0次

    项目中使用权限管理,springboot首选就是springsecurity。
    pom.xml

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

    然后就是application配置文件,用的是mysql数据库

    # jdbc_config
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/iptrace?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
    spring.datasource.username=root
    spring.datasource.password=root
    

    表和数据,别问我为什么要这样建,springsecurity就是这样定义的,你写完它会自动提示少这两个表。密码和username一样

    -- ----------------------------
    -- Table structure for users
    -- ----------------------------
    DROP TABLE IF EXISTS `users`;
    CREATE TABLE `users` (
      `username` varchar(50) NOT NULL,
      `password` varchar(100) NOT NULL,
      `enabled` tinyint(1) NOT NULL,
      PRIMARY KEY (`username`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of users   
    -- ----------------------------
    INSERT INTO `users` VALUES ('admin', '$2a$10$CeIYm40M71/THnbCQ0fvGOzjJu7d9GTVKnkXyqXq/bkjQvfW6MoQ6', '1');
    INSERT INTO `users` VALUES ('user', '$2a$10$eEhBAy0wNwiM.WGaqbtXEOrlC6TJcUXHuYKX8RcjxZRNaiCt5kFCy', '1');
    
    -- ----------------------------
    -- Table structure for authorities
    -- ----------------------------
    DROP TABLE IF EXISTS `authorities`;
    CREATE TABLE `authorities` (
      `username` varchar(50) NOT NULL,
      `authority` varchar(50) NOT NULL,
      UNIQUE KEY `ix_auth_username` (`username`,`authority`),
      CONSTRAINT `fk_authorities_users` FOREIGN KEY (`username`) REFERENCES `users` (`username`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of authorities
    -- ----------------------------
    INSERT INTO `authorities` VALUES ('admin', 'ROLE_ADMIN');
    INSERT INTO `authorities` VALUES ('user', 'ROLE_USER');
    

    然后设置security文件

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    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.PasswordEncoder;
    import org.springframework.security.provisioning.JdbcUserDetailsManager;
    import org.springframework.security.provisioning.UserDetailsManager;
    
    import javax.sql.DataSource;
    
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)//开启基于方法的声明式权限控制
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        protected DataSource datasource;
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/js/**", "/css/**", "/img/**", "/**/favicon.ico","/model/**","/picture/**","/plugin/**");
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                .authorizeRequests()
    //               .antMatchers("/").hasRole("ROLE_USER")
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll().successForwardUrl("/phone")
                    .and().rememberMe()
                    .tokenValiditySeconds(2419200).and()
    
                .logout().logoutUrl("/logout")
                    .permitAll();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //内存中创建用户信息和角色
        //auth.inMemoryAuthentication().withUser("user").password("123").roles("USER");
    
        //默认数据库连接,方法在下面
        // auth.userDetailsService(jdbcUserDetailsManager());
    
           //自定义读取用户信息和角色
            auth.jdbcAuthentication().dataSource(datasource)
                    .passwordEncoder(passwordEncoder())
                    .usersByUsernameQuery("select username,password,1 as enabled from users where username=?")
                    .authoritiesByUsernameQuery("select username,authority from authorities where username =?");
        }
    
        /* 采用jdbc方式 */
        public UserDetailsManager jdbcUserDetailsManager() throws Exception {
            JdbcUserDetailsManager userMan = new JdbcUserDetailsManager();
            userMan.setDataSource(datasource);
            return userMan;
        }
    
        //定义密码类型BCryptPasswordEncoder,当然也可以自定义密码类型(以后再说)
        @Bean
        public PasswordEncoder passwordEncoder(){
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            return encoder;
        }
    }
    

    然后在前台就可以使用security标签操作权限了。

    我用的是freemarker模板引擎。继续添加包。

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
        </dependency>
    

    然后主要的是把spring-security-taglibs\4.2.4.RELEASE\spring-security-taglibs-4.2.4.RELEASE.jar!\META-INF\security.tld文件拷出来。放在resources/static/tags/下。

    然后建个freemarker配置类

    import freemarker.ext.jsp.TaglibFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
    
    import javax.annotation.PostConstruct;
    import java.util.ArrayList;
    import java.util.List;
    
    @Configuration
    public class TldConfig extends WebMvcConfigurerAdapter {
    
        @Autowired
        private FreeMarkerConfigurer configurer;
    
        @PostConstruct
        public void freeMarkerConfigurer() {
            List<String> tlds = new ArrayList<String>();
            tlds.add("/static/tags/security.tld");
            TaglibFactory taglibFactory = configurer.getTaglibFactory();
            taglibFactory.setClasspathTlds(tlds);
            if(taglibFactory.getObjectWrapper() == null) {
                taglibFactory.setObjectWrapper(configurer.getConfiguration().getObjectWrapper());
            }
        }
    }
    

    最后在页面头部引用
    <#assign sec=JspTaglibs["http://www.springframework.org/security/tags"]/>

    <@sec.authorize access="hasRole('ADMIN')">
         ***
    </@sec.authorize>
    

    这样的话,只有admin角色的可以查看,user进来看不见。

    相关文章

      网友评论

          本文标题:22 springboot中集成springsecurity并使

          本文链接:https://www.haomeiwen.com/subject/wqxkdftx.html