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