繁体   English   中英

Spring Boot 身份验证有时仅适用于 Google Cloud

[英]Spring boot authentication only works sometimes on Google Cloud

我有一个关于 Spring Security 的教程。 虽然登录在本地主机上运行良好,但在我将其部署到谷歌云后,Spring 安全登录有时才有效。 例如,当我按登录时,有时会出现登录?错误有时不会。

我对这种行为感到非常困惑。

我曾尝试添加 cutom 身份验证,但没有奏效。 即使我输入了 4 个字母的用户名,我也没有得到任何信息(登录页面刷新)或登录(但只有 10 次尝试中的 1 次)。

如果您要在 localhost 中对此进行测试,它将完全正常工作。 虽然: http ://website-live-245110.appspot.com/(gccloud 托管站点)在这里并不总是有效。

CustomAuthenticationProvider.java

package com.spring.authprovider;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider{

    @Autowired
    private ThirdPartyAuthProviderClient thirdPartyAuthProviderClient;

    // one a user logs in, the authentication variable is filled with the details of the authentication
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // when the user logs in to the application, our object will be filled by spring
        String name = authentication.getName();
        Object password = authentication.getCredentials(); //object that encapsulates password that user types 
        // not printing or storing password anyone

        if(thirdPartyAuthProviderClient.shouldAuthenticate(name,password)) {
            // the array list is for roles, because we are not using it now, we are sending it an empty one
            return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
        } else {
            System.out.println("authentication failed for user: " + name);
        }
        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // there are multiple ways of authentication, use use username and password
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

第三方身份验证提供者客户端.java

package com.spring.authprovider;

import org.springframework.stereotype.Component;

@Component
public class ThirdPartyAuthProviderClient {

    //emulates request to third party application
    public boolean shouldAuthenticate(String username, Object password) {
        // 3rd party request to see if user is correct or no or should be logged in
        // user with username with 4 digits can be logged in to the application
        return username.length() == 4;
    }

}

网络安全配置文件

package com.spring;

import org.springframework.beans.factory.annotation.Autowired;
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.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import com.spring.authprovider.CustomAuthenticationProvider;



@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/home", "/time").permitAll() // any request matching /, /home, /time
                                                                                // can be accessed by anyone
                .anyRequest().authenticated() // any other request needs to be authenticated
                .and().authorizeRequests().antMatchers("/admin/**") // only admin can access /admin/anything
                .hasRole("ADMIN")
                .and().formLogin().loginPage("/login") // permit all to form login--- we use loginPage to use custom page
                .permitAll()
                .and().logout() // permit all to form logout
                .permitAll();

    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //specify auth provider
        auth.authenticationProvider(authProvider);
    }

    // configuration of static resources
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/templates/**", "/assets/**");
    }
}

配置文件

package com.spring;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }
}

模板

你好.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Sign Out"/>
        </form>
    </body>
</html>

主页.html


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>

        <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
</html>

登录.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example </title>
    </head>
    <body>
        <div th:if="${param.error}">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}">
            You have been logged out.
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> User Name : <input type="text" name="username"/> </label></div>
            <div><label> Password: <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="Sign In"/></div>
        </form>
    </body>
</html>

我希望它要么在输入 4 个字符的用户名时登录我,要么输出无效的用户名和密码。 错误。 代码在这里: https : //github.com/jeffpascal/Spring-and-springboot/tree/devs/SpringSecurity

我有类似的问题。 我的 Spring-Security 应用程序曾经在本地系统上运行得很好,但是当我将它部署到谷歌云时,身份验证不起作用。

我曾经获得登录页面,但是当我单击登录按钮时,我的浏览器从未收到响应。

我添加了调试日志,可以在 hibernate 的 show-sql 日志中看到用户正在从数据库中检索,但没有进一步。

在保持应用程序启动并运行几分钟后,我看到了以下日志

信息:使用 [SHA1PRNG] 为会话 ID 生成创建 SecureRandom 实例花费了 [260,620] 毫秒。

然后我修改了$JAVA_HOME/jre/lib/security/java.security ,将securerandom.source=file:/dev/random改为securerandom.source=file:/dev/urandom

有关此操作原因的更多详细信息,请参阅

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM