在SpringBoot中使用StandardPasswordEncoder [英] Using StandardPasswordEncoder in SpringBoot

查看:345
本文介绍了在SpringBoot中使用StandardPasswordEncoder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎和包作为可执行JAR文件生成了一个Spring Boot Web应用程序。



使用的技术: / p>

Spring Boot 1.4.2.RELEASE,Spring 4.3.4.RELEASE,Thymeleaf 2.1.5.RELEASE,Tomcat Embed 8.5.6,Maven 3,Java 8



这是我的安全配置类:

  @Configuration 
@ EnableWebSecurity
@PropertySource(classpath:/ config / app - $ {APP-KEY} .properties)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Value($ { securityConfig.formLogin.loginPage})
private String loginPage;

@Bean
public StandardPasswordEncoder encoder(){
返回新的StandardPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http)throws异常{

http
.formLogin()

.permitAll()
.loginProcessingUrl(/ tdk / login)
.failureUrl(/ tdk / login?error = true)
。 defaultSuccessUrl(/ events / list)
.and()
.exceptionHandling()
.accessDeniedPage(/ denied)
.and()
。 authorizeRequests()
.antMatchers(/ resources / **)。permitAll()
.antMatchers(/ mockup / **)。permitAll()
.antMatchers(用户/ **)。permitAll()
.antMatchers(/ books / **)。permitAll()
.antMatchers(/ welcome / **)。authenticated()
.and()
.logout()
.permitAll()
.logoutSuccessUrl( / index.html中);
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(new标准密码Encoder())
.withUser(test1)。password(c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae)角色(ADMIN)和()
.withUser(test2)。 ).roles(USER)。和()
.withUser(test3)。password(test3)。roles(SUPERADMIN);
}


@Bean
public static PropertySourcesPlaceholderConfigurer propertyDefaultConfig(){
return new PropertySourcesPlaceholderConfigurer();
}
}

这是我的Junit测试正常工作

  public class StandardPasswordEncoderTests {

@Test
public void getPasswordForTest1(){
StandardPasswordEncoder encoder = new StandardPasswordEncoder();
String password =test1;

assertTrue(
encoder.matches(password,c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae));

}
}

这里我的登录模板

 < form th:action =@ {/ tdk / login}method =post> 

< p th:if =$ {param.error}>
不良凭证$ {param.error}
< / p>

< p th:if =$ {loginError}class =error>用户或密码错误< / p>

< div class =input_label>< i class =fa fa-user>< / i>< input type =textname =user =User/>< / div>
< div class =input_label>< i class =fa fa-key>< / i>< input type =passwordname =passplaceholder =Password />< / DIV>
< input type =submitvalue =LOGIN/>
< / form>

但无论我放在哪里:

  test1 / c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae 

  test2 / test2 

我看到消息我的模板输出中的错误凭证$ {param.error}

解决方案



您可以将Spring Security配置更改为使用参数您的登录页面的名称。或者您可以更改登录页面以使用默认参数名称。



请参阅 FormLoginConfigurer#usernameParameter


执行身份验证时要查找用户名的HTTP参数。默认为username。


FormLoginConfigurer#passwordParameter


执行身份验证时要查找密码的HTTP参数。默认为密码。


您修改的登录页面(默认参数名称):

 < form th:action =@ {/ tdk / login}method =post> 
< p th:if =$ {param.error}>
不良凭证$ {param.error}
< / p>

< p th:if =$ {loginError}class =error>用户或密码错误< / p>

< div class =input_label>
< i class =fa fa-user>< / i>
< input type =textname =usernameplaceholder =User/>
< / div>
< div class =input_label>
< i class =fa fa-key>< / i>
< input type =passwordname =passwordplaceholder =Password/>
< / div>
< input type =submitvalue =LOGIN/>
< / form>


I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

Technologies used:

Spring Boot 1.4.2.RELEASE, Spring 4.3.4.RELEASE, Thymeleaf 2.1.5.RELEASE, Tomcat Embed 8.5.6, Maven 3, Java 8

This is my security config class:

@Configuration
@EnableWebSecurity
@PropertySource("classpath:/config/app-${APP-KEY}.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${securityConfig.formLogin.loginPage}")
    private String loginPage;

    @Bean
    public StandardPasswordEncoder encoder() {
        return new StandardPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .formLogin()
                .loginPage(loginPage)
                .permitAll()
                .loginProcessingUrl("/tdk/login")
                .failureUrl("/tdk/login?error=true")
                .defaultSuccessUrl("/events/list")
                .and()
            .exceptionHandling()
                .accessDeniedPage("/denied")
                .and()
            .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .antMatchers("/mockup/**").permitAll()
                .antMatchers("/users/**").permitAll()
                .antMatchers("/books/**").permitAll()
                .antMatchers("/welcome/**").authenticated()
                .and()
            .logout()
                .permitAll()
                .logoutSuccessUrl("/index.html");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .passwordEncoder(new StandardPasswordEncoder())
                .withUser("test1").password("c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae").roles("ADMIN").and()
                .withUser("test2").password("test2").roles("USER").and()
                .withUser("test3").password("test3").roles("SUPERADMIN");
    }


    @Bean
    public  static PropertySourcesPlaceholderConfigurer propertyDefaultConfig() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

This is my Junit Tests that works properly

public class StandardPasswordEncoderTests {

    @Test
    public void getPasswordForTest1() {
        StandardPasswordEncoder encoder = new StandardPasswordEncoder();
        String password = "test1";

        assertTrue(
                encoder.matches(password, "c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae"));

    }
}

Here my login template

<form th:action="@{/tdk/login}" method="post">

            <p th:if="${param.error}">
                Bad Credentials  ${param.error}
            </p>

                <p th:if="${loginError}" class="error">Wrong user or password</p>

                <div class="input_label"><i class="fa fa-user"></i><input type="text" name="user" placeholder="User" /></div>
                <div class="input_label"><i class="fa fa-key"></i><input type="password" name="pass" placeholder="Password" /></div>                      
                <input type="submit" value="LOGIN" />
             </form>

But whatever I put:

test1 / c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae

or

test2 / test2 

I see the message Bad Credentials ${param.error} in the output of my template

解决方案

The parameter names for username and password in your login page are not matching the names in Spring Security configuration.

You could change the Spring Security configuration to use the parameter names from your login page. Or you could change the login page to use the default parameter names.

See FormLoginConfigurer#usernameParameter:

The HTTP parameter to look for the username when performing authentication. Default is "username".

and FormLoginConfigurer#passwordParameter:

The HTTP parameter to look for the password when performing authentication. Default is "password".

Your modified login page (with default parameter names):

<form th:action="@{/tdk/login}" method="post">
    <p th:if="${param.error}">
        Bad Credentials  ${param.error}
    </p>

    <p th:if="${loginError}" class="error">Wrong user or password</p>

    <div class="input_label">
         <i class="fa fa-user"></i>
         <input type="text" name="username" placeholder="User" />
    </div>
    <div class="input_label">
         <i class="fa fa-key"></i>
         <input type="password" name="password" placeholder="Password" />
    </div>                      
    <input type="submit" value="LOGIN" />
</form>

这篇关于在SpringBoot中使用StandardPasswordEncoder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆