美文网首页
SpringBoot整合Spring Security手动配置用

SpringBoot整合Spring Security手动配置用

作者: 伍陆柒_ | 来源:发表于2019-10-18 10:15 被阅读0次

    部分引自 www.javaboy.org

    手动配置用户名密码有两种方式

    1.配置文件的方式

    application.properties

    spring.security.user.name=yzn
    spring.security.user.password=123
    spring.security.user.roles=admin
    

    启动测试

    2.采取java代码配置

    application.properties中配置注释掉,新建config目录,新建配置类

    package org.javaboy.security.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("yzn").password("123").roles("admin")
                    .and()
                    .withUser("test").password("123").roles("user");
        }
    }
    

    这种方式本来是没有问题的,但是Spring5以后需要对密码进行加密,否则无法正确登录
    为了演示方便,我先不加密,但需要使用一个过期方法

    package org.javaboy.security.config;
    
    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.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.password.NoOpPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("yzn").password("123").roles("admin")
                    .and()
                    .withUser("test").password("123").roles("user");
        }
    
        @Bean
        PasswordEncoder passwordEncoder(){
            return NoOpPasswordEncoder.getInstance();
        }
    }
    

    但两种方式都是写死的,项目中应该结合数据库动态管理

    相关文章

      网友评论

          本文标题:SpringBoot整合Spring Security手动配置用

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