spring-mvc - 在 Spring Boot 中使用 StandardPasswordEncoder

标签 spring-mvc authentication spring-boot encoding spring-security

我使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎生成了一个 Spring Boot Web 应用程序,并将其打包为可执行 JAR 文件。

使用的技术:

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() {
        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();
    }
}

这是我的 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}">
                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>

但是无论我输入什么:

test1 / c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae

test2 / test2 

我在模板的输出中看到消息 Bad Credentials ${param.error}

最佳答案

登录页面中的用户名和密码参数名称与 Spring Security 配置中的名称不匹配。

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

参见FormLoginConfigurer#usernameParameter :

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

FormLoginConfigurer#passwordParameter :

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

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

<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>

关于spring-mvc - 在 Spring Boot 中使用 StandardPasswordEncoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43558125/

相关文章:

spring - @Service 类中的 @Value 属性为 Null

java - 使用 Spring、Swing 和 SQLite 在 Java 中进行用户授权

java - AWS XRay SDK 无法读取 Docker 容器内的环境变量

forms - 有没有办法使用注释在 Spring MVC 上创建带有多个提交按钮的表单?

login - Spring 安全 : Cannot access target page even after successful login

java - 一个字段上有两个 hibernate validator 。仅需选择一项

java - 尝试在 Java 中使用 HttpClient 发送 HTTP Post GraphQL 查询时出现 HTTP 400

java - Jetty 需要 URL 的 SSL 客户端证书

security - session 暴力破解

java - 在启动 spring boot 服务之前等待依赖项加载