【问题标题】:How to display a page only, if certain parameters are provided in the URL?如果 URL 中提供了某些参数,如何仅显示页面?
【发布时间】:2019-05-29 10:16:14
【问题描述】:

我想在 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: 按照建议使用 return ClassPathResource("main.html") here 没有帮助。

【问题讨论】:

    标签: java spring spring-boot authentication kotlin


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      您不应该以这种方式来确保您的安全。通过 http 以明文形式发送密码不是一个好习惯。

      这里有使用 spring security 的基本身份验证示例。

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

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

      如果您按照本教程进行操作,那么您可以为初学者分配一个内存用户。然后您可以将您的身份验证详细信息 Base64Encode 编码给用户。然后对于每个用户,您可以发送身份验证详细信息,并且没有人可以在用户名和密码通过网络时窥探它们,并且您的请求在到达您的控制器之前得到处理。这样,您可以将业务逻辑与身份验证分离。

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

      【讨论】:

      • 我想以这种方式实现身份验证是有原因的。问题在于有条件地显示静态内容,而不是改变安全方法。
      • 您介意详细说明您的理由,以便我们进一步帮助您吗?出于任何原因想要以这种方式实现 Spring 安全性并没有真正遵循。如果您绝对需要这样做,您可以在每次向您提供错误密码时使用 Controller Advice 引发异常。您如何验证密码取决于您,尽管是数据库或其他。要在成功验证网页后返回,请返回“index.html”或您想要的任何页面,这将为您提供页面。
      • 原因是我想创建尽可能简单的原型。如果您的程序仅在本地计算机上运行,​​那么浪费大量时间开发复杂的安全系统,解决 Spring 安全问题将是愚蠢的。对于我的当前目的,基于电子邮件的身份验证就足够了。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多