如果网址中提供了某些参数,如何仅显示页面?

时间:2019-05-29 10:16:14

标签: java spring spring-boot authentication kotlin

我想在Spring中创建一个包含url的页面

http://myapp.com/sign-in?email=myemail@provider.com&pw=password

password是用户每次登录时都会通过电子邮件收到的一次性密码。

每当用户访问此页面时,我都希望发生两件事:

  1. 检查所提供的凭据是否正确。
  2. 如果是,则显示页面的HTML内容。

我已经完成了第一部分:

    @Autowired
    private var userRepository: UserRepository? = null

    @GetMapping
    fun signIn(@RequestParam email:String, @RequestParam(name="pw") password:String): RedirectView {
        // Is the password correct?

        // TODO: Read password hash of the user
        val existingUser: Optional<UserInfo>? = userRepository?.findById(email)
        if (existingUser == null) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        if (!existingUser.isPresent) {
            return redirectToErrorPage("Please register with your e-mail address first")
        }
        val hashInDb = existingUser.get().passwordHash
        val hashInParam = PasswordHashCalculator.calculateHash(password)
        if (!hashInDb.equals(hashInParam)) {
            return redirectToErrorPage("Invalid user name and/or password")
        }

        // TODO: Display the main page
        return null
    }

如何显示主页面(src/main/resources/static中的HTML文件),但仅在通过身份验证检查的情况下,才需要更改代码?

更新1:按建议的here使用return ClassPathResource("main.html")无济于事。

3 个答案:

答案 0 :(得分:2)

return ClassPathResource("static/main.html") should answer your question, don't forget to specify `static` folder at the beginning as `ClassPathResource` points to the `resources` folder

答案 1 :(得分:-1)

您不应该这样真正地保护您的安全。在http上以明文形式发送密码不是一个好习惯。

这里有一些使用spring安全性进行基本身份验证的示例。

https://www.baeldung.com/spring-security-basic-authentication

https://www.baeldung.com/securing-a-restful-web-service-with-spring-security

如果您遵循本教程,那么您可以做的是为启动者分配一个内存中用户。然后,您可以对您的身份验证信息进行Base64Encode。然后,对于每个用户,您都可以发送身份验证详细信息,并且没人能窥探用户名和密码,因为用户名和密码会一直通过网络,并且您的请求在到达控制器之前都会得到处理。这样,您可以将业务逻辑与身份验证脱钩。

至少这是一个开始。希望这会有所帮助。

答案 2 :(得分:-1)

@RobScully是正确的,您不应该这样处理授权。您可以做的就是启用spring-security并使用spring安全注释来处理这种情况。 使用以下依赖项并设置基本的Spring安全性设置。

诸如@PreAuthorize()之类的注释随后可用于在执行方法之前验证用户特权。如果您坚持,甚至可以将此注释添加到控制器方法中,以在每次请求之前进行验证。

您可以设置和 LDAP服务器或Oauth,甚至可以使用数据库进行身份验证(如果您正在研究演示或其他内容)。

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring-security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring-security.version}</version>
        </dependency>

使用如下所示的配置类来配置安全性:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery(
            "select username,password, enabled from users where username=?")
        .authoritiesByUsernameQuery(
            "select username, role from user_roles where username=?");
    }   

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

      http.authorizeRequests()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')") //To check admin role permission
        .and()
          .formLogin().loginPage("/login").failureUrl("/login?error") //provide failure url
          .usernameParameter("username").passwordParameter("password")
        .and()
          .logout().logoutSuccessUrl("/login?logout") 
        .and()
          .exceptionHandling().accessDeniedPage("/403")
        .and()
        .csrf();
    }
}

此github中的示例项目提供了一个基本设置,您可以在其中使用spring security:

https://github.com/mohchi/spring-security-request-mapping

参考用途: https://www.mkyong.com/spring-security/spring-security-form-login-using-database/